diff --git a/.rustfmt.toml b/.rustfmt.toml index 5c8d931..37dd555 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1 +1,18 @@ -max_width = 80 \ No newline at end of file +edition = "2024" +unstable_features = true + +max_width = 80 +match_arm_blocks = false +match_arm_leading_pipes = "Always" +match_block_trailing_comma = true +imports_granularity = "Module" +newline_style = "Unix" +overflow_delimited_expr = true +enum_discrim_align_threshold = 20 +group_imports = "StdExternalCrate" +struct_field_align_threshold = 5 +trailing_semicolon = true +type_punctuation_density = "Wide" +use_field_init_shorthand = true +use_try_shorthand = true +wrap_comments = true diff --git a/src/main.rs b/src/main.rs index 8a7d069..b394916 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,8 +8,8 @@ fn main() { let now = std::time::Instant::now(); match presets::run(input) { - Ok(()) => {} - Err(e) => println!("{e}"), + | Ok(()) => {}, + | Err(e) => println!("{e}"), } println!("{} milliseconds elapsed", now.elapsed().as_millis()); diff --git a/src/rsprocess/assert/dsl.rs b/src/rsprocess/assert/dsl.rs index 1174f96..2b7e428 100644 --- a/src/rsprocess/assert/dsl.rs +++ b/src/rsprocess/assert/dsl.rs @@ -199,13 +199,13 @@ impl QualifierRestricted { label: &'a mut label::Label, ) -> &'a mut set::Set { match self { - Self::Entities => &mut label.available_entities, - Self::Context => &mut label.context, - Self::Reactants => &mut label.reactants, - Self::ReactantsAbsent => &mut label.reactants_absent, - Self::Inhibitors => &mut label.inhibitors, - Self::InhibitorsPresent => &mut label.inhibitors_present, - Self::Products => &mut label.products, + | Self::Entities => &mut label.available_entities, + | Self::Context => &mut label.context, + | Self::Reactants => &mut label.reactants, + | Self::ReactantsAbsent => &mut label.reactants_absent, + | Self::Inhibitors => &mut label.inhibitors, + | Self::InhibitorsPresent => &mut label.inhibitors_present, + | Self::Products => &mut label.products, } } @@ -214,13 +214,13 @@ impl QualifierRestricted { label: &'a label::Label, ) -> &'a set::Set { match self { - Self::Entities => &label.available_entities, - Self::Context => &label.context, - Self::Reactants => &label.reactants, - Self::ReactantsAbsent => &label.reactants_absent, - Self::Inhibitors => &label.inhibitors, - Self::InhibitorsPresent => &label.inhibitors_present, - Self::Products => &label.products, + | Self::Entities => &label.available_entities, + | Self::Context => &label.context, + | Self::Reactants => &label.reactants, + | Self::ReactantsAbsent => &label.reactants_absent, + | Self::Inhibitors => &label.inhibitors, + | Self::InhibitorsPresent => &label.inhibitors_present, + | Self::Products => &label.products, } } @@ -232,13 +232,11 @@ impl QualifierRestricted { impl QualifierLabel { pub(super) fn get(&self, l: &label::Label) -> AssertReturnValue { match self { - QualifierLabel::AvailableEntities => { - AssertReturnValue::Set(l.t.clone()) - } - QualifierLabel::AllReactants => { - AssertReturnValue::Set(l.reactants.union(&l.reactants_absent)) - } - QualifierLabel::AllInhibitors => AssertReturnValue::Set( + | QualifierLabel::AvailableEntities => + AssertReturnValue::Set(l.t.clone()), + | QualifierLabel::AllReactants => + AssertReturnValue::Set(l.reactants.union(&l.reactants_absent)), + | QualifierLabel::AllInhibitors => AssertReturnValue::Set( l.inhibitors.union(&l.inhibitors_present), ), } @@ -248,12 +246,10 @@ impl QualifierLabel { impl QualifierSystem { pub(super) fn get(&self, l: &system::System) -> AssertReturnValue { match self { - Self::Context => { - AssertReturnValue::Context(l.context_process.clone()) - } - Self::Entities => { - AssertReturnValue::Set(l.available_entities.clone()) - } + | Self::Context => + AssertReturnValue::Context(l.context_process.clone()), + | Self::Entities => + AssertReturnValue::Set(l.available_entities.clone()), } } } @@ -261,8 +257,8 @@ impl QualifierSystem { impl Unary { pub(super) fn is_prefix(&self) -> bool { match self { - Self::Not | Self::Rand => true, - Self::Empty + | Self::Not | Self::Rand => true, + | Self::Empty | Self::Length | Self::ToStr | Self::Qualifier(_) @@ -279,40 +275,37 @@ impl Unary { type_exp: &AssertionTypes, ) -> Result { match (self, type_exp) { - (Self::Not, AssertionTypes::Boolean) => Ok(AssertionTypes::Boolean), - (Self::Rand, AssertionTypes::Integer) => { - Ok(AssertionTypes::Integer) - } - (Self::Empty, AssertionTypes::Set) => Ok(AssertionTypes::Boolean), - (Self::Length, AssertionTypes::Set) - | (Self::Length, AssertionTypes::String) => { - Ok(AssertionTypes::Integer) - } - (Self::ToStr, AssertionTypes::Boolean) + | (Self::Not, AssertionTypes::Boolean) => + Ok(AssertionTypes::Boolean), + | (Self::Rand, AssertionTypes::Integer) => + Ok(AssertionTypes::Integer), + | (Self::Empty, AssertionTypes::Set) => Ok(AssertionTypes::Boolean), + | (Self::Length, AssertionTypes::Set) + | (Self::Length, AssertionTypes::String) => + Ok(AssertionTypes::Integer), + | (Self::ToStr, AssertionTypes::Boolean) | (Self::ToStr, AssertionTypes::Element) - | (Self::ToStr, AssertionTypes::Integer) => { - Ok(AssertionTypes::String) - } - (Self::Qualifier(Qualifier::Label(_)), AssertionTypes::Label) => { - Ok(AssertionTypes::Set) - } - ( + | (Self::ToStr, AssertionTypes::Integer) => + Ok(AssertionTypes::String), + | (Self::Qualifier(Qualifier::Label(_)), AssertionTypes::Label) => + Ok(AssertionTypes::Set), + | ( Self::Qualifier(Qualifier::Restricted(_)), AssertionTypes::Label, ) => Ok(AssertionTypes::Set), - (Self::ToEl, AssertionTypes::String) => Ok(AssertionTypes::Element), - (Self::Qualifier(Qualifier::Edge(_)), AssertionTypes::Edge) => { - Ok(AssertionTypes::Node) - } - ( + | (Self::ToEl, AssertionTypes::String) => + Ok(AssertionTypes::Element), + | (Self::Qualifier(Qualifier::Edge(_)), AssertionTypes::Edge) => + Ok(AssertionTypes::Node), + | ( Self::Qualifier(Qualifier::Node(QualifierNode::Neighbours)), AssertionTypes::Node, ) => Ok(AssertionTypes::RangeNeighbours), - ( + | ( Self::Qualifier(Qualifier::System(QualifierSystem::Entities)), AssertionTypes::System, ) => Ok(AssertionTypes::Set), - ( + | ( Self::Qualifier(Qualifier::Restricted( QualifierRestricted::Entities, )), @@ -329,15 +322,15 @@ impl Unary { \".SystemEntities\" and \".SystemContext\" to refer to \ the system fields)." )), - ( + | ( Self::Qualifier(Qualifier::System(QualifierSystem::Context)), AssertionTypes::System, ) => Ok(AssertionTypes::Context), - ( + | ( Self::Qualifier(Qualifier::Node(QualifierNode::System)), AssertionTypes::Node, ) => Ok(AssertionTypes::System), - (op, type_exp) => Err(format!( + | (op, type_exp) => Err(format!( "Expression has incompatible type with operation: type \ {type_exp:?} with operation \"{op:?}\"." )), @@ -348,7 +341,7 @@ impl Unary { impl Binary { pub(super) fn is_prefix(&self) -> bool { match self { - Self::And + | Self::And | Self::Or | Self::Xor | Self::Less @@ -364,7 +357,7 @@ impl Binary { | Self::Quotient | Self::Reminder | Self::Concat => false, - Self::SubStr | Self::Min | Self::Max | Self::CommonSubStr => true, + | Self::SubStr | Self::Min | Self::Max | Self::CommonSubStr => true, } } @@ -374,7 +367,7 @@ impl Binary { pub(super) fn is_infix(&self) -> bool { match self { - Self::And + | Self::And | Self::Or | Self::Xor | Self::Less @@ -390,7 +383,8 @@ impl Binary { | Self::Quotient | Self::Reminder | Self::Concat => true, - Self::SubStr | Self::Min | Self::Max | Self::CommonSubStr => false, + | Self::SubStr | Self::Min | Self::Max | Self::CommonSubStr => + false, } } @@ -400,17 +394,18 @@ impl Binary { t2: &AssertionTypes, ) -> Result { match (self, t1, t2) { - (Self::And, AssertionTypes::Boolean, AssertionTypes::Boolean) - | (Self::Or, AssertionTypes::Boolean, AssertionTypes::Boolean) => { - Ok(AssertionTypes::Boolean) - } - (Self::Xor, AssertionTypes::Boolean, AssertionTypes::Boolean) => { - Ok(AssertionTypes::Boolean) - } - (Self::Xor, AssertionTypes::Set, AssertionTypes::Set) => { - Ok(AssertionTypes::Set) - } - (Self::Less, AssertionTypes::Integer, AssertionTypes::Integer) + | (Self::And, AssertionTypes::Boolean, AssertionTypes::Boolean) + | (Self::Or, AssertionTypes::Boolean, AssertionTypes::Boolean) => + Ok(AssertionTypes::Boolean), + | (Self::Xor, AssertionTypes::Boolean, AssertionTypes::Boolean) => + Ok(AssertionTypes::Boolean), + | (Self::Xor, AssertionTypes::Set, AssertionTypes::Set) => + Ok(AssertionTypes::Set), + | ( + Self::Less, + AssertionTypes::Integer, + AssertionTypes::Integer, + ) | (Self::Less, AssertionTypes::Set, AssertionTypes::Set) | ( Self::LessEq, @@ -418,41 +413,64 @@ impl Binary { AssertionTypes::Integer, ) | (Self::LessEq, AssertionTypes::Set, AssertionTypes::Set) - | (Self::More, AssertionTypes::Integer, AssertionTypes::Integer) + | ( + Self::More, + AssertionTypes::Integer, + AssertionTypes::Integer, + ) | (Self::More, AssertionTypes::Set, AssertionTypes::Set) | ( Self::MoreEq, AssertionTypes::Integer, AssertionTypes::Integer, ) - | (Self::MoreEq, AssertionTypes::Set, AssertionTypes::Set) => { - Ok(AssertionTypes::Boolean) - } - (Self::Eq, AssertionTypes::Integer, AssertionTypes::Integer) + | (Self::MoreEq, AssertionTypes::Set, AssertionTypes::Set) => + Ok(AssertionTypes::Boolean), + | (Self::Eq, AssertionTypes::Integer, AssertionTypes::Integer) | (Self::Eq, AssertionTypes::Boolean, AssertionTypes::Boolean) | (Self::Eq, AssertionTypes::Element, AssertionTypes::Element) | (Self::Eq, AssertionTypes::Label, AssertionTypes::Label) | (Self::Eq, AssertionTypes::String, AssertionTypes::String) | (Self::Eq, AssertionTypes::Set, AssertionTypes::Set) - | (Self::NotEq, AssertionTypes::Integer, AssertionTypes::Integer) - | (Self::NotEq, AssertionTypes::Boolean, AssertionTypes::Boolean) - | (Self::NotEq, AssertionTypes::Element, AssertionTypes::Element) + | ( + Self::NotEq, + AssertionTypes::Integer, + AssertionTypes::Integer, + ) + | ( + Self::NotEq, + AssertionTypes::Boolean, + AssertionTypes::Boolean, + ) + | ( + Self::NotEq, + AssertionTypes::Element, + AssertionTypes::Element, + ) | (Self::NotEq, AssertionTypes::Label, AssertionTypes::Label) | (Self::NotEq, AssertionTypes::String, AssertionTypes::String) - | (Self::NotEq, AssertionTypes::Set, AssertionTypes::Set) => { - Ok(AssertionTypes::Boolean) - } - (Self::Plus, AssertionTypes::Integer, AssertionTypes::Integer) - | (Self::Minus, AssertionTypes::Integer, AssertionTypes::Integer) - | (Self::Times, AssertionTypes::Integer, AssertionTypes::Integer) => { - Ok(AssertionTypes::Integer) - } - (Self::Plus, AssertionTypes::Set, AssertionTypes::Set) + | (Self::NotEq, AssertionTypes::Set, AssertionTypes::Set) => + Ok(AssertionTypes::Boolean), + | ( + Self::Plus, + AssertionTypes::Integer, + AssertionTypes::Integer, + ) + | ( + Self::Minus, + AssertionTypes::Integer, + AssertionTypes::Integer, + ) + | ( + Self::Times, + AssertionTypes::Integer, + AssertionTypes::Integer, + ) => Ok(AssertionTypes::Integer), + | (Self::Plus, AssertionTypes::Set, AssertionTypes::Set) | (Self::Minus, AssertionTypes::Set, AssertionTypes::Set) - | (Self::Times, AssertionTypes::Set, AssertionTypes::Set) => { - Ok(AssertionTypes::Set) - } - ( + | (Self::Times, AssertionTypes::Set, AssertionTypes::Set) => + Ok(AssertionTypes::Set), + | ( Self::Exponential, AssertionTypes::Integer, AssertionTypes::Integer, @@ -467,25 +485,27 @@ impl Binary { AssertionTypes::Integer, AssertionTypes::Integer, ) => Ok(AssertionTypes::Integer), - (Self::Concat, AssertionTypes::String, AssertionTypes::String) => { - Ok(AssertionTypes::String) - } - (Self::Concat, AssertionTypes::Set, AssertionTypes::Element) => { - Ok(AssertionTypes::Set) - } - (Self::SubStr, AssertionTypes::String, AssertionTypes::String) => { - Ok(AssertionTypes::Integer) - } - (Self::Min, AssertionTypes::Integer, AssertionTypes::Integer) - | (Self::Max, AssertionTypes::Integer, AssertionTypes::Integer) => { - Ok(AssertionTypes::Integer) - } - ( + | ( + Self::Concat, + AssertionTypes::String, + AssertionTypes::String, + ) => Ok(AssertionTypes::String), + | (Self::Concat, AssertionTypes::Set, AssertionTypes::Element) => + Ok(AssertionTypes::Set), + | ( + Self::SubStr, + AssertionTypes::String, + AssertionTypes::String, + ) => Ok(AssertionTypes::Integer), + | (Self::Min, AssertionTypes::Integer, AssertionTypes::Integer) + | (Self::Max, AssertionTypes::Integer, AssertionTypes::Integer) => + Ok(AssertionTypes::Integer), + | ( Self::CommonSubStr, AssertionTypes::String, AssertionTypes::String, ) => Ok(AssertionTypes::String), - _ => Err(format!( + | _ => Err(format!( "Expressions have incompatible types: {t1:?} and \ {t2:?} with operation {self:?}." )), @@ -500,15 +520,15 @@ impl AssertReturnValue { val: AssertReturnValue, ) -> Result<(), String> { match (self, q, val) { - ( + | ( Self::Label(l), Qualifier::Restricted(q), AssertReturnValue::Set(set), ) => { *q.referenced_mut(l) = set; Ok(()) - } - (s, q, val) => Err(format!( + }, + | (s, q, val) => Err(format!( "Cannot assign {val:?} to {s:?} with qualifier \ {q:?}" )), @@ -521,19 +541,19 @@ impl AssertReturnValue { // ----------------------------------------------------------------------------- pub(super) struct TypeContext { - data: HashMap, + data: HashMap, return_ty: Option, } pub(super) struct Context { - data: HashMap, + data: HashMap, special: HashMap, } impl TypeContext { pub(super) fn new() -> Self { TypeContext { - data: HashMap::new(), + data: HashMap::new(), return_ty: None, } } @@ -566,32 +586,33 @@ impl TypeContext { S: SpecialVariables, { match (v, q) { - (Variable::Id(v), None) => { + | (Variable::Id(v), None) => { self.data.insert(v.clone(), ty); Ok(()) - } - (Variable::Id(v), Some(q)) => match self.data.entry(v.clone()) { - std::collections::hash_map::Entry::Vacant(_ve) => Err(format!( - "Variable {v:?} as no assignment while \ + }, + | (Variable::Id(v), Some(q)) => match self.data.entry(v.clone()) { + | std::collections::hash_map::Entry::Vacant(_ve) => + Err(format!( + "Variable {v:?} as no assignment while \ trying to assign to qualification {q:?}, \ assign first a value." - )), - std::collections::hash_map::Entry::Occupied(oe) => { + )), + | std::collections::hash_map::Entry::Occupied(oe) => { match (oe.get(), q, ty) { - ( + | ( AssertionTypes::Label, Qualifier::Restricted(_), AssertionTypes::Set, ) => Ok(()), - (t, q, ty) => Err(format!( + | (t, q, ty) => Err(format!( "Variable {v:?} has type {t:?}, \ but was assigned with qualifier \ {q:?} value with type {ty:?}." )), } - } + }, }, - (Variable::Special(s), None) => { + | (Variable::Special(s), None) => if s.type_of() == ty { Ok(()) } else { @@ -600,9 +621,8 @@ impl TypeContext { assigned a value of type {ty:?}.", s.type_of() )) - } - } - (Variable::Special(s), Some(q)) => { + }, + | (Variable::Special(s), Some(q)) => if s.type_qualified(q)? == ty { Ok(()) } else { @@ -612,8 +632,7 @@ impl TypeContext { qualifier {q:?}.", s.type_of() )) - } - } + }, } } @@ -626,28 +645,28 @@ impl TypeContext { S: SpecialVariables, { let v = match v { - Variable::Special(s) => { + | Variable::Special(s) => { return Err(format!( "Protected word {s:?} used in for \ assignment." )); - } - Variable::Id(v) => v, + }, + | Variable::Id(v) => v, }; match ty { - AssertionTypes::RangeSet => { + | AssertionTypes::RangeSet => { self.data.insert(v.clone(), AssertionTypes::Element); Ok(()) - } - AssertionTypes::RangeInteger => { + }, + | AssertionTypes::RangeInteger => { self.data.insert(v.clone(), AssertionTypes::Integer); Ok(()) - } - AssertionTypes::RangeNeighbours => { + }, + | AssertionTypes::RangeNeighbours => { self.data.insert(v.clone(), AssertionTypes::Edge); Ok(()) - } - _ => Err(format!("Range has incorrect type {ty:?}.")), + }, + | _ => Err(format!("Range has incorrect type {ty:?}.")), } } @@ -656,14 +675,13 @@ impl TypeContext { S: SpecialVariables, { match v { - Variable::Special(s) => Ok(s.type_of()), - Variable::Id(v) => { + | Variable::Special(s) => Ok(s.type_of()), + | Variable::Id(v) => if let Some(ty) = self.data.get(v) { Ok(*ty) } else { Err(format!("Could not find variable {v:?}.")) - } - } + }, } } } @@ -674,7 +692,7 @@ impl Context { S: SpecialVariables, { Self { - data: HashMap::new(), + data: HashMap::new(), special: S::new_context(input), } } @@ -689,35 +707,35 @@ impl Context { S: SpecialVariables, { match (v, q) { - (Variable::Id(v), None) => { + | (Variable::Id(v), None) => { self.data.insert(v.clone(), val); Ok(()) - } - (Variable::Id(v), Some(q)) => match self.data.entry(v.clone()) { - std::collections::hash_map::Entry::Vacant(_ve) => Err(format!( - "Variable {v:?} as no assignment while \ + }, + | (Variable::Id(v), Some(q)) => match self.data.entry(v.clone()) { + | std::collections::hash_map::Entry::Vacant(_ve) => + Err(format!( + "Variable {v:?} as no assignment while \ trying to assign to qualification {q:?}, \ assign first a value." - )), - std::collections::hash_map::Entry::Occupied(mut oe) => { + )), + | std::collections::hash_map::Entry::Occupied(mut oe) => match (oe.get_mut(), q, val) { - ( + | ( &mut AssertReturnValue::Label(ref mut l), Qualifier::Restricted(q), AssertReturnValue::Set(set), ) => { *q.referenced_mut(l) = set; Ok(()) - } - (val, q, newval) => Err(format!( + }, + | (val, q, newval) => Err(format!( "Variable {v:?} has value {val:?}, \ but was assigned with qualifier \ {q:?} new value {newval:?}." )), - } - } + }, }, - (Variable::Special(s), None) => { + | (Variable::Special(s), None) => if s.correct_type(&val) { if let Some(s) = self.special.get_mut(s) { *s = val; @@ -727,9 +745,8 @@ impl Context { Ok(()) } else { Err(format!("Trying to assign {val:?} to variable {s:?}.")) - } - } - (Variable::Special(s), Some(q)) => { + }, + | (Variable::Special(s), Some(q)) => { if let Some(s) = self.special.get_mut(s) { s.assign_qualified(*q, val) } else { @@ -739,7 +756,7 @@ impl Context { was found." )) } - } + }, } } @@ -748,16 +765,15 @@ impl Context { S: SpecialVariables, { match v { - Variable::Id(var) => self.data.get(var).cloned().ok_or(format!( + | Variable::Id(var) => self.data.get(var).cloned().ok_or(format!( "Variable {v:?} used, but no value \ assigned." )), - Variable::Special(s) => { + | Variable::Special(s) => self.special.get(s).cloned().ok_or(format!( "Variable {v:?} used but no value \ assigned." - )) - } + )), } } } @@ -770,75 +786,65 @@ impl AssertReturnValue { graph: &graph::SystemGraph, ) -> Result { match (self, u) { - (AssertReturnValue::Boolean(b), Unary::Not) => { - Ok(AssertReturnValue::Boolean(!b)) - } - (AssertReturnValue::Integer(i), Unary::Rand) => { - Ok(AssertReturnValue::Integer(rand::random_range(0..i))) - } - (AssertReturnValue::Set(set), Unary::Empty) => { - Ok(AssertReturnValue::Boolean(set.is_empty())) - } - (AssertReturnValue::String(s), Unary::Empty) => { - Ok(AssertReturnValue::Boolean(s.is_empty())) - } - (AssertReturnValue::Set(set), Unary::Length) => { - Ok(AssertReturnValue::Integer(set.len() as i64)) - } - (AssertReturnValue::String(s), Unary::Length) => { - Ok(AssertReturnValue::Integer(s.len() as i64)) - } - (AssertReturnValue::Boolean(b), Unary::ToStr) => { - Ok(AssertReturnValue::String(format!("{b}"))) - } - (AssertReturnValue::Integer(i), Unary::ToStr) => { - Ok(AssertReturnValue::String(format!("{i}"))) - } - (AssertReturnValue::Element(el), Unary::ToStr) => { + | (AssertReturnValue::Boolean(b), Unary::Not) => + Ok(AssertReturnValue::Boolean(!b)), + | (AssertReturnValue::Integer(i), Unary::Rand) => + Ok(AssertReturnValue::Integer(rand::random_range(0..i))), + | (AssertReturnValue::Set(set), Unary::Empty) => + Ok(AssertReturnValue::Boolean(set.is_empty())), + | (AssertReturnValue::String(s), Unary::Empty) => + Ok(AssertReturnValue::Boolean(s.is_empty())), + | (AssertReturnValue::Set(set), Unary::Length) => + Ok(AssertReturnValue::Integer(set.len() as i64)), + | (AssertReturnValue::String(s), Unary::Length) => + Ok(AssertReturnValue::Integer(s.len() as i64)), + | (AssertReturnValue::Boolean(b), Unary::ToStr) => + Ok(AssertReturnValue::String(format!("{b}"))), + | (AssertReturnValue::Integer(i), Unary::ToStr) => + Ok(AssertReturnValue::String(format!("{i}"))), + | (AssertReturnValue::Element(el), Unary::ToStr) => Ok(AssertReturnValue::String( translator .decode(el) .ok_or(format!("Could not find element {el:?}."))?, - )) - } - ( + )), + | ( AssertReturnValue::Label(l), Unary::Qualifier(Qualifier::Label(q)), ) => Ok(q.get(&l)), - ( + | ( AssertReturnValue::Label(l), Unary::Qualifier(Qualifier::Restricted(q)), ) => Ok(q.get(&l)), - (AssertReturnValue::String(s), Unary::ToEl) => { - Ok(AssertReturnValue::Element(translator.encode(s))) - } - ( + | (AssertReturnValue::String(s), Unary::ToEl) => + Ok(AssertReturnValue::Element(translator.encode(s))), + | ( AssertReturnValue::Edge(edge), Unary::Qualifier(Qualifier::Edge(QualifierEdge::Source)), ) => Ok(AssertReturnValue::Node( graph.edge_endpoints(edge).unwrap().0, )), - ( + | ( AssertReturnValue::Edge(edge), Unary::Qualifier(Qualifier::Edge(QualifierEdge::Target)), ) => Ok(AssertReturnValue::Node( graph.edge_endpoints(edge).unwrap().1, )), - ( + | ( AssertReturnValue::Node(node), Unary::Qualifier(Qualifier::Node(QualifierNode::Neighbours)), ) => Ok(AssertReturnValue::Neighbours(node)), - ( + | ( AssertReturnValue::Node(node), Unary::Qualifier(Qualifier::Node(QualifierNode::System)), ) => Ok(AssertReturnValue::System( graph.node_weight(node).unwrap().clone(), )), - ( + | ( AssertReturnValue::System(sys), Unary::Qualifier(Qualifier::System(q)), ) => Ok(q.get(&sys)), - (val, u) => Err(format!( + | (val, u) => Err(format!( "Incompatible unary operation {u:?} on value \ {val:?}." )), @@ -853,64 +859,56 @@ impl AssertReturnValue { ) -> Result { use AssertReturnValue::*; Ok(match (b, self, other) { - (Binary::And, Boolean(b1), Boolean(b2)) => Boolean(b1 && b2), - (Binary::Or, Boolean(b1), Boolean(b2)) => Boolean(b1 || b2), - (Binary::Xor, Boolean(b1), Boolean(b2)) => Boolean(b1 ^ b2), - (Binary::Xor, Set(s1), Set(s2)) => { - Set(s1.union(&s2).subtraction(&s1.intersection(&s2))) - } - (Binary::Less, Integer(i1), Integer(i2)) => Boolean(i1 < i2), - (Binary::Less, Set(s1), Set(s2)) => { - Boolean(s1.is_subset(&s2) && !s2.is_subset(&s1)) - } - (Binary::LessEq, Integer(i1), Integer(i2)) => Boolean(i1 <= i2), - (Binary::LessEq, Set(s1), Set(s2)) => Boolean(s1.is_subset(&s2)), - (Binary::More, Integer(i1), Integer(i2)) => Boolean(i1 > i2), - (Binary::More, Set(s1), Set(s2)) => { - Boolean(s2.is_subset(&s1) && !s1.is_subset(&s2)) - } - (Binary::MoreEq, Integer(i1), Integer(i2)) => Boolean(i1 >= i2), - (Binary::MoreEq, Set(s1), Set(s2)) => Boolean(s2.is_subset(&s1)), - (Binary::Eq, Integer(i1), Integer(i2)) => Boolean(i1 == i2), - (Binary::Eq, Boolean(b1), Boolean(b2)) => Boolean(b1 == b2), - (Binary::Eq, Element(el1), Element(el2)) => Boolean(el1 == el2), - (Binary::Eq, Label(l1), Label(l2)) => Boolean(l1 == l2), - (Binary::Eq, String(s1), String(s2)) => Boolean(s1 == s2), - (Binary::Eq, Set(set1), Set(set2)) => Boolean(set1 == set2), - (Binary::NotEq, Integer(i1), Integer(i2)) => Boolean(i1 != i2), - (Binary::NotEq, Boolean(b1), Boolean(b2)) => Boolean(b1 != b2), - (Binary::NotEq, Element(el1), Element(el2)) => Boolean(el1 != el2), - (Binary::NotEq, Label(l1), Label(l2)) => Boolean(l1 != l2), - (Binary::NotEq, String(s1), String(s2)) => Boolean(s1 != s2), - (Binary::NotEq, Set(set1), Set(set2)) => Boolean(set1 != set2), - (Binary::Plus, Integer(i1), Integer(i2)) => Integer(i1 + i2), - (Binary::Plus, Set(set1), Set(set2)) => Set(set1.union(&set2)), - (Binary::Minus, Integer(i1), Integer(i2)) => Integer(i1 - i2), - (Binary::Minus, Set(set1), Set(set2)) => { - Set(set1.subtraction(&set2)) - } - (Binary::Times, Integer(i1), Integer(i2)) => Integer(i1 * i2), - (Binary::Times, Set(set1), Set(set2)) => { - Set(set1.intersection(&set2)) - } - (Binary::Exponential, Integer(i1), Integer(i2)) => { + | (Binary::And, Boolean(b1), Boolean(b2)) => Boolean(b1 && b2), + | (Binary::Or, Boolean(b1), Boolean(b2)) => Boolean(b1 || b2), + | (Binary::Xor, Boolean(b1), Boolean(b2)) => Boolean(b1 ^ b2), + | (Binary::Xor, Set(s1), Set(s2)) => + Set(s1.union(&s2).subtraction(&s1.intersection(&s2))), + | (Binary::Less, Integer(i1), Integer(i2)) => Boolean(i1 < i2), + | (Binary::Less, Set(s1), Set(s2)) => + Boolean(s1.is_subset(&s2) && !s2.is_subset(&s1)), + | (Binary::LessEq, Integer(i1), Integer(i2)) => Boolean(i1 <= i2), + | (Binary::LessEq, Set(s1), Set(s2)) => Boolean(s1.is_subset(&s2)), + | (Binary::More, Integer(i1), Integer(i2)) => Boolean(i1 > i2), + | (Binary::More, Set(s1), Set(s2)) => + Boolean(s2.is_subset(&s1) && !s1.is_subset(&s2)), + | (Binary::MoreEq, Integer(i1), Integer(i2)) => Boolean(i1 >= i2), + | (Binary::MoreEq, Set(s1), Set(s2)) => Boolean(s2.is_subset(&s1)), + | (Binary::Eq, Integer(i1), Integer(i2)) => Boolean(i1 == i2), + | (Binary::Eq, Boolean(b1), Boolean(b2)) => Boolean(b1 == b2), + | (Binary::Eq, Element(el1), Element(el2)) => Boolean(el1 == el2), + | (Binary::Eq, Label(l1), Label(l2)) => Boolean(l1 == l2), + | (Binary::Eq, String(s1), String(s2)) => Boolean(s1 == s2), + | (Binary::Eq, Set(set1), Set(set2)) => Boolean(set1 == set2), + | (Binary::NotEq, Integer(i1), Integer(i2)) => Boolean(i1 != i2), + | (Binary::NotEq, Boolean(b1), Boolean(b2)) => Boolean(b1 != b2), + | (Binary::NotEq, Element(el1), Element(el2)) => + Boolean(el1 != el2), + | (Binary::NotEq, Label(l1), Label(l2)) => Boolean(l1 != l2), + | (Binary::NotEq, String(s1), String(s2)) => Boolean(s1 != s2), + | (Binary::NotEq, Set(set1), Set(set2)) => Boolean(set1 != set2), + | (Binary::Plus, Integer(i1), Integer(i2)) => Integer(i1 + i2), + | (Binary::Plus, Set(set1), Set(set2)) => Set(set1.union(&set2)), + | (Binary::Minus, Integer(i1), Integer(i2)) => Integer(i1 - i2), + | (Binary::Minus, Set(set1), Set(set2)) => + Set(set1.subtraction(&set2)), + | (Binary::Times, Integer(i1), Integer(i2)) => Integer(i1 * i2), + | (Binary::Times, Set(set1), Set(set2)) => + Set(set1.intersection(&set2)), + | (Binary::Exponential, Integer(i1), Integer(i2)) => if i2 < 0 { Integer(0) } else { Integer(i1.pow(i2 as u32)) - } - } - (Binary::Quotient, Integer(i1), Integer(i2)) => { - Integer(i1.div_euclid(i2)) - } - (Binary::Reminder, Integer(i1), Integer(i2)) => { - Integer(i1.rem_euclid(i2)) - } - (Binary::Concat, String(s1), String(s2)) => String(s1 + &s2), - (Binary::Concat, Set(s), Element(e)) => { - Set(s.union(&set::Set::from([e]))) - } - (Binary::SubStr, String(s1), String(s2)) => { + }, + | (Binary::Quotient, Integer(i1), Integer(i2)) => + Integer(i1.div_euclid(i2)), + | (Binary::Reminder, Integer(i1), Integer(i2)) => + Integer(i1.rem_euclid(i2)), + | (Binary::Concat, String(s1), String(s2)) => String(s1 + &s2), + | (Binary::Concat, Set(s), Element(e)) => + Set(s.union(&set::Set::from([e]))), + | (Binary::SubStr, String(s1), String(s2)) => { let mut len = s1.len() as i64; for (p, c) in s1.chars().enumerate() { if s2.chars().nth(p) != Some(c) { @@ -919,10 +917,10 @@ impl AssertReturnValue { } } Integer(len) - } - (Binary::Min, Integer(i1), Integer(i2)) => Integer(i1.min(i2)), - (Binary::Max, Integer(i1), Integer(i2)) => Integer(i1.max(i2)), - (Binary::CommonSubStr, String(s1), String(s2)) => { + }, + | (Binary::Min, Integer(i1), Integer(i2)) => Integer(i1.min(i2)), + | (Binary::Max, Integer(i1), Integer(i2)) => Integer(i1.max(i2)), + | (Binary::CommonSubStr, String(s1), String(s2)) => { let mut s = std::string::String::new(); for (p, c) in s1.chars().enumerate() { if s2.chars().nth(p) != Some(c) { @@ -931,13 +929,13 @@ impl AssertReturnValue { s.push(c); } String(s) - } - (b, val1, val2) => { + }, + | (b, val1, val2) => { return Err(format!( "Operation {b:?} on values {val1:?} and \ {val2:?} could not be executed." )); - } + }, }) } } @@ -950,29 +948,29 @@ where S: SpecialVariables, { match tree { - Tree::Concat(t1, t2) => { + | Tree::Concat(t1, t2) => { typecheck_helper(t1, c)?; typecheck_helper(t2, c) - } - Tree::If(exp, t) => { + }, + | Tree::If(exp, t) => { match typecheck_expression(exp, c)? { - AssertionTypes::Boolean => {} - _ => { + | AssertionTypes::Boolean => {}, + | _ => { return Err("Expression in if statement doesn't return a \ boolean." .to_string()); - } + }, }; typecheck_helper(t, c) - } - Tree::IfElse(exp, t1, t2) => { + }, + | Tree::IfElse(exp, t1, t2) => { match typecheck_expression(exp, c)? { - AssertionTypes::Boolean => {} - _ => { + | AssertionTypes::Boolean => {}, + | _ => { return Err("Expression in if statement doesn't return a \ boolean." .into()); - } + }, }; let type_t1 = typecheck_helper(t1, c)?; let type_t2 = typecheck_helper(t2, c)?; @@ -981,22 +979,22 @@ where } else { Err("Branches of if statement do not match.".into()) } - } - Tree::Assignment(assignvar, q, exp) => { + }, + | Tree::Assignment(assignvar, q, exp) => { let type_exp = typecheck_expression(exp, c)?; c.assign(assignvar, q.into(), type_exp)?; Ok(AssertionTypes::NoType) - } - Tree::Return(exp) => { + }, + | Tree::Return(exp) => { let type_exp = typecheck_expression(exp, c)?; c.return_type(type_exp)?; Ok(AssertionTypes::NoType) - } - Tree::For(var, range, t) => { + }, + | Tree::For(var, range, t) => { let type_range = typecheck_range(range, c)?; c.assign_range(var, type_range)?; typecheck_helper(t, c) - } + }, } } @@ -1019,24 +1017,24 @@ where S: SpecialVariables, { match exp { - Expression::True | Expression::False => Ok(AssertionTypes::Boolean), - Expression::Integer(_) => Ok(AssertionTypes::Integer), - Expression::Label(_) => Ok(AssertionTypes::Label), - Expression::Set(_) => Ok(AssertionTypes::Set), - Expression::Element(_) => Ok(AssertionTypes::Element), - Expression::String(_) => Ok(AssertionTypes::String), - Expression::Var(v) => c.get(v), + | Expression::True | Expression::False => Ok(AssertionTypes::Boolean), + | Expression::Integer(_) => Ok(AssertionTypes::Integer), + | Expression::Label(_) => Ok(AssertionTypes::Label), + | Expression::Set(_) => Ok(AssertionTypes::Set), + | Expression::Element(_) => Ok(AssertionTypes::Element), + | Expression::String(_) => Ok(AssertionTypes::String), + | Expression::Var(v) => c.get(v), - Expression::Unary(u, exp) => { + | Expression::Unary(u, exp) => { let type_exp = typecheck_expression(exp, c)?; u.associate(&type_exp) - } + }, - Expression::Binary(b, exp1, exp2) => { + | Expression::Binary(b, exp1, exp2) => { let type_exp1 = typecheck_expression(exp1, c)?; let type_exp2 = typecheck_expression(exp2, c)?; b.associate(&type_exp1, &type_exp2) - } + }, } } @@ -1048,7 +1046,7 @@ where S: SpecialVariables, { match range { - Range::IterateInRange(exp1, exp2) => { + | Range::IterateInRange(exp1, exp2) => { let type_exp1 = typecheck_expression(exp1, c)?; let type_exp2 = typecheck_expression(exp2, c)?; if let (AssertionTypes::Integer, AssertionTypes::Integer) = @@ -1061,20 +1059,19 @@ where {type_exp1:?} and {type_exp2:?}." )) } - } - Range::IterateOverSet(exp) => { + }, + | Range::IterateOverSet(exp) => { let type_exp = typecheck_expression(exp, c)?; match type_exp { - AssertionTypes::Set => Ok(AssertionTypes::RangeSet), - AssertionTypes::RangeNeighbours => { - Ok(AssertionTypes::RangeNeighbours) - } - _ => Err(format!( + | AssertionTypes::Set => Ok(AssertionTypes::RangeSet), + | AssertionTypes::RangeNeighbours => + Ok(AssertionTypes::RangeNeighbours), + | _ => Err(format!( "Expressions in range is not a set or \ neighbours of a node, but is: {type_exp:?}." )), } - } + }, } } @@ -1088,36 +1085,37 @@ where S: SpecialVariables, { match tree { - Tree::Concat(t1, t2) => { + | Tree::Concat(t1, t2) => { if let Some(val) = execute(t1, c, translator, graph)? { Ok(Some(val)) } else { execute(t2, c, translator, graph) } - } - Tree::If(exp, t) => { + }, + | Tree::If(exp, t) => { let guard = execute_exp(exp, c, translator, graph)?; if let AssertReturnValue::Boolean(true) = guard { execute(t, c, translator, graph) } else { Ok(None) } - } - Tree::IfElse(exp, t1, t2) => { + }, + | Tree::IfElse(exp, t1, t2) => { let guard = execute_exp(exp, c, translator, graph)?; if let AssertReturnValue::Boolean(true) = guard { execute(t1, c, translator, graph) } else { execute(t2, c, translator, graph) } - } - Tree::Assignment(v, q, exp) => { + }, + | Tree::Assignment(v, q, exp) => { let val = execute_exp(exp, c, translator, graph)?; c.assign(v, q.into(), val)?; Ok(None) - } - Tree::Return(exp) => Ok(Some(execute_exp(exp, c, translator, graph)?)), - Tree::For(v, r, t) => { + }, + | Tree::Return(exp) => + Ok(Some(execute_exp(exp, c, translator, graph)?)), + | Tree::For(v, r, t) => { let range = range_into_iter(r, c, translator, graph)?; for val in range { c.assign(v, None, val)?; @@ -1126,7 +1124,7 @@ where } } Ok(None) - } + }, } } @@ -1144,39 +1142,39 @@ where use petgraph::visit::EdgeRef; match range { - Range::IterateOverSet(exp) => { + | Range::IterateOverSet(exp) => { let val = execute_exp(exp, c, translator, graph)?; match val { - AssertReturnValue::Set(set) => Ok(set + | AssertReturnValue::Set(set) => Ok(set .into_iter() .map(AssertReturnValue::Element) .collect::>() .into_iter()), - AssertReturnValue::Neighbours(node) => Ok(graph + | AssertReturnValue::Neighbours(node) => Ok(graph .edges(node) .map(|x| AssertReturnValue::Edge(x.id())) .collect::>() .into_iter()), - _ => Err(format!("{val:?} is not a set in for cycle.")), + | _ => Err(format!("{val:?} is not a set in for cycle.")), } - } - Range::IterateInRange(exp1, exp2) => { + }, + | Range::IterateInRange(exp1, exp2) => { let val1 = execute_exp(exp1, c, translator, graph)?; let val2 = execute_exp(exp2, c, translator, graph)?; match (val1, val2) { - ( + | ( AssertReturnValue::Integer(i1), AssertReturnValue::Integer(i2), ) => Ok((i1..i2) .map(AssertReturnValue::Integer) .collect::>() .into_iter()), - (val1, val2) => Err(format!( + | (val1, val2) => Err(format!( "{val1:?}..{val2:?} is not a valid integer \ range in for cycle." )), } - } + }, } } @@ -1190,22 +1188,22 @@ where S: SpecialVariables, { match exp { - Expression::True => Ok(AssertReturnValue::Boolean(true)), - Expression::False => Ok(AssertReturnValue::Boolean(false)), - Expression::Integer(i) => Ok(AssertReturnValue::Integer(*i)), - Expression::Label(l) => Ok(AssertReturnValue::Label(*l.clone())), - Expression::Set(set) => Ok(AssertReturnValue::Set(set.clone())), - Expression::Element(el) => Ok(AssertReturnValue::Element(*el)), - Expression::String(s) => Ok(AssertReturnValue::String(s.clone())), - Expression::Var(var) => c.get(var), - Expression::Unary(u, exp) => { + | Expression::True => Ok(AssertReturnValue::Boolean(true)), + | Expression::False => Ok(AssertReturnValue::Boolean(false)), + | Expression::Integer(i) => Ok(AssertReturnValue::Integer(*i)), + | Expression::Label(l) => Ok(AssertReturnValue::Label(*l.clone())), + | Expression::Set(set) => Ok(AssertReturnValue::Set(set.clone())), + | Expression::Element(el) => Ok(AssertReturnValue::Element(*el)), + | Expression::String(s) => Ok(AssertReturnValue::String(s.clone())), + | Expression::Var(var) => c.get(var), + | Expression::Unary(u, exp) => { let val = execute_exp(exp, c, translator, graph)?; val.unary(u, translator, graph) - } - Expression::Binary(b, exp1, exp2) => { + }, + | Expression::Binary(b, exp1, exp2) => { let val1 = execute_exp(exp1, c, translator, graph)?; let val2 = execute_exp(exp2, c, translator, graph)?; val1.binary(b, val2, translator) - } + }, } } diff --git a/src/rsprocess/assert/fmt.rs b/src/rsprocess/assert/fmt.rs index cf9fb51..9501c7b 100644 --- a/src/rsprocess/assert/fmt.rs +++ b/src/rsprocess/assert/fmt.rs @@ -1,11 +1,12 @@ // ----------------------------------------------------------------------------- // Display Implementation for all types // ----------------------------------------------------------------------------- +use std::fmt; + use super::super::translator::{ Formatter, PrintableWithTranslator, Translator, }; use super::dsl::*; -use std::fmt; impl fmt::Debug for Assert where @@ -22,28 +23,27 @@ where { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Concat(t1, t2) => { + | Self::Concat(t1, t2) => { write!(f, "{t1:?};\n{t2:?}") - } - Self::If(exp, t) => { + }, + | Self::If(exp, t) => { write!(f, "if {exp:?} {{\n{t:?}\n}}") - } - Self::IfElse(exp, t1, t2) => { + }, + | Self::IfElse(exp, t1, t2) => { write!(f, "if {exp:?} {{\n{t1:?}\n}} else {{\n{t2:?}\n}}") - } - Self::Assignment(v, q, exp) => { + }, + | Self::Assignment(v, q, exp) => if let Some(q) = q { write!(f, "{v:?}.{q:?} = {exp:?}") } else { write!(f, "{v:?} = {exp:?}") - } - } - Self::Return(exp) => { + }, + | Self::Return(exp) => { write!(f, "return {exp:?}") - } - Self::For(v, r, t) => { + }, + | Self::For(v, r, t) => { write!(f, "for {v:?} in {r:?} {{\n{t:?}\n}}") - } + }, } } } @@ -54,12 +54,12 @@ where { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Special(s) => { + | Self::Special(s) => { write!(f, "{s:?}") - } - Self::Id(s) => { + }, + | Self::Id(s) => { write!(f, "{s:?}") - } + }, } } } @@ -70,40 +70,39 @@ where { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::True => { + | Self::True => { write!(f, "True") - } - Self::False => { + }, + | Self::False => { write!(f, "False") - } - Self::Integer(i) => { + }, + | Self::Integer(i) => { write!(f, "{i}") - } - Self::Label(rslabel) => { + }, + | Self::Label(rslabel) => { write!(f, "{{debug: {rslabel:?}}}") - } - Self::Set(set) => { + }, + | Self::Set(set) => { write!(f, "{{debug: {set:?}}}") - } - Self::Element(el) => { + }, + | Self::Element(el) => { write!(f, "'{{debug: {el:?}}}'") - } - Self::String(s) => { + }, + | Self::String(s) => { write!(f, r#""{s:?}""#) - } - Self::Var(v) => { + }, + | Self::Var(v) => { write!(f, "{v:?}") - } - Self::Unary(u, exp) => { + }, + | Self::Unary(u, exp) => if u.is_prefix() { write!(f, "{u:?}({exp:?})") } else if u.is_suffix() { write!(f, "{exp:?}{u:?}") } else { unreachable!() - } - } - Self::Binary(b, exp1, exp2) => { + }, + | Self::Binary(b, exp1, exp2) => if b.is_prefix() { write!(f, "{b:?}({exp1:?}, {exp2:?})") } else if b.is_suffix() { @@ -112,8 +111,7 @@ where write!(f, "({exp1:?} {b:?} {exp2:?})") } else { unreachable!() - } - } + }, } } } @@ -124,8 +122,10 @@ where { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::IterateOverSet(exp) => write!(f, "{{{exp:?}}}"), - Self::IterateInRange(exp1, exp2) => write!(f, "{exp1:?}..{exp2:?}"), + | Self::IterateOverSet(exp) => write!(f, "{{{exp:?}}}"), + | Self::IterateInRange(exp1, exp2) => { + write!(f, "{exp1:?}..{exp2:?}") + }, } } } @@ -133,13 +133,13 @@ where impl fmt::Debug for Unary { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Not => write!(f, "not"), - Self::Rand => write!(f, "rand"), - Self::Empty => write!(f, ".empty"), - Self::Length => write!(f, ".length"), - Self::ToStr => write!(f, ".tostr"), - Self::ToEl => write!(f, ".toel"), - Self::Qualifier(q) => write!(f, ".{q:?}"), + | Self::Not => write!(f, "not"), + | Self::Rand => write!(f, "rand"), + | Self::Empty => write!(f, ".empty"), + | Self::Length => write!(f, ".length"), + | Self::ToStr => write!(f, ".tostr"), + | Self::ToEl => write!(f, ".toel"), + | Self::Qualifier(q) => write!(f, ".{q:?}"), } } } @@ -147,13 +147,13 @@ impl fmt::Debug for Unary { impl fmt::Debug for QualifierRestricted { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Entities => write!(f, "Entities"), - Self::Context => write!(f, "Context"), - Self::Reactants => write!(f, "Reactants"), - Self::ReactantsAbsent => write!(f, "ReactantsAbsent"), - Self::Inhibitors => write!(f, "Inhibitors"), - Self::InhibitorsPresent => write!(f, "InhibitorsPresent"), - Self::Products => write!(f, "Products"), + | Self::Entities => write!(f, "Entities"), + | Self::Context => write!(f, "Context"), + | Self::Reactants => write!(f, "Reactants"), + | Self::ReactantsAbsent => write!(f, "ReactantsAbsent"), + | Self::Inhibitors => write!(f, "Inhibitors"), + | Self::InhibitorsPresent => write!(f, "InhibitorsPresent"), + | Self::Products => write!(f, "Products"), } } } @@ -161,9 +161,9 @@ impl fmt::Debug for QualifierRestricted { impl fmt::Debug for QualifierLabel { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::AvailableEntities => write!(f, "AvailableEntities"), - Self::AllReactants => write!(f, "AllReactants"), - Self::AllInhibitors => write!(f, "AllInhibitors"), + | Self::AvailableEntities => write!(f, "AvailableEntities"), + | Self::AllReactants => write!(f, "AllReactants"), + | Self::AllInhibitors => write!(f, "AllInhibitors"), } } } @@ -171,8 +171,8 @@ impl fmt::Debug for QualifierLabel { impl fmt::Debug for QualifierSystem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Context => write!(f, "context"), - Self::Entities => write!(f, "entities"), + | Self::Context => write!(f, "context"), + | Self::Entities => write!(f, "entities"), } } } @@ -180,8 +180,8 @@ impl fmt::Debug for QualifierSystem { impl fmt::Debug for QualifierEdge { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Source => write!(f, "source"), - Self::Target => write!(f, "target"), + | Self::Source => write!(f, "source"), + | Self::Target => write!(f, "target"), } } } @@ -189,8 +189,8 @@ impl fmt::Debug for QualifierEdge { impl fmt::Debug for QualifierNode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Neighbours => write!(f, "neighbours"), - Self::System => write!(f, "system"), + | Self::Neighbours => write!(f, "neighbours"), + | Self::System => write!(f, "system"), } } } @@ -198,11 +198,11 @@ impl fmt::Debug for QualifierNode { impl fmt::Debug for Qualifier { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Label(q) => write!(f, "{q:?}"), - Self::Restricted(q) => write!(f, "{q:?}"), - Self::System(q) => write!(f, "{q:?}"), - Self::Edge(q) => write!(f, "{q:?}"), - Self::Node(q) => write!(f, "{q:?}"), + | Self::Label(q) => write!(f, "{q:?}"), + | Self::Restricted(q) => write!(f, "{q:?}"), + | Self::System(q) => write!(f, "{q:?}"), + | Self::Edge(q) => write!(f, "{q:?}"), + | Self::Node(q) => write!(f, "{q:?}"), } } } @@ -210,26 +210,26 @@ impl fmt::Debug for Qualifier { impl fmt::Debug for Binary { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::And => write!(f, "&&"), - Self::Or => write!(f, "||"), - Self::Xor => write!(f, "^^"), - Self::Less => write!(f, "<"), - Self::LessEq => write!(f, "<="), - Self::More => write!(f, ">"), - Self::MoreEq => write!(f, ">="), - Self::Eq => write!(f, "=="), - Self::NotEq => write!(f, "!="), - Self::Plus => write!(f, "+"), - Self::Minus => write!(f, "-"), - Self::Times => write!(f, "*"), - Self::Exponential => write!(f, "^"), - Self::Quotient => write!(f, "/"), - Self::Reminder => write!(f, "%"), - Self::Concat => write!(f, "::"), - Self::SubStr => write!(f, "substr"), - Self::Min => write!(f, "min"), - Self::Max => write!(f, "max"), - Self::CommonSubStr => write!(f, "commonsubstr"), + | Self::And => write!(f, "&&"), + | Self::Or => write!(f, "||"), + | Self::Xor => write!(f, "^^"), + | Self::Less => write!(f, "<"), + | Self::LessEq => write!(f, "<="), + | Self::More => write!(f, ">"), + | Self::MoreEq => write!(f, ">="), + | Self::Eq => write!(f, "=="), + | Self::NotEq => write!(f, "!="), + | Self::Plus => write!(f, "+"), + | Self::Minus => write!(f, "-"), + | Self::Times => write!(f, "*"), + | Self::Exponential => write!(f, "^"), + | Self::Quotient => write!(f, "/"), + | Self::Reminder => write!(f, "%"), + | Self::Concat => write!(f, "::"), + | Self::SubStr => write!(f, "substr"), + | Self::Min => write!(f, "min"), + | Self::Max => write!(f, "max"), + | Self::CommonSubStr => write!(f, "commonsubstr"), } } } @@ -237,19 +237,19 @@ impl fmt::Debug for Binary { impl fmt::Debug for AssertReturnValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Boolean(b) => write!(f, "{b:?}"), - Self::Integer(i) => write!(f, "{i:?}"), - Self::String(s) => write!(f, r#""{s:?}""#), - Self::Label(l) => write!(f, "{{debug: {l:?}}}"), - Self::Set(set) => write!(f, "{{debug: {set:?}}}"), - Self::Element(el) => write!(f, "{{debug: {el:?}}}"), - Self::Edge(edge) => write!(f, "{{debug: {edge:?}}}"), - Self::Node(node) => write!(f, "{{debug: {node:?}}}"), - Self::Neighbours(node) => { + | Self::Boolean(b) => write!(f, "{b:?}"), + | Self::Integer(i) => write!(f, "{i:?}"), + | Self::String(s) => write!(f, r#""{s:?}""#), + | Self::Label(l) => write!(f, "{{debug: {l:?}}}"), + | Self::Set(set) => write!(f, "{{debug: {set:?}}}"), + | Self::Element(el) => write!(f, "{{debug: {el:?}}}"), + | Self::Edge(edge) => write!(f, "{{debug: {edge:?}}}"), + | Self::Node(node) => write!(f, "{{debug: {node:?}}}"), + | Self::Neighbours(node) => { write!(f, "{{debug: {node:?}}}.neighbours") - } - Self::System(sys) => write!(f, "{{debug: {sys:?}}}"), - Self::Context(ctx) => write!(f, "{{debug: {ctx:?}}}"), + }, + | Self::System(sys) => write!(f, "{{debug: {sys:?}}}"), + | Self::Context(ctx) => write!(f, "{{debug: {ctx:?}}}"), } } } @@ -257,20 +257,20 @@ impl fmt::Debug for AssertReturnValue { impl fmt::Debug for AssertionTypes { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Boolean => write!(f, "boolean"), - Self::Integer => write!(f, "integer"), - Self::String => write!(f, "string"), - Self::Label => write!(f, "label"), - Self::Set => write!(f, "set"), - Self::Element => write!(f, "element"), - Self::System => write!(f, "system"), - Self::Context => write!(f, "context"), - Self::NoType => write!(f, "no type"), - Self::RangeInteger => write!(f, "range of integers"), - Self::RangeSet => write!(f, "range of set"), - Self::RangeNeighbours => write!(f, "range of edges"), - Self::Edge => write!(f, "edge"), - Self::Node => write!(f, "node"), + | Self::Boolean => write!(f, "boolean"), + | Self::Integer => write!(f, "integer"), + | Self::String => write!(f, "string"), + | Self::Label => write!(f, "label"), + | Self::Set => write!(f, "set"), + | Self::Element => write!(f, "element"), + | Self::System => write!(f, "system"), + | Self::Context => write!(f, "context"), + | Self::NoType => write!(f, "no type"), + | Self::RangeInteger => write!(f, "range of integers"), + | Self::RangeSet => write!(f, "range of set"), + | Self::RangeNeighbours => write!(f, "range of edges"), + | Self::Edge => write!(f, "edge"), + | Self::Node => write!(f, "node"), } } } @@ -304,19 +304,19 @@ where translator: &Translator, ) -> fmt::Result { match self { - Self::Concat(t1, t2) => write!( + | Self::Concat(t1, t2) => write!( f, "{};\n{}", Formatter::from(translator, &**t1), Formatter::from(translator, &**t2) ), - Self::If(exp, t) => write!( + | Self::If(exp, t) => write!( f, "if {} {{\n{}\n}}", Formatter::from(translator, &**exp), Formatter::from(translator, &**t) ), - Self::IfElse(exp, t1, t2) => { + | Self::IfElse(exp, t1, t2) => { write!( f, "if {} {{\n{}\n}} else {{\n{}\n}}", @@ -324,8 +324,8 @@ where Formatter::from(translator, &**t1), Formatter::from(translator, &**t2) ) - } - Self::Assignment(v, q, exp) => { + }, + | Self::Assignment(v, q, exp) => if let Some(q) = q { write!( f, @@ -341,12 +341,11 @@ where Formatter::from(translator, v), Formatter::from(translator, &**exp) ) - } - } - Self::Return(exp) => { + }, + | Self::Return(exp) => { write!(f, "return {}", Formatter::from(translator, &**exp)) - } - Self::For(v, r, t) => { + }, + | Self::For(v, r, t) => { write!( f, "for {} in {} {{\n{}\n}}", @@ -354,7 +353,7 @@ where Formatter::from(translator, r), Formatter::from(translator, &**t) ) - } + }, } } } @@ -369,8 +368,10 @@ where translator: &Translator, ) -> fmt::Result { match self { - Self::Special(s) => write!(f, "{}", Formatter::from(translator, s)), - Self::Id(s) => write!(f, "{s}"), + | Self::Special(s) => { + write!(f, "{}", Formatter::from(translator, s)) + }, + | Self::Id(s) => write!(f, "{s}"), } } } @@ -385,19 +386,21 @@ where translator: &Translator, ) -> fmt::Result { match self { - Self::True => write!(f, "True"), - Self::False => write!(f, "False"), - Self::Integer(i) => write!(f, "{i}"), - Self::Label(l) => { + | Self::True => write!(f, "True"), + | Self::False => write!(f, "False"), + | Self::Integer(i) => write!(f, "{i}"), + | Self::Label(l) => { write!(f, "{}", Formatter::from(translator, &**l)) - } - Self::Set(set) => write!(f, "{}", Formatter::from(translator, set)), - Self::Element(el) => { + }, + | Self::Set(set) => { + write!(f, "{}", Formatter::from(translator, set)) + }, + | Self::Element(el) => { write!(f, "'{}'", Formatter::from(translator, el)) - } - Self::String(s) => write!(f, r#""{s}""#), - Self::Var(v) => write!(f, "{}", Formatter::from(translator, v)), - Self::Unary(u, exp) => { + }, + | Self::String(s) => write!(f, r#""{s}""#), + | Self::Var(v) => write!(f, "{}", Formatter::from(translator, v)), + | Self::Unary(u, exp) => if u.is_prefix() { write!( f, @@ -414,9 +417,8 @@ where ) } else { unreachable!() - } - } - Self::Binary(b, exp1, exp2) => { + }, + | Self::Binary(b, exp1, exp2) => if b.is_prefix() { write!( f, @@ -443,8 +445,7 @@ where ) } else { unreachable!() - } - } + }, } } } @@ -459,10 +460,10 @@ where translator: &Translator, ) -> fmt::Result { match self { - Self::IterateOverSet(exp) => { + | Self::IterateOverSet(exp) => { write!(f, "{}", Formatter::from(translator, &**exp)) - } - Self::IterateInRange(exp1, exp2) => write!( + }, + | Self::IterateInRange(exp1, exp2) => write!( f, "{}..{}", Formatter::from(translator, &**exp1), @@ -479,15 +480,15 @@ impl PrintableWithTranslator for Unary { translator: &Translator, ) -> fmt::Result { match self { - Self::Not => write!(f, "not"), - Self::Rand => write!(f, "rand"), - Self::Empty => write!(f, ".empty"), - Self::Length => write!(f, ".length"), - Self::ToStr => write!(f, ".tostr"), - Self::ToEl => write!(f, ".toel"), - Self::Qualifier(q) => { + | Self::Not => write!(f, "not"), + | Self::Rand => write!(f, "rand"), + | Self::Empty => write!(f, ".empty"), + | Self::Length => write!(f, ".length"), + | Self::ToStr => write!(f, ".tostr"), + | Self::ToEl => write!(f, ".toel"), + | Self::Qualifier(q) => { write!(f, ".{}", Formatter::from(translator, q)) - } + }, } } } @@ -549,13 +550,15 @@ impl PrintableWithTranslator for Qualifier { translator: &Translator, ) -> fmt::Result { match self { - Self::Label(q) => write!(f, "{}", Formatter::from(translator, q)), - Self::Restricted(q) => { + | Self::Label(q) => write!(f, "{}", Formatter::from(translator, q)), + | Self::Restricted(q) => { write!(f, "{}", Formatter::from(translator, q)) - } - Self::System(q) => write!(f, "{}", Formatter::from(translator, q)), - Self::Edge(q) => write!(f, "{}", Formatter::from(translator, q)), - Self::Node(q) => write!(f, "{}", Formatter::from(translator, q)), + }, + | Self::System(q) => { + write!(f, "{}", Formatter::from(translator, q)) + }, + | Self::Edge(q) => write!(f, "{}", Formatter::from(translator, q)), + | Self::Node(q) => write!(f, "{}", Formatter::from(translator, q)), } } } @@ -577,25 +580,27 @@ impl PrintableWithTranslator for AssertReturnValue { translator: &Translator, ) -> fmt::Result { match self { - Self::Boolean(b) => write!(f, "{b}"), - Self::Integer(i) => write!(f, "{i}"), - Self::String(s) => write!(f, r#""{s}""#), - Self::Label(l) => write!(f, "{}", Formatter::from(translator, l)), - Self::Set(set) => write!(f, "{}", Formatter::from(translator, set)), - Self::Element(el) => { + | Self::Boolean(b) => write!(f, "{b}"), + | Self::Integer(i) => write!(f, "{i}"), + | Self::String(s) => write!(f, r#""{s}""#), + | Self::Label(l) => write!(f, "{}", Formatter::from(translator, l)), + | Self::Set(set) => { + write!(f, "{}", Formatter::from(translator, set)) + }, + | Self::Element(el) => { write!(f, "{}", Formatter::from(translator, el)) - } - Self::Edge(edge) => write!(f, "{{edge: {edge:?}}}"), - Self::Node(node) => write!(f, "{{node: {node:?}}}"), - Self::Neighbours(node) => { + }, + | Self::Edge(edge) => write!(f, "{{edge: {edge:?}}}"), + | Self::Node(node) => write!(f, "{{node: {node:?}}}"), + | Self::Neighbours(node) => { write!(f, "{{node: {node:?}}}.neighbours") - } - Self::System(sys) => { + }, + | Self::System(sys) => { write!(f, "{}", Formatter::from(translator, sys)) - } - Self::Context(ctx) => { + }, + | Self::Context(ctx) => { write!(f, "{}", Formatter::from(translator, ctx)) - } + }, } } } diff --git a/src/rsprocess/assert/rsassert.rs b/src/rsprocess/assert/rsassert.rs index 19dfb06..db6236e 100644 --- a/src/rsprocess/assert/rsassert.rs +++ b/src/rsprocess/assert/rsassert.rs @@ -1,8 +1,8 @@ -use crate::rsprocess::translator::PrintableWithTranslator; +use std::collections::HashMap; use super::super::{graph, label, set, system, translator}; use super::dsl::*; -use std::collections::HashMap; +use crate::rsprocess::translator::PrintableWithTranslator; // ---------------------------------------------------------------------------- // Specific Assert Implementation @@ -60,20 +60,18 @@ enum EdgeRelablerInputValues { impl SpecialVariables for EdgeRelablerInput { fn type_of(&self) -> AssertionTypes { match self { - Self::Edge => AssertionTypes::Edge, - Self::Label => AssertionTypes::Label, + | Self::Edge => AssertionTypes::Edge, + | Self::Label => AssertionTypes::Label, } } fn type_qualified(&self, q: &Qualifier) -> Result { match (self, q) { - (Self::Label, Qualifier::Label(_)) - | (Self::Label, Qualifier::Restricted(_)) => { - Ok(AssertionTypes::Set) - } - (s, q) => { - Err(format!("Wrong use of qualifier {q:?} on variable {s:?}.")) - } + | (Self::Label, Qualifier::Label(_)) + | (Self::Label, Qualifier::Restricted(_)) => + Ok(AssertionTypes::Set), + | (s, q) => + Err(format!("Wrong use of qualifier {q:?} on variable {s:?}.")), } } @@ -83,21 +81,19 @@ impl SpecialVariables for EdgeRelablerInput { input .iter() .map(|(key, value)| match value { - EdgeRelablerInputValues::Edge(e) => { - (*key, AssertReturnValue::Edge(*e)) - } - EdgeRelablerInputValues::Label(l) => { - (*key, AssertReturnValue::Label(l.clone())) - } + | EdgeRelablerInputValues::Edge(e) => + (*key, AssertReturnValue::Edge(*e)), + | EdgeRelablerInputValues::Label(l) => + (*key, AssertReturnValue::Label(l.clone())), }) .collect::>() } fn correct_type(&self, other: &AssertReturnValue) -> bool { match (self, other) { - (Self::Edge, AssertReturnValue::Edge(_)) + | (Self::Edge, AssertReturnValue::Edge(_)) | (Self::Label, AssertReturnValue::Label(_)) => true, - (_, _) => false, + | (_, _) => false, } } } @@ -105,8 +101,8 @@ impl SpecialVariables for EdgeRelablerInput { impl std::fmt::Debug for EdgeRelablerInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Label => write!(f, "label"), - Self::Edge => write!(f, "edge"), + | Self::Label => write!(f, "label"), + | Self::Edge => write!(f, "edge"), } } } @@ -126,7 +122,7 @@ impl Assert { let mut context = TypeContext::new(); let ty = typecheck(&self.tree, &mut context)?; match ty { - AssertionTypes::Boolean + | AssertionTypes::Boolean | AssertionTypes::Integer | AssertionTypes::String | AssertionTypes::Label @@ -136,15 +132,13 @@ impl Assert { | AssertionTypes::Node | AssertionTypes::System | AssertionTypes::Context => Ok(()), - AssertionTypes::NoType => { + | AssertionTypes::NoType => Err("No return type, at least one return statement required." - .into()) - } - AssertionTypes::RangeInteger + .into()), + | AssertionTypes::RangeInteger | AssertionTypes::RangeSet - | AssertionTypes::RangeNeighbours => { - Err(format!("Returned type {ty:?} is not a valid return type.")) - } + | AssertionTypes::RangeNeighbours => + Err(format!("Returned type {ty:?} is not a valid return type.")), } } @@ -231,22 +225,19 @@ enum NodeRelablerInputValues { impl SpecialVariables for NodeRelablerInput { fn type_of(&self) -> AssertionTypes { match self { - Self::Entities => AssertionTypes::Set, - Self::Node => AssertionTypes::Node, + | Self::Entities => AssertionTypes::Set, + | Self::Node => AssertionTypes::Node, } } fn type_qualified(&self, q: &Qualifier) -> Result { match (self, q) { - (Self::Node, Qualifier::Node(QualifierNode::System)) => { - Ok(AssertionTypes::System) - } - (Self::Node, Qualifier::Node(QualifierNode::Neighbours)) => { - Ok(AssertionTypes::RangeNeighbours) - } - (s, q) => { - Err(format!("Wrong use of qualifier {q:?} on variable {s:?}.")) - } + | (Self::Node, Qualifier::Node(QualifierNode::System)) => + Ok(AssertionTypes::System), + | (Self::Node, Qualifier::Node(QualifierNode::Neighbours)) => + Ok(AssertionTypes::RangeNeighbours), + | (s, q) => + Err(format!("Wrong use of qualifier {q:?} on variable {s:?}.")), } } @@ -256,21 +247,19 @@ impl SpecialVariables for NodeRelablerInput { input .iter() .map(|(key, value)| match value { - NodeRelablerInputValues::Entities(e) => { - (*key, AssertReturnValue::Set(e.clone())) - } - NodeRelablerInputValues::Node(n) => { - (*key, AssertReturnValue::Node(*n)) - } + | NodeRelablerInputValues::Entities(e) => + (*key, AssertReturnValue::Set(e.clone())), + | NodeRelablerInputValues::Node(n) => + (*key, AssertReturnValue::Node(*n)), }) .collect::>() } fn correct_type(&self, other: &AssertReturnValue) -> bool { match (self, other) { - (Self::Entities, AssertReturnValue::Set(_)) + | (Self::Entities, AssertReturnValue::Set(_)) | (Self::Node, AssertReturnValue::Node(_)) => true, - (_, _) => false, + | (_, _) => false, } } } @@ -278,8 +267,8 @@ impl SpecialVariables for NodeRelablerInput { impl std::fmt::Debug for NodeRelablerInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Entities => write!(f, "entities"), - Self::Node => write!(f, "node"), + | Self::Entities => write!(f, "entities"), + | Self::Node => write!(f, "node"), } } } @@ -299,7 +288,7 @@ impl Assert { let mut context = TypeContext::new(); let ty = typecheck(&self.tree, &mut context)?; match ty { - AssertionTypes::Boolean + | AssertionTypes::Boolean | AssertionTypes::Integer | AssertionTypes::String | AssertionTypes::Label @@ -309,15 +298,13 @@ impl Assert { | AssertionTypes::Node | AssertionTypes::System | AssertionTypes::Context => Ok(()), - AssertionTypes::NoType => { + | AssertionTypes::NoType => Err("No return type, at least one return statement required." - .into()) - } - AssertionTypes::RangeInteger + .into()), + | AssertionTypes::RangeInteger | AssertionTypes::RangeSet - | AssertionTypes::RangeNeighbours => { - Err(format!("Returned type {ty:?} is not a valid return type.")) - } + | AssertionTypes::RangeNeighbours => + Err(format!("Returned type {ty:?} is not a valid return type.")), } } diff --git a/src/rsprocess/assert/tests.rs b/src/rsprocess/assert/tests.rs index a4bb434..38ca9ac 100644 --- a/src/rsprocess/assert/tests.rs +++ b/src/rsprocess/assert/tests.rs @@ -1273,11 +1273,12 @@ fn for_8() { #[test] fn nodes() { + use std::rc::Rc; + use environment::Environment; use label::Label; use process::Process; use set::Set; - use std::rc::Rc; use system::System; use translator::Translator; diff --git a/src/rsprocess/bisimilarity/bisimilarity_paige_tarkan.rs b/src/rsprocess/bisimilarity/bisimilarity_paige_tarkan.rs index f65fcc7..3900e6f 100644 --- a/src/rsprocess/bisimilarity/bisimilarity_paige_tarkan.rs +++ b/src/rsprocess/bisimilarity/bisimilarity_paige_tarkan.rs @@ -160,7 +160,7 @@ impl CompoundBlock { } struct BackEdgesGroup { - block: Rc>, + block: Rc>, subblock: Block, } @@ -334,15 +334,14 @@ fn group_by_backedges( let key = (*block).borrow().block.clone(); match backedges_grouped.entry(key) { - Entry::Occupied(mut entry) => { - entry.get_mut().subblock.push(*node) - } - Entry::Vacant(entry) => { + | Entry::Occupied(mut entry) => + entry.get_mut().subblock.push(*node), + | Entry::Vacant(entry) => { entry.insert(BackEdgesGroup { - block: Rc::clone(&block), + block: Rc::clone(&block), subblock: Vec::from([*node]), }); - } + }, } } } @@ -430,8 +429,8 @@ where loop { let (smaller_component, simple_splitter_block) = { let splitter_block = match queue.pop() { - Some(coarse_block) => coarse_block, - None => break, + | Some(coarse_block) => coarse_block, + | None => break, }; let mut simple_blocks_in_splitter_block = splitter_block .simple_blocks_subsets_of_self @@ -451,8 +450,8 @@ where }) .map(|(index, _)| index) { - Some(v) => v, - None => return (None, converter), + | Some(v) => v, + | None => return (None, converter), } }; @@ -579,24 +578,24 @@ where for edge in graph.edge_references() { let source_id = match association_weight_id.get(&edge.source()) { - Some(id) => *id, - None => { + | Some(id) => *id, + | None => { let id = new_graph_a.add_node(last_id); original_nodes.insert(last_id); last_id += 1; association_weight_id.insert(edge.source(), id); id - } + }, }; let target_id = match association_weight_id.get(&edge.target()) { - Some(id) => *id, - None => { + | Some(id) => *id, + | None => { let id = new_graph_a.add_node(last_id); original_nodes.insert(last_id); last_id += 1; association_weight_id.insert(edge.target(), id); id - } + }, }; let weight = *converter_edges.get(edge.weight()).unwrap(); @@ -715,13 +714,12 @@ where let (result, _converter) = match maximum_bisimulation(&[&&new_graph_a, &&new_graph_b]) { - (None, _) => return false, - (Some(val), converter) => ( - check_bisimilarity::( - val, - &converter, - [original_nodes_a, original_nodes_b], - ), + | (None, _) => return false, + | (Some(val), converter) => ( + check_bisimilarity::(val, &converter, [ + original_nodes_a, + original_nodes_b, + ]), converter, ), }; @@ -742,8 +740,8 @@ where } let (result, _converter) = match maximum_bisimulation(&[graph_a, graph_b]) { - (None, _) => return false, - (Some(val), converter) => ( + | (None, _) => return false, + | (Some(val), converter) => ( val.into_iter().find(|el| { let mut keep_track = [false, false]; for e in el { diff --git a/src/rsprocess/choices.rs b/src/rsprocess/choices.rs index c88370b..c8208af 100644 --- a/src/rsprocess/choices.rs +++ b/src/rsprocess/choices.rs @@ -43,10 +43,10 @@ impl BasicChoices for Choices { self.context_moves.is_empty(), choices.context_moves.is_empty(), ) { - (true, true) => {} - (true, false) => self.context_moves = choices.context_moves, - (false, true) => {} - (false, false) => { + | (true, true) => {}, + | (true, false) => self.context_moves = choices.context_moves, + | (false, true) => {}, + | (false, false) => { let mut new_self = vec![]; for item_self in &self.context_moves { for item_choices in &choices.context_moves { @@ -57,7 +57,7 @@ impl BasicChoices for Choices { } } self.context_moves = new_self; - } + }, } } } @@ -155,10 +155,10 @@ impl BasicChoices for PositiveChoices { self.context_moves.is_empty(), choices.context_moves.is_empty(), ) { - (true, true) => {} - (true, false) => self.context_moves = choices.context_moves, - (false, true) => {} - (false, false) => { + | (true, true) => {}, + | (true, false) => self.context_moves = choices.context_moves, + | (false, true) => {}, + | (false, false) => { let mut new_self = vec![]; for item_self in &self.context_moves { for item_choices in &choices.context_moves { @@ -169,7 +169,7 @@ impl BasicChoices for PositiveChoices { } } self.context_moves = new_self; - } + }, } } } diff --git a/src/rsprocess/dot.rs b/src/rsprocess/dot.rs index c4056d8..0a39cf8 100644 --- a/src/rsprocess/dot.rs +++ b/src/rsprocess/dot.rs @@ -4,12 +4,11 @@ static PRINTNAMES: bool = false; use core::fmt::{self, Display, Write}; -use petgraph::{ - data::DataMap, - visit::{ - EdgeRef, GraphProp, IntoEdgeReferences, IntoNodeReferences, - NodeIndexable, NodeRef, - }, + +use petgraph::data::DataMap; +use petgraph::visit::{ + EdgeRef, GraphProp, IntoEdgeReferences, IntoNodeReferences, NodeIndexable, + NodeRef, }; pub struct Dot<'a, G> @@ -190,10 +189,10 @@ where if let Some(rank_dir) = &self.config.RankDir { let value = match rank_dir { - RankDir::TB => "TB", - RankDir::BT => "BT", - RankDir::LR => "LR", - RankDir::RL => "RL", + | RankDir::TB => "TB", + | RankDir::BT => "BT", + | RankDir::LR => "LR", + | RankDir::RL => "RL", }; writeln!(f, "{INDENT}rankdir=\"{value}\"\n")?; } @@ -335,10 +334,10 @@ where fn write_char(&mut self, c: char) -> fmt::Result { match c { - '"' | '\\' => self.0.write_char('\\')?, + | '"' | '\\' => self.0.write_char('\\')?, // \l is for left justified linebreak - '\n' => return self.0.write_str("\\l"), - _ => {} + | '\n' => return self.0.write_str("\\l"), + | _ => {}, } self.0.write_char(c) } diff --git a/src/rsprocess/element.rs b/src/rsprocess/element.rs index 0727734..f15c107 100644 --- a/src/rsprocess/element.rs +++ b/src/rsprocess/element.rs @@ -1,6 +1,7 @@ -use serde::{Deserialize, Serialize}; use std::fmt; +use serde::{Deserialize, Serialize}; + use super::translator::PrintableWithTranslator; pub type IdType = u32; @@ -41,8 +42,8 @@ pub enum IdState { impl fmt::Display for IdState { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Positive => write!(f, "+"), - Self::Negative => write!(f, "-"), + | Self::Positive => write!(f, "+"), + | Self::Negative => write!(f, "-"), } } } @@ -52,8 +53,8 @@ impl std::ops::Not for IdState { fn not(self) -> Self::Output { match self { - Self::Positive => Self::Negative, - Self::Negative => Self::Positive, + | Self::Positive => Self::Negative, + | Self::Negative => Self::Positive, } } } @@ -71,7 +72,7 @@ impl std::ops::Not for IdState { Deserialize, )] pub struct PositiveType { - pub id: IdType, + pub id: IdType, pub state: IdState, } @@ -93,7 +94,7 @@ impl PrintableWithTranslator for PositiveType { impl From<(IdType, IdState)> for PositiveType { fn from(value: (IdType, IdState)) -> Self { Self { - id: value.0, + id: value.0, state: value.1, } } @@ -102,7 +103,7 @@ impl From<(IdType, IdState)> for PositiveType { impl From<(&IdType, &IdState)> for PositiveType { fn from(value: (&IdType, &IdState)) -> Self { Self { - id: *value.0, + id: *value.0, state: *value.1, } } diff --git a/src/rsprocess/environment.rs b/src/rsprocess/environment.rs index dc08d21..7c8c102 100644 --- a/src/rsprocess/environment.rs +++ b/src/rsprocess/environment.rs @@ -1,9 +1,10 @@ -use serde::{Deserialize, Serialize}; use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::rc::Rc; +use serde::{Deserialize, Serialize}; + use super::choices::{BasicChoices, Choices, PositiveChoices}; use super::element::IdType; use super::process::{BasicProcess, PositiveProcess, Process}; @@ -289,26 +290,26 @@ impl BasicEnvironment for Environment { current_entities: &Set, ) -> Result { match context_process { - Process::Nill => Ok(Choices::default()), - Process::RecursiveIdentifier { identifier } => { + | Process::Nill => Ok(Choices::default()), + | Process::RecursiveIdentifier { identifier } => { let newprocess = self.get(*identifier); if let Some(newprocess) = newprocess { self.unfold(newprocess, current_entities) } else { Err(format!("Missing symbol in context: {identifier}")) } - } - Process::EntitySet { + }, + | Process::EntitySet { entities, next_process, } => Ok(Choices::from([( Rc::new(entities.clone()), Rc::clone(next_process), )])), - Process::Guarded { + | Process::Guarded { reaction, next_process, - } => { + } => if reaction.enabled(current_entities) { Ok(Choices::from([( Rc::new(reaction.products.clone()), @@ -316,14 +317,13 @@ impl BasicEnvironment for Environment { )])) } else { Ok(Choices::default()) - } - } - Process::WaitEntity { + }, + | Process::WaitEntity { repeat, repeated_process: _, next_process, } if *repeat <= 0 => self.unfold(next_process, current_entities), - Process::WaitEntity { + | Process::WaitEntity { repeat, repeated_process, next_process, @@ -332,8 +332,8 @@ impl BasicEnvironment for Environment { self.unfold(repeated_process, current_entities)?; choices1.replace(Rc::clone(next_process)); Ok(choices1) - } - Process::WaitEntity { + }, + | Process::WaitEntity { repeat, repeated_process, next_process, @@ -346,20 +346,20 @@ impl BasicEnvironment for Environment { next_process: Rc::clone(next_process), })); Ok(choices1) - } - Process::Summation { children } => { + }, + | Process::Summation { children } => { // short-circuits with try_fold. children.iter().try_fold(Choices::default(), |mut acc, x| { match self.unfold(x, current_entities) { - Ok(mut choices) => { + | Ok(mut choices) => { acc.append(&mut choices); Ok(acc) - } - Err(e) => Err(e), + }, + | Err(e) => Err(e), } }) - } - Process::NondeterministicChoice { children } => { + }, + | Process::NondeterministicChoice { children } => { // short-circuits with try_fold. if children.is_empty() { Ok(Choices::from(vec![( @@ -375,7 +375,7 @@ impl BasicEnvironment for Environment { }, ) } - } + }, } } } @@ -458,9 +458,9 @@ impl From> for Environment { impl Environment { /// Two set of entities E1 and E2 are confluent w.r.t. the perpetual context /// delta iff they reach the same loop. - /// confluent checks if all the sets of entities in ```entities``` are confluent - /// and if so returns the maximal length of prefixes traversed to reached the - /// loop, its dimension (length) and the loop. + /// confluent checks if all the sets of entities in ```entities``` are + /// confluent and if so returns the maximal length of prefixes traversed + /// to reached the loop, its dimension (length) and the loop. /// see confluent, confluents pub fn confluent( &self, @@ -491,12 +491,12 @@ impl Environment { Some((max_distance, dimension, hoop)) } - /// Two set of entities E1 and E2 are confluent w.r.t. the perpetual context Q - /// iff they reach the same loop. - /// The predicate confluent(Rs,Q,Es,Loop,Distance,Dimension) checks if all the - /// sets of entities in Es are confluent and if so returns the Loop, the maximal - /// length of prefixes traversed to reached the loop and its dimension (length). - /// see confluent, confluents + /// Two set of entities E1 and E2 are confluent w.r.t. the perpetual context + /// Q iff they reach the same loop. + /// The predicate confluent(Rs,Q,Es,Loop,Distance,Dimension) checks if all + /// the sets of entities in Es are confluent and if so returns the Loop, + /// the maximal length of prefixes traversed to reached the loop and its + /// dimension (length). see confluent, confluents pub fn confluent_named( &self, reaction_rules: &[Reaction], @@ -531,8 +531,8 @@ impl Environment { } /// invariant_named checks if all the sets of entities in ```entities``` are - /// confluent and if so returns the set of all traversed states, together with - /// the loop. + /// confluent and if so returns the set of all traversed states, together + /// with the loop. /// see invariant pub fn invariant_named( &self, @@ -575,15 +575,15 @@ impl Environment { /// Suppose the context has the form /// Q1. ... Q1.Q2. ... Q2. ... Qn. ... Qn. ... - /// and that each context Q1, Q2, ... , Q(n-1) is provided for a large number - /// of times, enough to stabilize the system in a loop (while Qn is provided - /// infinitely many times). Then it can be the case that when the context - /// switches from Qi to Q(i+1), no matter what is the current state of the loop - /// for Qi at the moment of the switching, the system will stabilize in the same - /// loop for Q(i+1): if this is the case the system is called "loop confluent". - /// loop_confluent_named checks this property over the list of contexts - /// [Q1,Q2,...,Qn] and returns the lists of Loops, Distances and Dimensions for - /// all Qi's. + /// and that each context Q1, Q2, ... , Q(n-1) is provided for a large + /// number of times, enough to stabilize the system in a loop (while Qn + /// is provided infinitely many times). Then it can be the case that + /// when the context switches from Qi to Q(i+1), no matter what is the + /// current state of the loop for Qi at the moment of the switching, the + /// system will stabilize in the same loop for Q(i+1): if this is the + /// case the system is called "loop confluent". loop_confluent_named + /// checks this property over the list of contexts [Q1,Q2,...,Qn] and + /// returns the lists of Loops, Distances and Dimensions for all Qi's. /// see loop_confluent pub fn loop_confluent_named( deltas: &[Self], @@ -600,8 +600,8 @@ impl Environment { /// "strong confluence" requires loop confluence and additionally check /// that even if the context is switched BEFORE REACHING THE LOOP for Qi /// the traversed states are still confluent for Q(i+1) - /// IMPORTANT: this notion of confluence assumes each context can be executed 0 - /// or more times + /// IMPORTANT: this notion of confluence assumes each context can be + /// executed 0 or more times /// see strong_confluent #[allow(clippy::type_complexity)] pub fn strong_confluent_named( @@ -656,26 +656,26 @@ impl BasicEnvironment for PositiveEnvironment { entities: &Self::Set, ) -> Result { match context { - PositiveProcess::Nill => Ok(Self::Choices::default()), - PositiveProcess::RecursiveIdentifier { identifier } => { + | PositiveProcess::Nill => Ok(Self::Choices::default()), + | PositiveProcess::RecursiveIdentifier { identifier } => { let newprocess = self.get(*identifier); if let Some(newprocess) = newprocess { self.unfold(newprocess, entities) } else { Err(format!("Missing symbol in context: {identifier}")) } - } - PositiveProcess::EntitySet { + }, + | PositiveProcess::EntitySet { entities, next_process, } => Ok(Self::Choices::from([( Rc::new(entities.clone()), Rc::clone(next_process), )])), - PositiveProcess::Guarded { + | PositiveProcess::Guarded { reaction, next_process, - } => { + } => if reaction.enabled(entities) { Ok(Self::Choices::from([( Rc::new(reaction.products.clone()), @@ -683,14 +683,13 @@ impl BasicEnvironment for PositiveEnvironment { )])) } else { Ok(Self::Choices::default()) - } - } - PositiveProcess::WaitEntity { + }, + | PositiveProcess::WaitEntity { repeat, repeated_process: _, next_process, } if *repeat <= 0 => self.unfold(next_process, entities), - PositiveProcess::WaitEntity { + | PositiveProcess::WaitEntity { repeat, repeated_process, next_process, @@ -698,8 +697,8 @@ impl BasicEnvironment for PositiveEnvironment { let mut choices1 = self.unfold(repeated_process, entities)?; choices1.replace(Rc::clone(next_process)); Ok(choices1) - } - PositiveProcess::WaitEntity { + }, + | PositiveProcess::WaitEntity { repeat, repeated_process, next_process, @@ -711,21 +710,21 @@ impl BasicEnvironment for PositiveEnvironment { next_process: Rc::clone(next_process), })); Ok(choices1) - } - PositiveProcess::Summation { children } => { + }, + | PositiveProcess::Summation { children } => { // short-circuits with try_fold. children.iter().try_fold( Self::Choices::default(), |mut acc, x| match self.unfold(x, entities) { - Ok(mut choices) => { + | Ok(mut choices) => { acc.append(&mut choices); Ok(acc) - } - Err(e) => Err(e), + }, + | Err(e) => Err(e), }, ) - } - PositiveProcess::NondeterministicChoice { children } => { + }, + | PositiveProcess::NondeterministicChoice { children } => { // short-circuits with try_fold. if children.is_empty() { Ok(Self::Choices::from(vec![( @@ -741,7 +740,7 @@ impl BasicEnvironment for PositiveEnvironment { }, ) } - } + }, } } } diff --git a/src/rsprocess/format_helpers.rs b/src/rsprocess/format_helpers.rs index 46e8092..79cd504 100644 --- a/src/rsprocess/format_helpers.rs +++ b/src/rsprocess/format_helpers.rs @@ -1,8 +1,9 @@ pub mod graph_map_nodes_ty_from { + use std::rc::Rc; + use super::super::set::{BasicSet, Set}; use super::super::system::System; use super::super::translator; - use std::rc::Rc; type GraphMapNodesFnTy = dyn Fn(petgraph::prelude::NodeIndex, &System) -> String; @@ -70,10 +71,11 @@ pub mod graph_map_nodes_ty_from { } pub mod graph_map_edges_ty_from { + use std::rc::Rc; + use super::super::label::Label; use super::super::set::{BasicSet, Set}; use super::super::translator; - use std::rc::Rc; type GraphMapEdgesFnTy<'a> = dyn Fn(petgraph::prelude::EdgeIndex, &'a Label) -> String + 'a; @@ -233,9 +235,10 @@ pub mod graph_map_edges_ty_from { } pub mod node_formatter { + use std::rc::Rc; + use petgraph::visit::IntoNodeReferences; use petgraph::{Directed, Graph}; - use std::rc::Rc; use super::super::element::IdType; use super::super::graph::{OperationType, SystemGraph}; @@ -272,15 +275,12 @@ pub mod node_formatter { Box::new(move |_, n| { let rssystem = original_graph.node_weight(n.0).unwrap(); match (Some(s) == star, &rssystem.context_process) { - (true, Process::RecursiveIdentifier { identifier: _ }) => { - Some(", fillcolor=".to_string() + &color) - } - (false, Process::RecursiveIdentifier { identifier: id }) + | (true, Process::RecursiveIdentifier { identifier: _ }) => + Some(", fillcolor=".to_string() + &color), + | (false, Process::RecursiveIdentifier { identifier: id }) if id == &s => - { - Some(", fillcolor=".to_string() + &color) - } - _ => None, + Some(", fillcolor=".to_string() + &color), + | _ => None, } }) } @@ -295,13 +295,12 @@ pub mod node_formatter { Box::new(move |_, n| { let rssystem = original_graph.node_weight(n.0).unwrap(); match &rssystem.context_process { - Process::EntitySet { + | Process::EntitySet { entities, next_process: _, - } if ot.evaluate(entities, &set) => { - Some(", fillcolor=".to_string() + &color) - } - _ => None, + } if ot.evaluate(entities, &set) => + Some(", fillcolor=".to_string() + &color), + | _ => None, } }) } @@ -378,9 +377,10 @@ pub mod node_formatter { } pub mod edge_formatter { + use std::rc::Rc; + use petgraph::visit::{EdgeRef, IntoEdgeReferences}; use petgraph::{Directed, Graph}; - use std::rc::Rc; use super::super::graph::{OperationType, SystemGraph}; use super::super::set::Set; diff --git a/src/rsprocess/graph.rs b/src/rsprocess/graph.rs index 0750116..e040966 100644 --- a/src/rsprocess/graph.rs +++ b/src/rsprocess/graph.rs @@ -1,8 +1,9 @@ //! Definitions for generating graphs from a simulation. +use std::rc::Rc; + use petgraph::visit::{IntoEdgeReferences, IntoNodeReferences}; use petgraph::{Directed, Graph}; -use std::rc::Rc; use super::element::IdType; use super::label::Label; @@ -16,8 +17,8 @@ fn common_system_entities(graph: &SystemGraph) -> Set { graph .node_references() .fold(None, |acc, node| match acc { - None => Some(node.1.available_entities.clone()), - Some(acc) => Some(node.1.available_entities.intersection(&acc)), + | None => Some(node.1.available_entities.clone()), + | Some(acc) => Some(node.1.available_entities.intersection(&acc)), }) .unwrap_or(Set::default()) } @@ -35,8 +36,8 @@ macro_rules! common_label { .fold(None, |$acc_name, $edge_name| { let $edge_name = $edge_name.weight(); match $acc_name { - None => Some($empty_expr), - Some($acc_name) => Some($some_expr), + | None => Some($empty_expr), + | Some($acc_name) => Some($some_expr), } }) .unwrap_or(Set::default()) @@ -134,8 +135,8 @@ impl<'a> MapEdges<'a, System, Label, Directed, u32> for SystemGraph { .enumerate() .map(|(i, edge)| { match edge_map.execute(self, &EdgeIndex::new(i), translator) { - Err(e) => Err(e), - Ok(val) => Ok((edge.source(), edge.target(), val)), + | Err(e) => Err(e), + | Ok(val) => Ok((edge.source(), edge.target(), val)), } }) .collect::, _>>()?; @@ -178,22 +179,22 @@ fn match_node_display<'a>( common_entities: Rc, translator: Rc, ) -> Box> { - use super::format_helpers::graph_map_nodes_ty_from::*; use NodeDisplayBase::*; + use super::format_helpers::graph_map_nodes_ty_from::*; + match base { - String { string } => format_string(string.clone()), - Hide => format_hide(translator), - Entities => format_entities(translator), - MaskEntities { mask } => format_mask_entities(translator, mask.clone()), - ExcludeEntities { mask } => { - format_exclude_entities(translator, mask.clone()) - } - Context => format_context(translator), - UncommonEntities => { - format_exclude_entities(translator, (*common_entities).clone()) - } - MaskUncommonEntities { mask } => format_exclude_entities( + | String { string } => format_string(string.clone()), + | Hide => format_hide(translator), + | Entities => format_entities(translator), + | MaskEntities { mask } => + format_mask_entities(translator, mask.clone()), + | ExcludeEntities { mask } => + format_exclude_entities(translator, mask.clone()), + | Context => format_context(translator), + | UncommonEntities => + format_exclude_entities(translator, (*common_entities).clone()), + | MaskUncommonEntities { mask } => format_exclude_entities( translator, mask.intersection(&common_entities), ), @@ -299,16 +300,17 @@ fn match_edge_display<'a>( translator: Rc, common: CommonEntities, ) -> Box> { - use super::format_helpers::graph_map_edges_ty_from::*; use EdgeDisplayBase::*; + use super::format_helpers::graph_map_edges_ty_from::*; + match base { - String { string } => format_string(translator, string.clone()), - Hide => format_hide(translator), - Products { + | String { string } => format_string(translator, string.clone()), + | Hide => format_hide(translator), + | Products { mask, filter_common, - } => { + } => if *filter_common { format_products( translator, @@ -317,12 +319,11 @@ fn match_edge_display<'a>( ) } else { format_products(translator, mask.clone(), None) - } - } - Entities { + }, + | Entities { mask, filter_common, - } => { + } => if *filter_common { format_entities( translator, @@ -331,12 +332,11 @@ fn match_edge_display<'a>( ) } else { format_entities(translator, mask.clone(), None) - } - } - Context { + }, + | Context { mask, filter_common, - } => { + } => if *filter_common { format_context( translator, @@ -345,12 +345,11 @@ fn match_edge_display<'a>( ) } else { format_context(translator, mask.clone(), None) - } - } - Union { + }, + | Union { mask, filter_common, - } => { + } => if *filter_common { format_union( translator, @@ -359,12 +358,11 @@ fn match_edge_display<'a>( ) } else { format_union(translator, mask.clone(), None) - } - } - Difference { + }, + | Difference { mask, filter_common, - } => { + } => if *filter_common { format_difference( translator, @@ -373,12 +371,11 @@ fn match_edge_display<'a>( ) } else { format_difference(translator, mask.clone(), None) - } - } - EntitiesDeleted { + }, + | EntitiesDeleted { mask, filter_common, - } => { + } => if *filter_common { format_entities_deleted( translator, @@ -387,12 +384,11 @@ fn match_edge_display<'a>( ) } else { format_entities_deleted(translator, mask.clone(), None) - } - } - EntitiesAdded { + }, + | EntitiesAdded { mask, filter_common, - } => { + } => if *filter_common { format_entities_added( translator, @@ -401,8 +397,7 @@ fn match_edge_display<'a>( ) } else { format_entities_added(translator, mask.clone(), None) - } - } + }, } } @@ -556,11 +551,11 @@ pub enum OperationType { impl OperationType { pub fn evaluate(&self, a: &Set, b: &Set) -> bool { match self { - Self::Equals => a.is_subset(b) && b.is_subset(a), - Self::Subset => a.is_subset(b) && !b.is_subset(a), - Self::SubsetEqual => a.is_subset(b), - Self::Superset => b.is_subset(a) && !a.is_subset(b), - Self::SupersetEqual => b.is_subset(a), + | Self::Equals => a.is_subset(b) && b.is_subset(a), + | Self::Subset => a.is_subset(b) && !b.is_subset(a), + | Self::SubsetEqual => a.is_subset(b), + | Self::Superset => b.is_subset(a) && !a.is_subset(b), + | Self::SupersetEqual => b.is_subset(a), } } } @@ -584,7 +579,7 @@ pub enum NodeColorConditional { #[derive(Clone)] pub struct NodeColor { pub conditionals: Vec<(NodeColorConditional, String)>, - pub base_color: String, + pub base_color: String, } #[inline(always)] @@ -601,52 +596,48 @@ fn match_node_color_conditional<'a>( ) -> Box> { use super::format_helpers::node_formatter::*; match rule { - NodeColorConditional::ContextConditional(ccc) => match ccc { - ContextColorConditional::Nill => { - format_nill(Rc::clone(&original_graph), color.to_string(), star) - } - ContextColorConditional::RecursiveIdentifier(s) => { + | NodeColorConditional::ContextConditional(ccc) => match ccc { + | ContextColorConditional::Nill => + format_nill(Rc::clone(&original_graph), color.to_string(), star), + | ContextColorConditional::RecursiveIdentifier(s) => format_recursive_identifier( Rc::clone(&original_graph), color.to_string(), star, *s, - ) - } - ContextColorConditional::EntitySet(ot, set) => format_entity_set( + ), + | ContextColorConditional::EntitySet(ot, set) => format_entity_set( Rc::clone(&original_graph), color.to_string(), star, *ot, set.clone(), ), - ContextColorConditional::NonDeterministicChoice => { + | ContextColorConditional::NonDeterministicChoice => format_non_deterministic_choice( Rc::clone(&original_graph), color.to_string(), star, - ) - } - ContextColorConditional::Summation => format_summation( + ), + | ContextColorConditional::Summation => format_summation( Rc::clone(&original_graph), color.to_string(), star, ), - ContextColorConditional::WaitEntity => format_wait_entity( + | ContextColorConditional::WaitEntity => format_wait_entity( Rc::clone(&original_graph), color.to_string(), star, ), }, - NodeColorConditional::EntitiesConditional(ot, set) => { + | NodeColorConditional::EntitiesConditional(ot, set) => format_entities_conditional( Rc::clone(&original_graph), color.to_string(), star, *ot, set.clone(), - ) - } + ), } } @@ -702,7 +693,7 @@ pub enum EdgeColorConditional { #[derive(Clone)] pub struct EdgeColor { pub conditionals: Vec<(EdgeColorConditional, String)>, - pub base_color: String, + pub base_color: String, } fn edge_formatter_base_color(base_color: String) -> String { @@ -716,53 +707,51 @@ fn match_edge_color_conditional<'a>( ) -> Box> { use super::format_helpers::edge_formatter::*; match rule { - EdgeColorConditional::Entities(ot, set) => format_entities( + | EdgeColorConditional::Entities(ot, set) => format_entities( Rc::clone(&original_graph), color.to_string(), *ot, set.clone(), ), - EdgeColorConditional::Context(ot, set) => format_context( + | EdgeColorConditional::Context(ot, set) => format_context( Rc::clone(&original_graph), color.to_string(), *ot, set.clone(), ), - EdgeColorConditional::T(ot, set) => format_t( + | EdgeColorConditional::T(ot, set) => format_t( Rc::clone(&original_graph), color.to_string(), *ot, set.clone(), ), - EdgeColorConditional::Reactants(ot, set) => format_reactants( + | EdgeColorConditional::Reactants(ot, set) => format_reactants( Rc::clone(&original_graph), color.to_string(), *ot, set.clone(), ), - EdgeColorConditional::ReactantsAbsent(ot, set) => { + | EdgeColorConditional::ReactantsAbsent(ot, set) => format_reactants_absent( Rc::clone(&original_graph), color.to_string(), *ot, set.clone(), - ) - } - EdgeColorConditional::Inhibitors(ot, set) => format_inhibitors( + ), + | EdgeColorConditional::Inhibitors(ot, set) => format_inhibitors( Rc::clone(&original_graph), color.to_string(), *ot, set.clone(), ), - EdgeColorConditional::InhibitorsPresent(ot, set) => { + | EdgeColorConditional::InhibitorsPresent(ot, set) => format_inhibitors_present( Rc::clone(&original_graph), color.to_string(), *ot, set.clone(), - ) - } - EdgeColorConditional::Products(ot, set) => format_products( + ), + | EdgeColorConditional::Products(ot, set) => format_products( Rc::clone(&original_graph), color.to_string(), *ot, diff --git a/src/rsprocess/label.rs b/src/rsprocess/label.rs index e6f0471..5624730 100644 --- a/src/rsprocess/label.rs +++ b/src/rsprocess/label.rs @@ -1,7 +1,8 @@ -use serde::{Deserialize, Serialize}; use std::fmt::Debug; use std::hash::Hash; +use serde::{Deserialize, Serialize}; + use super::set::{BasicSet, PositiveSet, Set}; use super::translator::{Formatter, PrintableWithTranslator, Translator}; diff --git a/src/rsprocess/presets.rs b/src/rsprocess/presets.rs index e66d235..1507699 100644 --- a/src/rsprocess/presets.rs +++ b/src/rsprocess/presets.rs @@ -1,23 +1,21 @@ //! Module that holds useful presets for interacting with other modules. +use std::collections::HashMap; +use std::fmt::Display; +use std::io::prelude::*; +use std::rc::Rc; +use std::{env, fs, io}; + use lalrpop_util::ParseError; use petgraph::Graph; -use std::collections::HashMap; -use std::env; -use std::fmt::Display; -use std::fs; -use std::io; -use std::io::prelude::*; -use std::rc::Rc; +use super::super::grammar; use super::graph::MapEdges; use super::set::Set; use super::system::ExtensionsSystem; use super::translator::Translator; use super::*; -use super::super::grammar; - // ----------------------------------------------------------------------------- // Structures // ----------------------------------------------------------------------------- @@ -25,29 +23,29 @@ use super::super::grammar; /// Describes how the result of some computation has to be saved. pub struct SaveOptions { pub print: bool, - pub save: Option>, + pub save: Option>, } impl SaveOptions { pub fn combine(&mut self, other: &mut Self) { self.print = self.print || other.print; match (self.save.is_some(), other.save.is_some()) { - (false, false) | (true, false) => {} - (false, true) => { + | (false, false) | (true, false) => {}, + | (false, true) => { self.save = other.save.to_owned(); - } - (true, true) => { + }, + | (true, true) => { self.save .as_mut() .unwrap() .append(other.save.as_mut().unwrap()); - } + }, } } pub fn new() -> Self { SaveOptions { print: false, - save: None, + save: None, } } } @@ -90,7 +88,7 @@ pub enum Instruction { }, Loop { symbol: String, - so: SaveOptions, + so: SaveOptions, }, Frequency { so: SaveOptions, @@ -105,7 +103,7 @@ pub enum Instruction { }, Digraph { group: Option>, - gso: Vec, + gso: Vec, }, Bisimilarity { system_b: String, @@ -128,14 +126,14 @@ impl System { translator: Translator, ) -> Result { match self { - Self::System { sys } => Ok(EvaluatedSystem::System { + | Self::System { sys } => Ok(EvaluatedSystem::System { sys: sys.to_owned(), translator, }), - Self::Deserialize { path } => { + | Self::Deserialize { path } => { let (graph, translator) = deserialize(path.into())?; Ok(EvaluatedSystem::Graph { graph, translator }) - } + }, } } } @@ -143,7 +141,7 @@ impl System { #[derive(Clone)] pub enum EvaluatedSystem { Graph { - graph: graph::SystemGraph, + graph: graph::SystemGraph, translator: Translator, }, System { @@ -155,11 +153,11 @@ pub enum EvaluatedSystem { impl EvaluatedSystem { pub fn get_translator(&mut self) -> &mut Translator { match self { - EvaluatedSystem::Graph { + | EvaluatedSystem::Graph { graph: _, translator, } => translator, - EvaluatedSystem::System { sys: _, translator } => translator, + | EvaluatedSystem::System { sys: _, translator } => translator, } } } @@ -184,21 +182,23 @@ where { // relative path let mut path = match env::current_dir() { - Ok(p) => p, - Err(e) => return Err(format!("Error getting current directory: {e}")), + | Ok(p) => p, + | Err(e) => { + return Err(format!("Error getting current directory: {e}")); + }, }; path = path.join(path_string); // we read the file with a buffer let f = match fs::File::open(path) { - Ok(f) => f, - Err(e) => return Err(format!("Error opening file: {e}.")), + | Ok(f) => f, + | Err(e) => return Err(format!("Error opening file: {e}.")), }; let mut buf_reader = io::BufReader::new(f); let mut contents = String::new(); match buf_reader.read_to_string(&mut contents) { - Ok(_) => {} - Err(e) => return Err(format!("Error reading file: {e}")), + | Ok(_) => {}, + | Err(e) => return Err(format!("Error reading file: {e}")), } // parse @@ -215,18 +215,17 @@ where T: Display, { match e { - ParseError::ExtraToken { token: (l, t, r) } => Err(format!( + | ParseError::ExtraToken { token: (l, t, r) } => Err(format!( "Unexpected token \"{t}\" \ between positions {l} and {r}." )), - ParseError::UnrecognizedEof { + | ParseError::UnrecognizedEof { location: _, expected: _, } => Err("End of file encountered while parsing.".into()), - ParseError::InvalidToken { location } => { - Err(format!("Invalid token at position {location}.")) - } - ParseError::UnrecognizedToken { + | ParseError::InvalidToken { location } => + Err(format!("Invalid token at position {location}.")), + | ParseError::UnrecognizedToken { token: (l, t, r), expected, } => { @@ -289,8 +288,8 @@ where } Err(err) - } - ParseError::User { error } => Err(error.to_string()), + }, + | ParseError::User { error } => Err(error.to_string()), } } @@ -299,8 +298,8 @@ fn parser_experiment( contents: String, ) -> Result<(Vec, Vec), String> { match grammar::ExperimentParser::new().parse(translator, &contents) { - Ok(sys) => Ok(sys), - Err(e) => reformat_error(e, &contents), + | Ok(sys) => Ok(sys), + | Err(e) => reformat_error(e, &contents), } } @@ -309,31 +308,31 @@ fn parser_instructions( contents: String, ) -> Result { match grammar::RunParser::new().parse(translator, &contents) { - Ok(sys) => Ok(sys), - Err(e) => reformat_error(e, &contents), + | Ok(sys) => Ok(sys), + | Err(e) => reformat_error(e, &contents), } } fn save_file(contents: &String, path_string: String) -> Result<(), String> { // relative path let mut path = match env::current_dir() { - Ok(p) => p, - Err(_) => return Err("Error getting current directory.".into()), + | Ok(p) => p, + | Err(_) => return Err("Error getting current directory.".into()), }; path = path.join(path_string); let mut f = match fs::File::create(&path) { - Ok(f) => f, - Err(_) => { + | Ok(f) => f, + | Err(_) => { return Err(format!( "Error creating file {}.", path.to_str().unwrap() )); - } + }, }; match write!(f, "{contents}") { - Ok(_) => {} - Err(_) => return Err("Error writing to file.".into()), + | Ok(_) => {}, + | Err(_) => return Err("Error writing to file.".into()), } Ok(()) } @@ -346,15 +345,14 @@ fn save_file(contents: &String, path_string: String) -> Result<(), String> { /// Equivalent main_do(stat) or main_do(stat, MissingE) pub fn stats(system: &EvaluatedSystem) -> Result { match system { - EvaluatedSystem::System { sys, translator } => { - Ok(sys.statistics(translator)) - } - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::System { sys, translator } => + Ok(sys.statistics(translator)), + | EvaluatedSystem::Graph { graph, translator } => { let Some(sys) = graph.node_weights().next() else { return Err("No node found in graph.".into()); }; Ok(sys.statistics(translator)) - } + }, } } @@ -363,15 +361,14 @@ pub fn stats(system: &EvaluatedSystem) -> Result { /// Equivalent to main_do(target, E) pub fn target(system: &EvaluatedSystem) -> Result { let (res, translator) = match system { - EvaluatedSystem::System { sys, translator } => { - (sys.target()?, translator) - } - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::System { sys, translator } => + (sys.target()?, translator), + | EvaluatedSystem::Graph { graph, translator } => { let Some(sys) = graph.node_weights().next() else { return Err("No node found in graph.".into()); }; (sys.target()?, translator) - } + }, }; Ok(format!( "After {} steps we arrive at state:\n{}", @@ -386,15 +383,14 @@ pub fn target(system: &EvaluatedSystem) -> Result { /// equivalent to main_do(run,Es) pub fn traversed(system: &EvaluatedSystem) -> Result { let (res, translator) = match system { - EvaluatedSystem::System { sys, translator } => { - (sys.run_separated()?, translator) - } - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::System { sys, translator } => + (sys.run_separated()?, translator), + | EvaluatedSystem::Graph { graph, translator } => { let Some(sys) = graph.node_weights().next() else { return Err("No node found in graph.".into()); }; (sys.run_separated()?, translator) - } + }, }; let mut output = String::new(); @@ -420,23 +416,23 @@ pub fn hoop( use system::LoopSystem; let (res, translator) = match system { - EvaluatedSystem::System { sys, translator } => (sys, translator), - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::System { sys, translator } => (sys, translator), + | EvaluatedSystem::Graph { graph, translator } => { let Some(sys) = graph.node_weights().next() else { return Err("No node found in graph.".into()); }; (sys, translator) - } + }, }; // we retrieve the id for "x" and use it to find the corresponding loop let Some(id) = translator.encode_not_mut(&symbol) else { return Err(format!("Symbol {symbol} not found.")); }; let res = match res.lollipops_only_loop_named(id) { - Some(o) => o, - None => { + | Some(o) => o, + | None => { return Err("No loop found.".into()); - } + }, }; let mut output = String::new(); @@ -459,13 +455,13 @@ pub fn freq(system: &EvaluatedSystem) -> Result { use frequency::BasicFrequency; let (sys, translator) = match system { - EvaluatedSystem::System { sys, translator } => (sys, translator), - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::System { sys, translator } => (sys, translator), + | EvaluatedSystem::Graph { graph, translator } => { let Some(sys) = graph.node_weights().next() else { return Err("No node found in graph.".into()); }; (sys, translator) - } + }, }; let res = frequency::Frequency::naive_frequency(sys)?; @@ -486,13 +482,13 @@ pub fn limit_freq( use frequency::BasicFrequency; let (sys, translator): (&system::System, &mut Translator) = match system { - EvaluatedSystem::System { sys, translator } => (sys, translator), - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::System { sys, translator } => (sys, translator), + | EvaluatedSystem::Graph { graph, translator } => { let Some(sys) = graph.node_weights().next() else { return Err("No node found in graph.".into()); }; (sys, translator) - } + }, }; let (_, sets) = read_file(translator, experiment, parser_experiment)?; @@ -502,10 +498,10 @@ pub fn limit_freq( &sys.reaction_rules, &sys.available_entities, ) { - Some(e) => e, - None => { + | Some(e) => e, + | None => { return Err("Error calculating frequency.".into()); - } + }, }; Ok(format!( @@ -526,13 +522,13 @@ pub fn fast_freq( use frequency::BasicFrequency; let (sys, translator): (&system::System, &mut Translator) = match system { - EvaluatedSystem::System { sys, translator } => (sys, translator), - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::System { sys, translator } => (sys, translator), + | EvaluatedSystem::Graph { graph, translator } => { let Some(sys) = graph.node_weights().next() else { return Err("No node found in graph".into()); }; (sys, translator) - } + }, }; let (weights, sets) = read_file(translator, experiment, parser_experiment)?; @@ -543,10 +539,10 @@ pub fn fast_freq( &sys.available_entities, &weights, ) { - Some(e) => e, - None => { + | Some(e) => e, + | None => { return Err("Error calculating frequency.".into()); - } + }, }; Ok(format!( @@ -560,7 +556,7 @@ pub fn fast_freq( pub fn digraph(system: &mut EvaluatedSystem) -> Result<(), String> { if let EvaluatedSystem::System { sys, translator } = system { *system = EvaluatedSystem::Graph { - graph: sys.digraph()?, + graph: sys.digraph()?, translator: translator.to_owned(), }; } @@ -638,10 +634,9 @@ pub fn bisimilar( .system .compute(system_a.get_translator().clone())? { - EvaluatedSystem::System { sys, translator } => { - EvaluatedSystem::System { sys, translator } - } - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::System { sys, translator } => + EvaluatedSystem::System { sys, translator }, + | EvaluatedSystem::Graph { graph, translator } => { if translator != *system_a.get_translator() { return Err("Bisimilarity not implemented for systems with \ different encodings. Serialize the systems \ @@ -649,7 +644,7 @@ pub fn bisimilar( .into()); } EvaluatedSystem::Graph { graph, translator } - } + }, }; digraph(system_a)?; @@ -657,7 +652,7 @@ pub fn bisimilar( // since we ran digraph on both they have to be graphs match (system_a, &mut system_b) { - ( + | ( EvaluatedSystem::Graph { graph: a, translator: _, @@ -673,14 +668,15 @@ pub fn bisimilar( b.map_edges(edge_relabeler, translator_b)?; Ok(format!( "{}", - // bisimilarity::bisimilarity_kanellakis_smolka::bisimilarity(&&a, &&b) + // bisimilarity::bisimilarity_kanellakis_smolka::bisimilarity(& + // &a, &&b) // bisimilarity::bisimilarity_paige_tarjan::bisimilarity_ignore_labels(&&a, &&b) bisimilarity::bisimilarity_paige_tarkan::bisimilarity(&&a, &&b) )) - } - _ => { + }, + | _ => { unreachable!() - } + }, } } @@ -697,11 +693,11 @@ pub fn dot( edge_color: graph::EdgeColor, ) -> Result { match system { - EvaluatedSystem::System { + | EvaluatedSystem::System { sys: _, translator: _, } => Err("Supplied system is not a graph".into()), - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::Graph { graph, translator } => { let rc_translator = Rc::new(translator.clone()); let modified_graph = graph.map( node_display.generate(Rc::clone(&rc_translator), graph), @@ -722,7 +718,7 @@ pub fn dot( ); Ok(format!("{dot}")) - } + }, } } @@ -733,11 +729,11 @@ pub fn graphml( edge_display: graph::EdgeDisplay, ) -> Result { match system { - EvaluatedSystem::System { + | EvaluatedSystem::System { sys: _, translator: _, } => Err("Supplied system is not a graph".into()), - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::Graph { graph, translator } => { let rc_translator = Rc::new(translator.to_owned()); // map each value to the corresponding value we want to display @@ -753,7 +749,7 @@ pub fn graphml( .export_edge_weights_display(); Ok(format!("{graphml}")) - } + }, } } @@ -762,30 +758,30 @@ pub fn graphml( /// deserialization. pub fn serialize(system: &EvaluatedSystem, path: String) -> Result<(), String> { match system { - EvaluatedSystem::System { + | EvaluatedSystem::System { sys: _, translator: _, } => Err("Supplied system is not a graph".into()), - EvaluatedSystem::Graph { graph, translator } => { + | EvaluatedSystem::Graph { graph, translator } => { // relative path let mut path = std::path::PathBuf::from(path); path.set_extension("cbor"); let f = match fs::File::create(&path) { - Ok(f) => f, - Err(_) => { + | Ok(f) => f, + | Err(_) => { return Err(format!( "Error creating file {}.", path.to_str().unwrap() )); - } + }, }; match serialize::ser(f, graph, translator) { - Ok(_) => Ok(()), - Err(_) => Err("Error during serialization.".into()), + | Ok(_) => Ok(()), + | Err(_) => Err("Error during serialization.".into()), } - } + }, } } @@ -797,25 +793,25 @@ pub fn deserialize( ) -> Result<(graph::SystemGraph, Translator), String> { // relative path let mut path = match env::current_dir() { - Ok(p) => p, - Err(_) => return Err("Error getting current directory.".into()), + | Ok(p) => p, + | Err(_) => return Err("Error getting current directory.".into()), }; path = path.join(input_path); path.set_extension("cbor"); let f = match fs::File::open(&path) { - Ok(f) => f, - Err(_) => { + | Ok(f) => f, + | Err(_) => { return Err(format!( "Error opening file {}.", path.to_str().unwrap() )); - } + }, }; match serialize::de(f) { - Ok(a) => Ok(a), - Err(_) => Err("Error during deserialization.".into()), + | Ok(a) => Ok(a), + | Err(_) => Err("Error during deserialization.".into()), } } @@ -843,28 +839,28 @@ fn execute( system: &mut EvaluatedSystem, ) -> Result<(), String> { match instruction { - Instruction::Stats { so } => { + | Instruction::Stats { so } => { save_options!(stats(system)?, so); - } - Instruction::Target { so } => { + }, + | Instruction::Target { so } => { save_options!(target(system)?, so); - } - Instruction::Run { so } => { + }, + | Instruction::Run { so } => { save_options!(traversed(system)?, so); - } - Instruction::Loop { symbol, so } => { + }, + | Instruction::Loop { symbol, so } => { save_options!(hoop(system, symbol)?, so); - } - Instruction::Frequency { so } => { + }, + | Instruction::Frequency { so } => { save_options!(freq(system)?, so); - } - Instruction::LimitFrequency { experiment, so } => { + }, + | Instruction::LimitFrequency { experiment, so } => { save_options!(limit_freq(system, experiment)?, so); - } - Instruction::FastFrequency { experiment, so } => { + }, + | Instruction::FastFrequency { experiment, so } => { save_options!(fast_freq(system, experiment)?, so); - } - Instruction::Digraph { group, gso } => { + }, + | Instruction::Digraph { group, gso } => { let mut graph = system.clone(); digraph(&mut graph)?; if let Some(group) = group { @@ -873,7 +869,7 @@ fn execute( } for save in gso { match save { - GraphSaveOptions::Dot { + | GraphSaveOptions::Dot { node_display: nd, edge_display: ed, node_color: nc, @@ -881,28 +877,28 @@ fn execute( so, } => { save_options!(dot(&graph, nd, ed, nc, ec)?, so); - } - GraphSaveOptions::GraphML { + }, + | GraphSaveOptions::GraphML { node_display: nd, edge_display: ed, so, } => { save_options!(graphml(&graph, nd, ed)?, so); - } - GraphSaveOptions::Serialize { path } => { + }, + | GraphSaveOptions::Serialize { path } => { serialize(&graph, path)?; - } + }, } } - } - Instruction::Bisimilarity { + }, + | Instruction::Bisimilarity { system_b, edge_relabeler, so, } => { edge_relabeler.typecheck()?; save_options!(bisimilar(system, &edge_relabeler, system_b)?, so); - } + }, } Ok(()) } diff --git a/src/rsprocess/process.rs b/src/rsprocess/process.rs index cd7f0df..13f0bdb 100644 --- a/src/rsprocess/process.rs +++ b/src/rsprocess/process.rs @@ -1,9 +1,10 @@ -use serde::{Deserialize, Serialize}; use std::collections::VecDeque; use std::fmt::Debug; use std::hash::Hash; use std::rc::Rc; +use serde::{Deserialize, Serialize}; + use super::element::{IdState, IdType}; use super::reaction::{PositiveReaction, Reaction}; use super::set::{BasicSet, PositiveSet, Set}; @@ -38,11 +39,11 @@ pub enum Process { identifier: IdType, }, EntitySet { - entities: Set, + entities: Set, next_process: Rc, }, Guarded { - reaction: Reaction, + reaction: Reaction, next_process: Rc, }, WaitEntity { @@ -64,21 +65,21 @@ impl BasicProcess for Process { fn concat(&self, new: &Self) -> Self { match (self, new) { - ( + | ( Self::NondeterministicChoice { children: c1 }, Self::NondeterministicChoice { children: c2 }, ) => Self::NondeterministicChoice { children: [c1.clone(), c2.clone()].concat(), }, - (Self::NondeterministicChoice { children }, new) + | (Self::NondeterministicChoice { children }, new) | (new, Self::NondeterministicChoice { children }) => { let mut new_children = children.clone(); new_children.push(Rc::new(new.clone())); Self::NondeterministicChoice { children: new_children, } - } - (_, _) => Self::NondeterministicChoice { + }, + | (_, _) => Self::NondeterministicChoice { children: vec![Rc::new(self.clone()), Rc::new(new.clone())], }, } @@ -91,16 +92,16 @@ impl BasicProcess for Process { while let Some(el) = queue.pop_front() { match el { - Self::Nill => {} - Self::RecursiveIdentifier { identifier: _ } => {} - Self::EntitySet { + | Self::Nill => {}, + | Self::RecursiveIdentifier { identifier: _ } => {}, + | Self::EntitySet { entities, next_process, } => { elements.push(entities); queue.push_back(next_process); - } - Self::Guarded { + }, + | Self::Guarded { reaction, next_process, } => { @@ -108,25 +109,24 @@ impl BasicProcess for Process { elements.push(&reaction.inhibitors); elements.push(&reaction.products); queue.push_back(next_process); - } - Self::WaitEntity { + }, + | Self::WaitEntity { repeat: _, repeated_process, next_process, } => { queue.push_back(repeated_process); queue.push_back(next_process); - } - Self::Summation { children } => { + }, + | Self::Summation { children } => + for c in children { + queue.push_back(c); + }, + | Self::NondeterministicChoice { children } => { for c in children { queue.push_back(c); } - } - Self::NondeterministicChoice { children } => { - for c in children { - queue.push_back(c); - } - } + }, } } elements @@ -162,17 +162,17 @@ impl PrintableWithTranslator for Process { translator: &Translator, ) -> std::fmt::Result { match self { - Self::Nill => { + | Self::Nill => { write!(f, "Nill") - } - Self::RecursiveIdentifier { identifier } => { + }, + | Self::RecursiveIdentifier { identifier } => { write!( f, "[{}]", translator.decode(*identifier).unwrap_or("Missing".into()) ) - } - Self::EntitySet { + }, + | Self::EntitySet { entities, next_process, } => { @@ -182,8 +182,8 @@ impl PrintableWithTranslator for Process { Formatter::from(translator, entities), Formatter::from(translator, &**next_process) ) - } - Self::Guarded { + }, + | Self::Guarded { reaction, next_process, } => { @@ -193,8 +193,8 @@ impl PrintableWithTranslator for Process { Formatter::from(translator, reaction), Formatter::from(translator, &**next_process) ) - } - Self::WaitEntity { + }, + | Self::WaitEntity { repeat, repeated_process, next_process, @@ -205,8 +205,8 @@ impl PrintableWithTranslator for Process { Formatter::from(translator, &**repeated_process), Formatter::from(translator, &**next_process) ) - } - Self::Summation { children } => { + }, + | Self::Summation { children } => { write!(f, "[")?; let mut it = children.iter().peekable(); while let Some(child) = it.next() { @@ -221,8 +221,8 @@ impl PrintableWithTranslator for Process { } } write!(f, "]") - } - Self::NondeterministicChoice { children } => { + }, + | Self::NondeterministicChoice { children } => { write!(f, "[")?; let mut it = children.iter().peekable(); while let Some(child) = it.next() { @@ -237,7 +237,7 @@ impl PrintableWithTranslator for Process { } } write!(f, "]") - } + }, } } } @@ -251,11 +251,11 @@ pub enum PositiveProcess { identifier: IdType, }, EntitySet { - entities: PositiveSet, + entities: PositiveSet, next_process: Rc, }, Guarded { - reaction: PositiveReaction, + reaction: PositiveReaction, next_process: Rc, }, WaitEntity { @@ -277,21 +277,21 @@ impl BasicProcess for PositiveProcess { fn concat(&self, new: &Self) -> Self { match (self, new) { - ( + | ( Self::NondeterministicChoice { children: c1 }, Self::NondeterministicChoice { children: c2 }, ) => Self::NondeterministicChoice { children: [c1.clone(), c2.clone()].concat(), }, - (Self::NondeterministicChoice { children }, new) + | (Self::NondeterministicChoice { children }, new) | (new, Self::NondeterministicChoice { children }) => { let mut new_children = children.clone(); new_children.push(Rc::new(new.clone())); Self::NondeterministicChoice { children: new_children, } - } - (_, _) => Self::NondeterministicChoice { + }, + | (_, _) => Self::NondeterministicChoice { children: vec![Rc::new(self.clone()), Rc::new(new.clone())], }, } @@ -304,41 +304,40 @@ impl BasicProcess for PositiveProcess { while let Some(el) = queue.pop_front() { match el { - Self::Nill => {} - Self::RecursiveIdentifier { identifier: _ } => {} - Self::EntitySet { + | Self::Nill => {}, + | Self::RecursiveIdentifier { identifier: _ } => {}, + | Self::EntitySet { entities, next_process, } => { elements.push(entities); queue.push_back(next_process); - } - Self::Guarded { + }, + | Self::Guarded { reaction, next_process, } => { elements.push(&reaction.reactants); elements.push(&reaction.products); queue.push_back(next_process); - } - Self::WaitEntity { + }, + | Self::WaitEntity { repeat: _, repeated_process, next_process, } => { queue.push_back(repeated_process); queue.push_back(next_process); - } - Self::Summation { children } => { + }, + | Self::Summation { children } => + for c in children { + queue.push_back(c); + }, + | Self::NondeterministicChoice { children } => { for c in children { queue.push_back(c); } - } - Self::NondeterministicChoice { children } => { - for c in children { - queue.push_back(c); - } - } + }, } } elements @@ -374,17 +373,17 @@ impl PrintableWithTranslator for PositiveProcess { translator: &Translator, ) -> std::fmt::Result { match self { - Self::Nill => { + | Self::Nill => { write!(f, "Nill") - } - Self::RecursiveIdentifier { identifier } => { + }, + | Self::RecursiveIdentifier { identifier } => { write!( f, "[{}]", translator.decode(*identifier).unwrap_or("Missing".into()) ) - } - Self::EntitySet { + }, + | Self::EntitySet { entities, next_process, } => { @@ -394,8 +393,8 @@ impl PrintableWithTranslator for PositiveProcess { Formatter::from(translator, entities), Formatter::from(translator, &**next_process) ) - } - Self::Guarded { + }, + | Self::Guarded { reaction, next_process, } => { @@ -405,8 +404,8 @@ impl PrintableWithTranslator for PositiveProcess { Formatter::from(translator, reaction), Formatter::from(translator, &**next_process) ) - } - Self::WaitEntity { + }, + | Self::WaitEntity { repeat, repeated_process, next_process, @@ -417,8 +416,8 @@ impl PrintableWithTranslator for PositiveProcess { Formatter::from(translator, &**repeated_process), Formatter::from(translator, &**next_process) ) - } - Self::Summation { children } => { + }, + | Self::Summation { children } => { write!(f, "[")?; let mut it = children.iter().peekable(); while let Some(child) = it.next() { @@ -433,8 +432,8 @@ impl PrintableWithTranslator for PositiveProcess { } } write!(f, "]") - } - Self::NondeterministicChoice { children } => { + }, + | Self::NondeterministicChoice { children } => { write!(f, "[")?; let mut it = children.iter().peekable(); while let Some(child) = it.next() { @@ -449,7 +448,7 @@ impl PrintableWithTranslator for PositiveProcess { } } write!(f, "]") - } + }, } } } @@ -457,27 +456,25 @@ impl PrintableWithTranslator for PositiveProcess { impl From<&Process> for PositiveProcess { fn from(value: &Process) -> Self { match value { - Process::Nill => Self::Nill, - Process::EntitySet { + | Process::Nill => Self::Nill, + | Process::EntitySet { entities, next_process, } => Self::EntitySet { - entities: entities.to_positive_set(IdState::Positive), + entities: entities.to_positive_set(IdState::Positive), next_process: Rc::new((&**next_process).into()), }, - Process::RecursiveIdentifier { identifier } => { + | Process::RecursiveIdentifier { identifier } => Self::RecursiveIdentifier { identifier: *identifier, - } - } - Process::Guarded { + }, + | Process::Guarded { reaction, next_process, } => // TODO: is this right? - { Self::Guarded { - reaction: PositiveReaction { + reaction: PositiveReaction { reactants: reaction .reactants .to_positive_set(IdState::Positive) @@ -486,14 +483,13 @@ impl From<&Process> for PositiveProcess { .inhibitors .to_positive_set(IdState::Negative), ), - products: reaction + products: reaction .products .to_positive_set(IdState::Positive), }, next_process: Rc::new((&**next_process).into()), - } - } - Process::WaitEntity { + }, + | Process::WaitEntity { repeat, repeated_process, next_process, @@ -502,20 +498,19 @@ impl From<&Process> for PositiveProcess { repeated_process: Rc::new((&**repeated_process).into()), next_process: Rc::new((&**next_process).into()), }, - Process::Summation { children } => Self::Summation { + | Process::Summation { children } => Self::Summation { children: children .iter() .map(|c| Rc::new((&**c).into())) .collect(), }, - Process::NondeterministicChoice { children } => { + | Process::NondeterministicChoice { children } => Self::NondeterministicChoice { children: children .iter() .map(|c| Rc::new((&**c).into())) .collect(), - } - } + }, } } } diff --git a/src/rsprocess/reaction.rs b/src/rsprocess/reaction.rs index c9def44..5d4c556 100644 --- a/src/rsprocess/reaction.rs +++ b/src/rsprocess/reaction.rs @@ -3,9 +3,10 @@ //! Allows to define the 'classical' mechanism to compute in a Reaction System //! (RS) Framework. -use serde::{Deserialize, Serialize}; use std::hash::Hash; +use serde::{Deserialize, Serialize}; + use super::element::{IdState, IdType}; use super::set::{BasicSet, ExtensionsSet, PositiveSet, Set}; use super::translator::{Formatter, PrintableWithTranslator, Translator}; @@ -141,9 +142,9 @@ impl, Set: BasicSet> ExtensionReaction for T { Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, Hash, )] pub struct Reaction { - pub reactants: Set, + pub reactants: Set, pub inhibitors: Set, - pub products: Set, + pub products: Set, } impl BasicReaction for Reaction { @@ -219,7 +220,7 @@ impl Reaction { )] pub struct PositiveReaction { pub reactants: PositiveSet, - pub products: PositiveSet, + pub products: PositiveSet, } impl BasicReaction for PositiveReaction { @@ -266,7 +267,7 @@ impl PositiveReaction { reactants: reactants .to_positive_set(IdState::Positive) .union(&inhibitors.to_positive_set(IdState::Negative)), - products: products.to_positive_set(IdState::Positive), + products: products.to_positive_set(IdState::Positive), } } @@ -278,12 +279,11 @@ impl PositiveReaction { let mut found = false; for el in self.reactants.iter() { match other.reactants.identifiers.get(el.0) { - None => return None, - Some(s) => { + | None => return None, + | Some(s) => if s != el.1 { if found { return None } else { found = true } - } - } + }, } } Some(self.reactants.intersection(&other.reactants)) diff --git a/src/rsprocess/serialize.rs b/src/rsprocess/serialize.rs index 1c143f7..4a3c17a 100644 --- a/src/rsprocess/serialize.rs +++ b/src/rsprocess/serialize.rs @@ -5,14 +5,14 @@ use std::io; -use super::graph; use serde::{Deserialize, Serialize}; +use super::graph; use super::translator::Translator; #[derive(Serialize, Deserialize)] struct GraphAndTranslator { - graph: graph::SystemGraph, + graph: graph::SystemGraph, translator: Translator, } @@ -25,13 +25,10 @@ pub fn ser( where W: io::Write, { - serde_cbor_2::to_writer( - writer, - &GraphAndTranslator { - graph: graph.clone(), - translator: translator.clone(), - }, - ) + serde_cbor_2::to_writer(writer, &GraphAndTranslator { + graph: graph.clone(), + translator: translator.clone(), + }) } /// Deserializer for file that contains graph and translator. diff --git a/src/rsprocess/set.rs b/src/rsprocess/set.rs index 9f872ca..19d5d4e 100644 --- a/src/rsprocess/set.rs +++ b/src/rsprocess/set.rs @@ -1,8 +1,9 @@ -use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use std::hash::Hash; +use serde::{Deserialize, Serialize}; + use super::element::{IdState, IdType, PositiveType}; use super::translator::{Formatter, PrintableWithTranslator, Translator}; @@ -316,11 +317,11 @@ impl Set { .enumerate() .rfind(|(_, (els, pos))| **pos < els.len() - 1); match next { - None => break, - Some((pos, _)) => { + | None => break, + | Some((pos, _)) => { state[pos] += 1; state.iter_mut().skip(pos + 1).for_each(|el| *el = 0); - } + }, } } t @@ -346,8 +347,8 @@ impl Set { if !modified { e = { match tmp_t.next() { - Some(a) => a, - None => break, + | Some(a) => a, + | None => break, } }; } @@ -508,19 +509,19 @@ impl PrintableWithTranslator for PositiveSet { write!( f, "{}", - Formatter::from( - translator, - &PositiveType { id: *id, state: *s } - ) + Formatter::from(translator, &PositiveType { + id: *id, + state: *s, + }) )?; } else { write!( f, "{}, ", - Formatter::from( - translator, - &PositiveType { id: *id, state: *s } - ) + Formatter::from(translator, &PositiveType { + id: *id, + state: *s, + }) )?; } } diff --git a/src/rsprocess/set_test.rs b/src/rsprocess/set_test.rs index f013ab5..f3eed17 100644 --- a/src/rsprocess/set_test.rs +++ b/src/rsprocess/set_test.rs @@ -13,17 +13,14 @@ fn prohibiting_set_1() { Set::prohibiting_set(&[r1r, r2r], &[r1i, r2i]).unwrap(); prohibiting_set.sort(); - assert_eq!( - prohibiting_set, - vec![ - PositiveSet::from([(2, Negative)]), - PositiveSet::from([(3, Negative)]), - PositiveSet::from([(4, Negative), (11, Negative)]), - PositiveSet::from([(5, Positive)]), - PositiveSet::from([(6, Positive)]), - PositiveSet::from([(7, Positive)]), - ] - ) + assert_eq!(prohibiting_set, vec![ + PositiveSet::from([(2, Negative)]), + PositiveSet::from([(3, Negative)]), + PositiveSet::from([(4, Negative), (11, Negative)]), + PositiveSet::from([(5, Positive)]), + PositiveSet::from([(6, Positive)]), + PositiveSet::from([(7, Positive)]), + ]) } #[test] @@ -41,13 +38,10 @@ fn prohibiting_set_2() { Set::prohibiting_set(&[r1r, r2r], &[r1i, r2i]).unwrap(); prohibiting_set.sort(); - assert_eq!( - prohibiting_set, - vec![ - PositiveSet::from([(1, Negative)]), - PositiveSet::from([(2, Positive), (3, Positive)]), - ] - ) + assert_eq!(prohibiting_set, vec![ + PositiveSet::from([(1, Negative)]), + PositiveSet::from([(2, Positive), (3, Positive)]), + ]) } #[test] @@ -65,14 +59,11 @@ fn prohibiting_set_3() { Set::prohibiting_set(&[r1r, r2r], &[r1i, r2i]).unwrap(); prohibiting_set.sort(); - assert_eq!( - prohibiting_set, - vec![ - PositiveSet::from([(1, Positive), (2, Positive)]), - PositiveSet::from([(1, Negative), (3, Negative)]), - PositiveSet::from([(2, Positive), (3, Negative)]), - ] - ) + assert_eq!(prohibiting_set, vec![ + PositiveSet::from([(1, Positive), (2, Positive)]), + PositiveSet::from([(1, Negative), (3, Negative)]), + PositiveSet::from([(2, Positive), (3, Negative)]), + ]) } #[test] @@ -93,19 +84,16 @@ fn prohibiting_set_4() { Set::prohibiting_set(&[r1r, r2r, r3r], &[r1i, r2i, r3i]).unwrap(); prohibiting_set.sort(); - assert_eq!( - prohibiting_set, - vec![ - PositiveSet::from([(1, Negative), (3, Negative), (5, Negative)]), - PositiveSet::from([(1, Negative), (3, Negative), (6, Positive)]), - PositiveSet::from([(1, Negative), (4, Positive), (5, Negative)]), - PositiveSet::from([(1, Negative), (4, Positive), (6, Positive)]), - PositiveSet::from([(2, Positive), (3, Negative), (5, Negative)]), - PositiveSet::from([(2, Positive), (3, Negative), (6, Positive)]), - PositiveSet::from([(2, Positive), (4, Positive), (5, Negative)]), - PositiveSet::from([(2, Positive), (4, Positive), (6, Positive)]), - ] - ) + assert_eq!(prohibiting_set, vec![ + PositiveSet::from([(1, Negative), (3, Negative), (5, Negative)]), + PositiveSet::from([(1, Negative), (3, Negative), (6, Positive)]), + PositiveSet::from([(1, Negative), (4, Positive), (5, Negative)]), + PositiveSet::from([(1, Negative), (4, Positive), (6, Positive)]), + PositiveSet::from([(2, Positive), (3, Negative), (5, Negative)]), + PositiveSet::from([(2, Positive), (3, Negative), (6, Positive)]), + PositiveSet::from([(2, Positive), (4, Positive), (5, Negative)]), + PositiveSet::from([(2, Positive), (4, Positive), (6, Positive)]), + ]) } #[test] diff --git a/src/rsprocess/system.rs b/src/rsprocess/system.rs index ae60468..67cbd4c 100644 --- a/src/rsprocess/system.rs +++ b/src/rsprocess/system.rs @@ -1,12 +1,12 @@ -use petgraph::graph::DiGraph; -use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt::Debug; use std::hash::Hash; use std::rc::Rc; -use super::choices::Choices; -use super::choices::{BasicChoices, PositiveChoices}; +use petgraph::graph::DiGraph; +use serde::{Deserialize, Serialize}; + +use super::choices::{BasicChoices, Choices, PositiveChoices}; use super::element::IdState; use super::environment::{ BasicEnvironment, Environment, ExtensionsEnvironment, LoopEnvironment, @@ -780,7 +780,7 @@ impl From for PositiveSystem { for s in prohib_set { res.push(PositiveReaction { reactants: s, - products: PositiveSet::from([(el, IdState::Negative)]), + products: PositiveSet::from([(el, IdState::Negative)]), }) } } diff --git a/src/rsprocess/system_test.rs b/src/rsprocess/system_test.rs index ae931f6..204ff3f 100644 --- a/src/rsprocess/system_test.rs +++ b/src/rsprocess/system_test.rs @@ -1,19 +1,21 @@ -use crate::rsprocess::{set::PositiveSet, system::BasicSystem}; +use crate::rsprocess::set::PositiveSet; +use crate::rsprocess::system::BasicSystem; #[test] fn one_transition() { + use std::rc::Rc; + use super::environment::Environment; use super::process::Process; use super::reaction::Reaction; use super::set::{BasicSet, Set}; use super::system::{ExtensionsSystem, System}; - use std::rc::Rc; let system = System::from( Rc::new(Environment::default()), Set::from([1, 2]), Process::EntitySet { - entities: Set::from([]), + entities: Set::from([]), next_process: Rc::new(Process::Nill), }, Rc::new(vec![Reaction::from( @@ -24,7 +26,7 @@ fn one_transition() { ); match system.one_transition() { - Ok(Some(( + | Ok(Some(( _, System { available_entities, .. @@ -32,19 +34,20 @@ fn one_transition() { ))) => assert!( available_entities.len() == 1 && available_entities.contains(&3) ), - _ => panic!(), + | _ => panic!(), } } #[test] fn one_transition_2() { + use std::rc::Rc; + use super::element::{IdState, PositiveType}; use super::environment::PositiveEnvironment; use super::process::PositiveProcess; use super::reaction::PositiveReaction; use super::set::{BasicSet, PositiveSet}; use super::system::{ExtensionsSystem, PositiveSystem}; - use std::rc::Rc; let system = PositiveSystem::from( Rc::new(PositiveEnvironment::default()), @@ -56,7 +59,7 @@ fn one_transition_2() { PositiveProcess::WaitEntity { repeat: 2, repeated_process: Rc::new(PositiveProcess::EntitySet { - entities: PositiveSet::default(), + entities: PositiveSet::default(), next_process: Rc::new(PositiveProcess::Nill), }), next_process: Rc::new(PositiveProcess::Nill), @@ -67,15 +70,15 @@ fn one_transition_2() { (1, IdState::Positive), (3, IdState::Negative), ]), - products: PositiveSet::from([(3, IdState::Positive)]), + products: PositiveSet::from([(3, IdState::Positive)]), }, PositiveReaction { reactants: PositiveSet::from([(3, IdState::Positive)]), - products: PositiveSet::from([(3, IdState::Negative)]), + products: PositiveSet::from([(3, IdState::Negative)]), }, PositiveReaction { reactants: PositiveSet::from([(1, IdState::Negative)]), - products: PositiveSet::from([(3, IdState::Negative)]), + products: PositiveSet::from([(3, IdState::Negative)]), }, ]), ); @@ -83,21 +86,21 @@ fn one_transition_2() { let system = system.one_transition(); let system = match system { - Ok(Some((_, system))) => { + | Ok(Some((_, system))) => { assert!( system.available_entities.len() == 1 && system.available_entities.contains(&PositiveType { - id: 3, - state: IdState::Positive + id: 3, + state: IdState::Positive, }) ); system - } - _ => panic!(), + }, + | _ => panic!(), }; match system.one_transition() { - Ok(Some(( + | Ok(Some(( _, PositiveSystem { available_entities, .. @@ -105,28 +108,29 @@ fn one_transition_2() { ))) => assert!( available_entities.len() == 1 && available_entities.contains(&PositiveType { - id: 3, - state: IdState::Negative + id: 3, + state: IdState::Negative, }) ), - _ => panic!(), + | _ => panic!(), } } #[test] fn convertion() { + use std::rc::Rc; + use super::environment::Environment; use super::process::Process; use super::reaction::Reaction; use super::set::{BasicSet, Set}; use super::system::{PositiveSystem, System}; - use std::rc::Rc; let system = System::from( Rc::new(Environment::default()), Set::from([1, 2]), Process::EntitySet { - entities: Set::from([]), + entities: Set::from([]), next_process: Rc::new(Process::Nill), }, Rc::new(vec![Reaction::from( @@ -144,79 +148,62 @@ fn convertion() { #[test] fn traces_1() { + use std::rc::Rc; + use super::environment::Environment; use super::process::Process; use super::reaction::Reaction; use super::set::Set; use super::system::{ExtensionsSystem, System}; - use std::rc::Rc; let system = System { delta: Rc::new(Environment::from([ - ( - 100, - Process::WaitEntity { - repeat: 2, - repeated_process: Rc::new(Process::EntitySet { - entities: Set::from([1]), - next_process: Rc::new(Process::Nill), - }), + (100, Process::WaitEntity { + repeat: 2, + repeated_process: Rc::new(Process::EntitySet { + entities: Set::from([1]), next_process: Rc::new(Process::Nill), - }, - ), - ( - 102, - Process::WaitEntity { - repeat: 3, - repeated_process: Rc::new(Process::EntitySet { - entities: Set::from([2]), - next_process: Rc::new(Process::Nill), - }), + }), + next_process: Rc::new(Process::Nill), + }), + (102, Process::WaitEntity { + repeat: 3, + repeated_process: Rc::new(Process::EntitySet { + entities: Set::from([2]), next_process: Rc::new(Process::Nill), - }, - ), - ( - 103, - Process::WaitEntity { - repeat: 4, - repeated_process: Rc::new(Process::EntitySet { - entities: Set::from([3]), - next_process: Rc::new(Process::Nill), - }), + }), + next_process: Rc::new(Process::Nill), + }), + (103, Process::WaitEntity { + repeat: 4, + repeated_process: Rc::new(Process::EntitySet { + entities: Set::from([3]), next_process: Rc::new(Process::Nill), - }, - ), - ( - 101, - Process::Summation { - children: vec![ - Rc::new(Process::EntitySet { - entities: Set::from([10]), - next_process: Rc::new( - Process::RecursiveIdentifier { - identifier: 100, - }, - ), + }), + next_process: Rc::new(Process::Nill), + }), + (101, Process::Summation { + children: vec![ + Rc::new(Process::EntitySet { + entities: Set::from([10]), + next_process: Rc::new(Process::RecursiveIdentifier { + identifier: 100, }), - Rc::new(Process::EntitySet { - entities: Set::from([11]), - next_process: Rc::new( - Process::RecursiveIdentifier { - identifier: 102, - }, - ), + }), + Rc::new(Process::EntitySet { + entities: Set::from([11]), + next_process: Rc::new(Process::RecursiveIdentifier { + identifier: 102, }), - Rc::new(Process::EntitySet { - entities: Set::from([11]), - next_process: Rc::new( - Process::RecursiveIdentifier { - identifier: 103, - }, - ), + }), + Rc::new(Process::EntitySet { + entities: Set::from([11]), + next_process: Rc::new(Process::RecursiveIdentifier { + identifier: 103, }), - ], - }, - ), + }), + ], + }), ])), available_entities: Set::from([1, 2]), context_process: Process::RecursiveIdentifier { identifier: 101 }, @@ -249,12 +236,13 @@ fn traces_1() { #[test] fn traces_empty_env() { + use std::rc::Rc; + use super::environment::Environment; use super::process::Process; use super::reaction::Reaction; use super::set::Set; use super::system::{ExtensionsSystem, System}; - use std::rc::Rc; let system = System { delta: Rc::new(Environment::from([])), @@ -262,7 +250,7 @@ fn traces_empty_env() { context_process: Process::WaitEntity { repeat: 10, repeated_process: Rc::new(Process::EntitySet { - entities: Set::from([1, 2]), + entities: Set::from([1, 2]), next_process: Rc::new(Process::Nill), }), next_process: Rc::new(Process::Nill), @@ -307,23 +295,20 @@ fn conversion_reactions() { .then(a.reactants.cmp(&b.reactants)) }); - assert_eq!( - reactions, - vec![ - PositiveReaction::from( - PositiveSet::from([(2, Positive), (3, Negative)]), - PositiveSet::from([(5, Positive)]), - ), - PositiveReaction::from( - PositiveSet::from([(2, Negative)]), - PositiveSet::from([(5, Negative)]), - ), - PositiveReaction::from( - PositiveSet::from([(3, Positive)]), - PositiveSet::from([(5, Negative)]), - ), - ] - ); + assert_eq!(reactions, vec![ + PositiveReaction::from( + PositiveSet::from([(2, Positive), (3, Negative)]), + PositiveSet::from([(5, Positive)]), + ), + PositiveReaction::from( + PositiveSet::from([(2, Negative)]), + PositiveSet::from([(5, Negative)]), + ), + PositiveReaction::from( + PositiveSet::from([(3, Positive)]), + PositiveSet::from([(5, Negative)]), + ), + ]); } #[test] diff --git a/src/rsprocess/transitions.rs b/src/rsprocess/transitions.rs index 0274969..4d3fb51 100644 --- a/src/rsprocess/transitions.rs +++ b/src/rsprocess/transitions.rs @@ -22,11 +22,11 @@ pub struct TransitionsIterator< impl<'a> TransitionsIterator<'a, Set, System, Process> { pub fn from(system: &'a System) -> Result { match system.unfold() { - Ok(o) => Ok(TransitionsIterator { + | Ok(o) => Ok(TransitionsIterator { choices_iterator: o.into_iter(), system, }), - Err(e) => Err(e), + | Err(e) => Err(e), } } } @@ -98,11 +98,11 @@ impl<'a> Iterator for TransitionsIterator<'a, Set, System, Process> { impl<'a> TransitionsIterator<'a, PositiveSet, PositiveSystem, PositiveProcess> { pub fn from(system: &'a PositiveSystem) -> Result { match system.unfold() { - Ok(o) => Ok(TransitionsIterator { + | Ok(o) => Ok(TransitionsIterator { choices_iterator: o.into_iter(), system, }), - Err(e) => Err(e), + | Err(e) => Err(e), } } } diff --git a/src/rsprocess/translator.rs b/src/rsprocess/translator.rs index a7c94f3..8730d24 100644 --- a/src/rsprocess/translator.rs +++ b/src/rsprocess/translator.rs @@ -1,9 +1,10 @@ //! Module for translation and keeping track of strings. -use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt; +use serde::{Deserialize, Serialize}; + use super::element::IdType; /// precision for printing frequencies @@ -58,9 +59,9 @@ impl PartialEq for Translator { fn eq(&self, other: &Self) -> bool { for (s, id) in self.strings.iter() { match other.strings.get(s) { - None => return false, - Some(id2) if id != id2 => return false, - _ => {} + | None => return false, + | Some(id2) if id != id2 => return false, + | _ => {}, } } true