diff --git a/Cargo.toml b/Cargo.toml index 2ff0c25..e765162 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hibou_label" -version = "0.8.0" +version = "0.8.1" authors = ["Erwan Mahe"] edition = "2021" diff --git a/src/canonize/process.rs b/src/canonize/process.rs deleted file mode 100644 index 2e30838..0000000 --- a/src/canonize/process.rs +++ /dev/null @@ -1,305 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -use std::fs; -use std::fs::File; -use std::io::{Read,BufReader,BufRead,BufWriter,Write}; - -use std::collections::{HashSet,HashMap}; - -use std::process::Command; - -use crate::output::rendering::graphviz::graph::*; -use crate::output::rendering::graphviz::node_style::*; -use crate::output::rendering::graphviz::edge_style::*; -use crate::output::rendering::graphviz::common::*; - - -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::general_context::GeneralContext; - -use crate::canonize::term_repr_out::to_term_repr_temp; -use crate::canonize::transformations::get_all_transfos::*; -use crate::canonize::transformations::get_one_transfo::*; - -use crate::canonize::transformations::phases::InteractionTermTransformation; - -pub fn canon_process_interaction_term(interaction : &Interaction, - gen_ctx : &GeneralContext, - name : &String, - search_all : bool) { - // empties temp directory if exists - match fs::remove_dir_all("./temp") { - Ok(_) => { - // do nothing - }, - Err(e) => { - // do nothing - } - } - // creates temp directory - fs::create_dir_all("./temp").unwrap(); - // *** - let mut file = File::create(&format!("{:}.dot", name)).unwrap(); - file.write(format!("digraph {} {{\n", name).as_bytes()); - file.write("overlap=false;\n".as_bytes()); - if search_all { - canonize_process_all_transfos(&mut file, &interaction, gen_ctx); - } else { - canonize_process_one_transfo(&mut file, &interaction, gen_ctx); - } - file.write("}\n".as_bytes()); - let status = Command::new("dot") - .arg("-Tsvg:cairo") - .arg(&format!("{:}.dot", name)) - .arg("-o") - .arg(&format!("{:}.svg", name)) - .output(); -} - -fn canonize_process_one_transfo(file : &mut File, - init_interaction : &Interaction, - gen_ctx : &GeneralContext) { - canonize_process(file, - init_interaction, - gen_ctx, - &phase_1_one_transfo, - &phase_2_one_transfo); -} - -fn canonize_process_all_transfos(file : &mut File, - init_interaction : &Interaction, - gen_ctx : &GeneralContext) { - canonize_process(file, - init_interaction, - gen_ctx, - &phase_1_all_transfos, - &phase_2_all_transfos); -} - -fn canonize_process(file : &mut File, - init_interaction : &Interaction, - gen_ctx : &GeneralContext, - phase_1 : &dyn Fn(&Interaction) -> Vec, - phase_2 : &dyn Fn(&Interaction) -> Vec) -> Interaction { - // *** - // source node - { - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - node_gv_options.push( GraphvizNodeStyleItem::Style(vec![GvNodeStyleKind::Filled]) ); - node_gv_options.push( GraphvizNodeStyleItem::Label("".to_string()) ); - let gv_node = GraphVizNode{id : "i0".to_string(), style : node_gv_options}; - file.write( gv_node.to_dot_string().as_bytes() ); - file.write("\n".as_bytes() ); - } - // *** - // transition from source - { - let gv_edge = GraphVizEdge{origin_id : "i0".to_string(), target_id : "i1".to_string(), style : Vec::new()}; - file.write( gv_edge.to_dot_string().as_bytes() ); - file.write("\n".as_bytes() ); - } - // *** - // init process - let mut queue : Vec<(u32,Interaction)> = vec![(1,init_interaction.clone())]; - let mut next_index : u32 = 2; - // *** - // ===================================================================================================== - // PHASE 1 - let mut known : HashMap = HashMap::new(); - known.insert( init_interaction.clone(), 1 ); - file.write("subgraph cluster_phase1 {\n".as_bytes() ); - file.write("style=filled;color=lightblue1;label=\"phase 1\";\n".as_bytes() ); - // *** - // first node - { - to_term_repr_temp(&"i1".to_string(),init_interaction,gen_ctx); - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - node_gv_options.push( GraphvizNodeStyleItem::Image( "temp/i1.png".to_string() ) ); - node_gv_options.push( GraphvizNodeStyleItem::Label( "".to_string() ) ); - let gv_node = GraphVizNode{id : "i1".to_string(), style : node_gv_options}; - file.write( gv_node.to_dot_string().as_bytes() ); - file.write("\n".as_bytes() ); - } - let mut finals : HashSet<(u32,Interaction)> = HashSet::new(); - while queue.len() > 0 { - let (parent_id,parent_interaction) = queue.pop().unwrap(); - let parent_id_str = format!("i{}", parent_id); - // *** - let mut available_transfos = phase_1(&parent_interaction); - // *** - if available_transfos.len() > 0 { - for transformed in available_transfos { - if known.contains_key(&transformed.result) { - let target_id = known.get(&transformed.result).unwrap(); - // new transition - let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); - tran_gv_options.push( GraphvizEdgeStyleItem::Label( transformed.transformation_str_description() )); - let gv_edge = GraphVizEdge{origin_id : parent_id_str.clone(), - target_id : format!("i{}",&target_id), - style : tran_gv_options}; - file.write( gv_edge.to_dot_string().as_bytes() ); - file.write("\n".as_bytes() ); - // then discard the new interaction - } else { - // *** - let new_id_str = format!("i{}", next_index); - // new interaction node - { - to_term_repr_temp(&new_id_str,&transformed.result, gen_ctx); - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - node_gv_options.push( GraphvizNodeStyleItem::Image( format!("temp/{}.png",new_id_str) ) ); - node_gv_options.push( GraphvizNodeStyleItem::Label( "".to_string() ) ); - let gv_node = GraphVizNode{id : new_id_str.clone(), style : node_gv_options}; - file.write( gv_node.to_dot_string().as_bytes() ); - file.write("\n".as_bytes() ); - } - // new transition - { - let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); - tran_gv_options.push( GraphvizEdgeStyleItem::Label( transformed.transformation_str_description() )); - let gv_edge = GraphVizEdge{origin_id : parent_id_str.clone(), - target_id : new_id_str, - style : tran_gv_options}; - file.write( gv_edge.to_dot_string().as_bytes() ); - file.write("\n".as_bytes() ); - } - // save the new interaction - known.insert( transformed.result.clone(), next_index ); - queue.push((next_index,transformed.result) ); - next_index = next_index + 1; - } - } - } else { - finals.insert( (parent_id,parent_interaction) ); - } - } - file.write("}\n".as_bytes() ); - // *** - // ===================================================================================================== - // PHASE 2 - known = HashMap::new(); - { - let mut temp_string : String = String::new(); - for (iid,iterm) in finals.drain() { - let old_id_str = format!("i{}", iid); - let new_id_str = format!("i{}", next_index); - // new interaction node - { - to_term_repr_temp(&new_id_str,&iterm,gen_ctx); - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - node_gv_options.push( GraphvizNodeStyleItem::Image( format!("temp/{}.png",new_id_str) ) ); - node_gv_options.push( GraphvizNodeStyleItem::Label( "".to_string() ) ); - let gv_node = GraphVizNode{id : new_id_str.clone(), style : node_gv_options}; - temp_string.push_str( &gv_node.to_dot_string() ); - temp_string.push_str( "\n" ); - } - // new transition - { - let tran_gv_options : GraphvizEdgeStyle = Vec::new(); - let gv_edge = GraphVizEdge{origin_id : old_id_str, - target_id : new_id_str, - style : tran_gv_options}; - file.write( gv_edge.to_dot_string().as_bytes() ); - file.write( "\n".as_bytes() ); - } - // save the old final - known.insert( iterm.clone(), next_index ); - queue.push( (next_index,iterm) ); - next_index = next_index + 1; - } - file.write("subgraph cluster_phase2 {\n".as_bytes() ); - file.write("style=filled;color=palegreen;label=\"phase 2\";\n".as_bytes() ); - file.write( temp_string.as_bytes() ); - } - // *** - while queue.len() > 0 { - let (parent_id,parent_interaction) = queue.pop().unwrap(); - let parent_id_str = format!("i{}", parent_id); - // *** - let mut available_transfos = phase_2(&parent_interaction); - // *** - if available_transfos.len() > 0 { - for transformed in available_transfos { - if known.contains_key(&transformed.result) { - let target_id = known.get(&transformed.result).unwrap(); - // new transition - let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); - tran_gv_options.push( GraphvizEdgeStyleItem::Label( transformed.transformation_str_description() )); - let gv_edge = GraphVizEdge{origin_id : parent_id_str.clone(), - target_id : format!("i{}",&target_id), - style : tran_gv_options}; - file.write( gv_edge.to_dot_string().as_bytes() ); - file.write("\n".as_bytes() ); - // then discard the new interaction - } else { - // *** - let new_id_str = format!("i{}", next_index); - // new interaction node - { - to_term_repr_temp(&new_id_str,&transformed.result, gen_ctx); - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - node_gv_options.push( GraphvizNodeStyleItem::Image( format!("temp/{}.png",new_id_str) ) ); - node_gv_options.push( GraphvizNodeStyleItem::Label( "".to_string() ) ); - let gv_node = GraphVizNode{id : new_id_str.clone(), style : node_gv_options}; - file.write( gv_node.to_dot_string().as_bytes() ); - file.write("\n".as_bytes() ); - } - // new transition - { - let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); - tran_gv_options.push( GraphvizEdgeStyleItem::Label( transformed.transformation_str_description() )); - let gv_edge = GraphVizEdge{origin_id : parent_id_str.clone(), - target_id : new_id_str, - style : tran_gv_options}; - file.write( gv_edge.to_dot_string().as_bytes() ); - file.write("\n".as_bytes() ); - } - // save the new interaction - known.insert( transformed.result.clone(), next_index ); - queue.push((next_index,transformed.result) ); - next_index = next_index + 1; - } - } - } else { - finals.insert( (parent_id,parent_interaction) ); - } - } - file.write("}\n".as_bytes() ); - // *** - // ===================================================================================================== - assert!(finals.len() == 1); - let elt = finals.iter().next().cloned().unwrap(); - let (_,canonical_interaction) = finals.take(&elt).unwrap(); - return canonical_interaction; -} - - - - - - - - - - diff --git a/src/canonize/total_order.rs b/src/canonize/total_order.rs deleted file mode 100644 index d60d2eb..0000000 --- a/src/canonize/total_order.rs +++ /dev/null @@ -1,286 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - - -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::general_context::GeneralContext; - -use crate::core::execution::trace::trace::TraceActionKind; - - - -fn emission_lower_than(em_act1 : &EmissionAction, em_act2 : &EmissionAction) -> bool { - if &em_act1.ms_id < &em_act2.ms_id { - return true; - } else if &em_act1.ms_id > &em_act2.ms_id{ - return false; - } - // *** - if &em_act1.origin_lf_id < &em_act2.origin_lf_id { - return true; - } else if &em_act1.origin_lf_id > &em_act2.origin_lf_id { - return false; - } - // *** - let max_tar_len = em_act1.targets.len().max(em_act2.targets.len()); - for i in 0..max_tar_len { - match (em_act1.targets.get(i) , em_act2.targets.get(i) ) { - ( Some( tar_ref1 ), Some(tar_ref2) ) => { - if tar_ref1 < tar_ref2 { - return true; - } - }, - (None,Some(_)) => { - return true; - }, - (Some(_),None) => {}, - (None,None) => {} - } - } - // *** - return em_act1.synchronicity < em_act2.synchronicity; -} - - -fn reception_lower_than(rc_act1 : &ReceptionAction, rc_act2 : &ReceptionAction) -> bool { - if &rc_act1.ms_id < &rc_act2.ms_id { - return true; - } else if &rc_act1.ms_id > &rc_act2.ms_id{ - return false; - } - // *** - match (rc_act1.origin_gt_id,rc_act2.origin_gt_id) { - (None,Some(_)) => { - return true; - }, - (Some(_),None) => {}, - (None,None) => {}, - (Some( gt_id1),Some(gt_id2)) => { - if gt_id1 < gt_id2 { - return true; - } - } - } - // *** - let max_tar_len = rc_act1.recipients.len().max(rc_act2.recipients.len()); - for i in 0..max_tar_len { - match (rc_act1.recipients.get(i) , rc_act2.recipients.get(i) ) { - ( Some( tar_lf_id1 ), Some(tar_lf_id2) ) => { - if tar_lf_id1 < tar_lf_id2 { - return true; - } - }, - (None,Some(_)) => { - return true; - }, - (Some(_),None) => {}, - (None,None) => {} - } - } - // *** - return rc_act1.synchronicity < rc_act2.synchronicity; -} - - -pub fn interaction_lower_than(i1 : &Interaction, i2 : &Interaction) -> bool { - match i1 { - &Interaction::Empty => { - match i2 { - &Interaction::Empty => { - return false; - }, - _ => { - return true; - } - } - }, - &Interaction::Emission(ref em_act1) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(ref em_act2) => { - return emission_lower_than(em_act1,em_act2); - }, - _ => { - return true; - } - } - }, - &Interaction::Reception(ref rc_act1) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(ref rc_act2) => { - return reception_lower_than(rc_act1,rc_act2); - }, - _ => { - return true; - } - } - } - &Interaction::Par(ref i11, ref i12) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(_) => { - return false; - }, - &Interaction::Par(ref i21, ref i22) => { - if interaction_lower_than(i11,i21) { - return true; - } else { - if i11 != i21 { - return false; - } else { - return interaction_lower_than(i12,i22); - } - } - }, - _ => { - return true; - } - } - }, - &Interaction::Seq(ref i11, ref i12) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(_) => { - return false; - }, - &Interaction::Par(_,_) => { - return false; - }, - &Interaction::Seq(ref i21, ref i22) => { - if interaction_lower_than(i11,i21) { - return true; - } else { - if i11 != i21 { - return false; - } else { - return interaction_lower_than(i12,i22); - } - } - }, - _ => { - return true; - } - } - }, - &Interaction::Strict(ref i11, ref i12) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(_) => { - return false; - }, - &Interaction::Par(_,_) => { - return false; - }, - &Interaction::Seq(_,_) => { - return false; - }, - &Interaction::Strict(ref i21, ref i22) => { - if interaction_lower_than(i11,i21) { - return true; - } else { - if i11 != i21 { - return false; - } else { - return interaction_lower_than(i12,i22); - } - } - }, - _ => { - return true; - } - } - }, - &Interaction::Alt(ref i11, ref i12) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(_) => { - return false; - }, - &Interaction::Par(_,_) => { - return false; - }, - &Interaction::Seq(_,_) => { - return false; - }, - &Interaction::Strict(_,_) => { - return false; - }, - &Interaction::Alt(ref i21, ref i22) => { - if interaction_lower_than(i11,i21) { - return true; - } else { - if i11 != i21 { - return false; - } else { - return interaction_lower_than(i12,i22); - } - } - }, - _ => { - return true; - } - } - }, - &Interaction::Loop(ref lk1, ref i11) => { - match i2 { - &Interaction::Loop(ref lk2, ref i21) => { - if lk1 < lk2 { - return true; - } else { - return interaction_lower_than(i11,i21); - } - }, - _ => { - return false; - } - } - }, - _ => { - panic!(); - } - } -} \ No newline at end of file diff --git a/src/canonize/transformations/phases.rs b/src/canonize/transformations/phases.rs deleted file mode 100644 index f651e5c..0000000 --- a/src/canonize/transformations/phases.rs +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::general_context::GeneralContext; - -use crate::output::rendering::textual::monochrome::position::position_to_text; - -use crate::canonize::transformations::transfokind::*; -use crate::canonize::transformations::transfodef::*; - -pub struct InteractionTermTransformation { - pub kind : TransformationKind, - pub position : Position, - pub result : Interaction -} - -impl InteractionTermTransformation { - pub fn new(kind : TransformationKind, - position : Position, - result : Interaction) -> InteractionTermTransformation { - return InteractionTermTransformation{kind,position,result}; - } - - pub fn transformation_str_description(&self) -> String { - return format!("{}@{}", self.kind.to_string(), position_to_text(&self.position)) - } -} - -pub fn transfos_phase1<'lifetime>() -> Vec<(TransformationKind, &'lifetime dyn Fn(&Interaction) -> Option)> { - return vec![ - (TransformationKind::Deduplicate,&deduplicate), - (TransformationKind::TriDeduplicateRF,&tri_deduplicate_right_flushed), - (TransformationKind::SimplLeft,&simpl_left), - (TransformationKind::SimplRight,&simpl_right), - (TransformationKind::FlushRight,&flush_right), - (TransformationKind::InvertPar,&invert_par_conditional), - (TransformationKind::TriInvertParRF,&tri_invert_par_conditional_right_flushed), - (TransformationKind::InvertAlt,&invert_alt_conditional), - (TransformationKind::TriInvertAltRF,&tri_invert_alt_conditional_right_flushed), - (TransformationKind::LoopSimpl,&loop_simpl), - (TransformationKind::LoopUnNest,&loop_unnest), - (TransformationKind::DeFactorizeL,&defactorize_left), - (TransformationKind::DeFactorizeR,&defactorize_right), - // *** - //(TransformationKind::StrictToPassing,&strict_to_passing), - (TransformationKind::SortEmissionTargets,&sort_emission_targets) - ]; -} - -pub fn transfos_phase2<'lifetime>() -> Vec<(TransformationKind, &'lifetime dyn Fn(&Interaction) -> Option)> { - return vec![ - (TransformationKind::Deduplicate,&deduplicate), - (TransformationKind::TriDeduplicateRF,&tri_deduplicate_right_flushed), - (TransformationKind::SimplLeft,&simpl_left), - (TransformationKind::SimplRight,&simpl_right), - (TransformationKind::FlushRight,&flush_right), - (TransformationKind::InvertPar,&invert_par_conditional), - (TransformationKind::TriInvertParRF,&tri_invert_par_conditional_right_flushed), - (TransformationKind::InvertAlt,&invert_alt_conditional), - (TransformationKind::TriInvertAltRF,&tri_invert_alt_conditional_right_flushed), - (TransformationKind::LoopSimpl,&loop_simpl), - (TransformationKind::LoopUnNest,&loop_unnest), - (TransformationKind::FactorizePrefixX,&factorize_prefix_strict), - (TransformationKind::FactorizePrefixS,&factorize_prefix_seq), - (TransformationKind::FactorizePrefixP,&factorize_prefix_par), - (TransformationKind::FactorizeSuffixX,&factorize_suffix_strict), - (TransformationKind::FactorizeSuffixS,&factorize_suffix_seq), - (TransformationKind::FactorizeSuffixP,&factorize_suffix_par), - // *** - //(TransformationKind::StrictToPassing,&strict_to_passing), - (TransformationKind::SortEmissionTargets,&sort_emission_targets) - ]; -} - diff --git a/src/canonize/transformations/transfodef.rs b/src/canonize/transformations/transfodef.rs deleted file mode 100644 index d5d959d..0000000 --- a/src/canonize/transformations/transfodef.rs +++ /dev/null @@ -1,630 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::language::syntax::util::get_recursive_frag::*; -use crate::core::language::syntax::util::fold_recursive_frags::*; -use crate::core::general_context::GeneralContext; - -use crate::canonize::total_order::interaction_lower_than; - - -pub(in crate::canonize) fn simpl_left(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - if **i1 == Interaction::Empty { - return Some( *(i2.clone()) ); - } - }, - &Interaction::Seq(ref i1, ref i2) => { - if **i1 == Interaction::Empty { - return Some( *(i2.clone()) ); - } - }, - &Interaction::Par(ref i1, ref i2) => { - if **i1 == Interaction::Empty { - return Some( *(i2.clone()) ); - } - }, - &Interaction::CoReg(_, ref i1, ref i2) => { - if **i1 == Interaction::Empty { - return Some( *(i2.clone()) ); - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn simpl_right(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - if **i2 == Interaction::Empty { - return Some( *(i1.clone()) ); - } - }, - &Interaction::Seq(ref i1, ref i2) => { - if **i2 == Interaction::Empty { - return Some( *(i1.clone()) ); - } - }, - &Interaction::Par(ref i1, ref i2) => { - if **i2 == Interaction::Empty { - return Some( *(i1.clone()) ); - } - }, - &Interaction::CoReg(_, ref i1, ref i2) => { - if **i2 == Interaction::Empty { - return Some( *(i1.clone()) ); - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn flush_right(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11,ref i12) => { - return Some( Interaction::Alt( i11.clone(), Box::new(Interaction::Alt(i12.clone(), i2.clone())) ) ); - }, - _ => {} - } - }, - &Interaction::Strict(ref i1, ref i2) => { - match **i1 { - Interaction::Strict(ref i11,ref i12) => { - return Some( Interaction::Strict( i11.clone(), Box::new(Interaction::Strict(i12.clone(), i2.clone())) ) ); - }, - _ => {} - } - }, - &Interaction::Seq(ref i1, ref i2) => { - match **i1 { - Interaction::Seq(ref i11,ref i12) => { - return Some( Interaction::Seq( i11.clone(), Box::new(Interaction::Seq(i12.clone(), i2.clone())) ) ); - }, - _ => {} - } - }, - &Interaction::Par(ref i1, ref i2) => { - match **i1 { - Interaction::Par(ref i11,ref i12) => { - return Some( Interaction::Par( i11.clone(), Box::new(Interaction::Par(i12.clone(), i2.clone())) ) ); - }, - _ => {} - } - }, - &Interaction::CoReg(ref cr1, ref i1, ref i2) => { - match **i1 { - Interaction::CoReg(ref cr2, ref i11,ref i12) => { - if cr1 == cr2 { - return Some( Interaction::CoReg( cr1.clone(), i11.clone(), Box::new(Interaction::CoReg(cr1.clone(), i12.clone(), i2.clone())) ) ); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn flush_left(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21,ref i22) => { - return Some( Interaction::Alt( Box::new(Interaction::Alt(i1.clone(), i21.clone())), i22.clone() ) ); - }, - _ => {} - } - }, - &Interaction::Strict(ref i1, ref i2) => { - match **i2 { - Interaction::Strict(ref i21,ref i22) => { - return Some( Interaction::Strict( Box::new(Interaction::Strict(i1.clone(), i21.clone())), i22.clone() ) ); - }, - _ => {} - } - }, - &Interaction::Seq(ref i1, ref i2) => { - match **i2 { - Interaction::Seq(ref i21,ref i22) => { - return Some( Interaction::Seq( Box::new(Interaction::Seq(i1.clone(), i21.clone())), i22.clone() ) ); - }, - _ => {} - } - }, - &Interaction::Par(ref i1, ref i2) => { - match **i2 { - Interaction::Par(ref i21,ref i22) => { - return Some( Interaction::Par( Box::new(Interaction::Par(i1.clone(), i21.clone())), i22.clone() ) ); - }, - _ => {} - } - }, - &Interaction::CoReg(ref cr1, ref i1, ref i2) => { - match **i2 { - Interaction::CoReg(ref cr2, ref i21,ref i22) => { - if cr1 == cr2 { - return Some( Interaction::CoReg( cr1.clone(), Box::new(Interaction::CoReg(cr1.clone(), i1.clone(), i21.clone())), i22.clone() ) ); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - -pub(in crate::canonize) fn invert_alt_conditional(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - if interaction_lower_than(i2,i1) { - return Some( Interaction::Alt( i2.clone(), i1.clone() ) ); - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn invert_par_conditional(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Par(ref i1, ref i2) => { - if interaction_lower_than(i2,i1) { - return Some(Interaction::Par(i2.clone(), i1.clone())); - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn tri_invert_alt_conditional_right_flushed(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i_right) => { - match **i_right { - Interaction::Alt(ref i2,ref i3) => { - if interaction_lower_than(i2,i1) { - return Some( Interaction::Alt( i2.clone(), Box::new(Interaction::Alt(i1.clone(), i3.clone())) ) ); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn tri_invert_par_conditional_right_flushed(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Par(ref i1, ref i_right) => { - match **i_right { - Interaction::Par(ref i2,ref i3) => { - if interaction_lower_than(i2,i1) { - return Some(Interaction::Par(i2.clone(), Box::new(Interaction::Par(i1.clone(), i3.clone())))); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn deduplicate(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - if i1 == i2 { - return Some( *i1.clone() ); - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn tri_deduplicate_right_flushed(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i_right) => { - match **i_right { - Interaction::Alt(ref i2,ref i3) => { - if i1 == i2 { - return Some( Interaction::Alt(i1.clone(),i3.clone()) ); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn factorize_prefix_strict(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_strict_frags = get_recursive_strict_frags(i1); - let mut right_strict_frags = get_recursive_strict_frags(i2); - if left_strict_frags[0] == right_strict_frags[0] { - let first_frag = left_strict_frags.remove(0); - right_strict_frags.remove(0); - if first_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_strict_frags(&mut left_strict_frags)), - Box::new(fold_recursive_strict_frags(&mut right_strict_frags)) - ); - return Some( Interaction::Strict( Box::new(first_frag.clone()), Box::new(new_alt)) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn factorize_prefix_seq(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_seq_frags = get_recursive_seq_frags(i1); - let mut right_seq_frags = get_recursive_seq_frags(i2); - if left_seq_frags[0] == right_seq_frags[0] { - let first_frag = left_seq_frags.remove(0); - right_seq_frags.remove(0); - if first_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_seq_frags(&mut left_seq_frags)), - Box::new(fold_recursive_seq_frags(&mut right_seq_frags)) - ); - return Some( Interaction::Seq( Box::new(first_frag.clone()), Box::new(new_alt)) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn factorize_prefix_par(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_par_frags = get_recursive_par_frags(i1); - let mut right_par_frags = get_recursive_par_frags(i2); - if left_par_frags[0] == right_par_frags[0] { - let first_frag = left_par_frags.remove(0); - right_par_frags.remove(0); - if first_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_par_frags(&mut left_par_frags)), - Box::new(fold_recursive_par_frags(&mut right_par_frags)) - ); - return Some( Interaction::Par( Box::new(first_frag.clone()), Box::new(new_alt)) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn factorize_suffix_strict(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_strict_frags = get_recursive_strict_frags(i1); - let mut right_strict_frags = get_recursive_strict_frags(i2); - if left_strict_frags.last() == right_strict_frags.last() { - let last_frag : &Interaction = left_strict_frags.pop().unwrap(); - right_strict_frags.pop(); - if last_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_strict_frags(&mut left_strict_frags)), - Box::new(fold_recursive_strict_frags(&mut right_strict_frags)) - ); - return Some( Interaction::Strict( Box::new(new_alt), Box::new(last_frag.clone()) ) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn factorize_suffix_seq(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_seq_frags = get_recursive_seq_frags(i1); - let mut right_seq_frags = get_recursive_seq_frags(i2); - if left_seq_frags.last() == right_seq_frags.last() { - let last_frag : &Interaction = left_seq_frags.pop().unwrap(); - right_seq_frags.pop(); - if last_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_seq_frags(&mut left_seq_frags)), - Box::new(fold_recursive_seq_frags(&mut right_seq_frags)) - ); - return Some( Interaction::Seq( Box::new(new_alt), Box::new(last_frag.clone()) ) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn factorize_suffix_par(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_par_frags = get_recursive_par_frags(i1); - let mut right_par_frags = get_recursive_par_frags(i2); - if left_par_frags.last() == right_par_frags.last() { - let last_frag : &Interaction = left_par_frags.pop().unwrap(); - right_par_frags.pop(); - if last_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_par_frags(&mut left_par_frags)), - Box::new(fold_recursive_par_frags(&mut right_par_frags)) - ); - return Some( Interaction::Par( Box::new(new_alt), Box::new(last_frag.clone()) ) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::canonize) fn defactorize_left(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21, ref i22) => { - let new_iA = Interaction::Strict( i1.clone(), i21.clone() ); - let new_iB = Interaction::Strict( i1.clone(), i22.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::Seq(ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21, ref i22) => { - let new_iA = Interaction::Seq( i1.clone(), i21.clone() ); - let new_iB = Interaction::Seq( i1.clone(), i22.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::Par(ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21, ref i22) => { - let new_iA = Interaction::Par( i1.clone(), i21.clone() ); - let new_iB = Interaction::Par( i1.clone(), i22.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::CoReg(ref cr, ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21, ref i22) => { - let new_iA = Interaction::CoReg( cr.clone(), i1.clone(), i21.clone() ); - let new_iB = Interaction::CoReg( cr.clone(), i1.clone(), i22.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - - -pub(in crate::canonize) fn defactorize_right(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11, ref i12) => { - let new_iA = Interaction::Strict( i11.clone(), i2.clone() ); - let new_iB = Interaction::Strict( i12.clone(), i2.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::Seq(ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11, ref i12) => { - let new_iA = Interaction::Seq( i11.clone(), i2.clone() ); - let new_iB = Interaction::Seq( i12.clone(), i2.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::Par(ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11, ref i12) => { - let new_iA = Interaction::Par( i11.clone(), i2.clone() ); - let new_iB = Interaction::Par( i12.clone(), i2.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::CoReg(ref cr, ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11, ref i12) => { - let new_iA = Interaction::CoReg( cr.clone(), i11.clone(), i2.clone() ); - let new_iB = Interaction::CoReg( cr.clone(), i12.clone(), i2.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - - -pub(in crate::canonize) fn loop_simpl(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Loop(ref sk, ref i1) => { - match **i1 { - Interaction::Empty => { - return Some( Interaction::Empty ); - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - -pub(in crate::canonize) fn loop_unnest(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Loop(ref lkA, ref i1) => { - match **i1 { - Interaction::Loop(ref lkB, ref i11) => { - return Some( Interaction::Loop((lkA.min(lkB)).clone(), i11.clone()) ); - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - - -pub(in crate::canonize) fn sort_emission_targets(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Emission(ref em_act) => { - let mut new_targets = em_act.targets.clone(); - new_targets.sort(); - if new_targets != em_act.targets { - let new_emission = EmissionAction::new(em_act.origin_lf_id,em_act.ms_id,em_act.synchronicity.clone(),new_targets); - return Some( Interaction::Emission(new_emission) ); - } - }, - &Interaction::Reception(ref rc_act) => { - let mut new_targets = rc_act.recipients.clone(); - new_targets.sort(); - if new_targets != rc_act.recipients { - let new_reception = ReceptionAction::new(rc_act.origin_gt_id.clone(),rc_act.ms_id,rc_act.synchronicity.clone(),new_targets); - return Some( Interaction::Reception(new_reception) ); - } - }, - _ => {} - } - return None; -} - - - - - - - - - - -/* - -pub(in crate::canonize) fn strict_to_passing(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - let mut frags : Vec<&Interaction> = Vec::new(); - frags.extend(get_recursive_strict_frags(i1)); - frags.extend(get_recursive_strict_frags(i2)); - let mut flag_changed = false; - match frags.remove(0) { - Interaction::Action(ref act1) => { - match &act1.act_kind { - ObservableActionKind::Emission(ref target_refs) => { - let mut new_targets : Vec = target_refs.clone(); - let mut continue_bool = true; - while continue_bool { - match frags.get(0).unwrap() { - Interaction::Action(ref act2) => { - match act2.act_kind { - ObservableActionKind::Reception(ref orig2) => { - match orig2 { - None => { - if &act2.ms_id == &act1.ms_id { - frags.remove(0); - new_targets.push(EmissionTargetRef::Lifeline(act2.lf_id)); - flag_changed = true; - } else { - continue_bool = false; - } - }, - _ => { - continue_bool = false; - } - } - }, - _ => { - continue_bool = false; - } - } - }, - _ => { - continue_bool = false; - } - } - if frags.len() == 0 { - continue_bool = false; - } - } - if flag_changed { - new_targets.sort(); - let new_action = ObservableAction{lf_id:act1.lf_id,act_kind:ObservableActionKind::Emission(new_targets),ms_id:act1.ms_id}; - let new_interaction = Interaction::Action(new_action); - frags.insert(0, &new_interaction); - return Some( fold_recursive_strict_frags(&mut frags) ); - } - }, - _ => {} - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} -*/ - - - - - - - diff --git a/src/canonize/transformations/transfokind.rs b/src/canonize/transformations/transfokind.rs deleted file mode 100644 index 1f621bb..0000000 --- a/src/canonize/transformations/transfokind.rs +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -#[derive(Clone, PartialEq, Debug, Eq, Hash)] -pub enum TransformationKind { - SimplLeft, - SimplRight, - FlushLeft, - FlushRight, - InvertAlt, - InvertPar, - TriInvertAltRF, - TriInvertParRF, - Deduplicate, - TriDeduplicateRF, - FactorizePrefixX, - FactorizePrefixS, - FactorizePrefixP, - FactorizeSuffixX, - FactorizeSuffixS, - FactorizeSuffixP, - DeFactorizeL, - DeFactorizeR, - LoopSimpl, - LoopUnNest, - StrictToPassing, - SortEmissionTargets, - MergeAndLeft1, - MergeAndRight1, - MergeAndLeft2, - MergeAndRight2, - MergeAction, - MergeSkip -} - -impl TransformationKind { - pub fn to_string(&self) -> String { - match self { - &TransformationKind::SimplLeft => { - return "SimplLeft".to_string(); - }, - &TransformationKind::SimplRight => { - return "SimplRight".to_string(); - }, - &TransformationKind::FlushLeft => { - return "FlushLeft".to_string(); - }, - &TransformationKind::FlushRight => { - return "FlushRight".to_string(); - }, - &TransformationKind::InvertAlt => { - return "InvertAlt".to_string(); - }, - &TransformationKind::InvertPar => { - return "InvertPar".to_string(); - }, - &TransformationKind::TriInvertAltRF => { - return "TriInvertAltRF".to_string(); - }, - &TransformationKind::TriInvertParRF => { - return "TriInvertParRF".to_string(); - }, - &TransformationKind::Deduplicate => { - return "Deduplicate".to_string(); - }, - &TransformationKind::TriDeduplicateRF => { - return "TriDeduplicateRF".to_string(); - }, - &TransformationKind::FactorizePrefixX => { - return "FactorizePrefixX".to_string(); - }, - &TransformationKind::FactorizePrefixS => { - return "FactorizePrefixS".to_string(); - }, - &TransformationKind::FactorizePrefixP => { - return "FactorizePrefixP".to_string(); - }, - &TransformationKind::FactorizeSuffixX => { - return "FactorizeSuffixX".to_string(); - }, - &TransformationKind::FactorizeSuffixS => { - return "FactorizeSuffixS".to_string(); - }, - &TransformationKind::FactorizeSuffixP => { - return "FactorizeSuffixP".to_string(); - }, - &TransformationKind::DeFactorizeL => { - return "DeFactorizeL".to_string(); - }, - &TransformationKind::DeFactorizeR => { - return "DeFactorizeR".to_string(); - }, - &TransformationKind::LoopSimpl => { - return "LoopSimpl".to_string(); - }, - &TransformationKind::LoopUnNest => { - return "LoopUnNest".to_string(); - }, - &TransformationKind::StrictToPassing => { - return "StrictToPassing".to_string(); - }, - &TransformationKind::SortEmissionTargets => { - return "SortEmissionTargets".to_string(); - }, - &TransformationKind::MergeAndLeft1 => { - return "MergeAndLeft1".to_string(); - }, - &TransformationKind::MergeAndRight1 => { - return "MergeAndRight1".to_string(); - }, - &TransformationKind::MergeAndLeft2 => { - return "MergeAndLeft2".to_string(); - }, - &TransformationKind::MergeAndRight2 => { - return "MergeAndRight2".to_string(); - }, - &TransformationKind::MergeAction => { - return "MergeAction".to_string(); - }, - &TransformationKind::MergeSkip => { - return "MergeSkip".to_string(); - } - } - } -} - diff --git a/src/core/execution/trace/from_model/implem.rs b/src/core/execution/trace/from_model/implem.rs index b927af4..6b110f8 100644 --- a/src/core/execution/trace/from_model/implem.rs +++ b/src/core/execution/trace/from_model/implem.rs @@ -24,7 +24,7 @@ use crate::core::language::syntax::action::{EmissionAction, EmissionTargetRef, R impl InterpretableAsTraceAction for EmissionAction { fn get_all_atomic_actions(&self) -> HashSet { let mut contents : HashSet = HashSet::new(); - contents.insert( self.get_specific_atomic_action(0) ); + contents.insert( self.get_first_atomic_action() ); for target_ref in &self.targets { match target_ref { &EmissionTargetRef::Lifeline(tar_lf_id) => { diff --git a/src/core/language/mod.rs b/src/core/language/mod.rs index 33ada6a..b79f1ba 100644 --- a/src/core/language/mod.rs +++ b/src/core/language/mod.rs @@ -20,4 +20,6 @@ pub mod involve; pub mod hide; pub mod position; pub mod avoid; -pub mod prune; \ No newline at end of file +pub mod prune; +pub mod unfold; +mod ord; \ No newline at end of file diff --git a/src/core/language/ord/action.rs b/src/core/language/ord/action.rs new file mode 100644 index 0000000..d893830 --- /dev/null +++ b/src/core/language/ord/action.rs @@ -0,0 +1,159 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + +use std::cmp::Ordering; +use crate::core::language::syntax::action::{EmissionAction, EmissionTargetRef, ReceptionAction}; + + + +impl Ord for EmissionTargetRef { + fn cmp(&self, other: &Self) -> Ordering { + match (self,other) { + (EmissionTargetRef::Lifeline(self_lf),EmissionTargetRef::Lifeline(other_lf)) => { + return self_lf.cmp(other_lf); + }, + (EmissionTargetRef::Lifeline(_),EmissionTargetRef::Gate(_)) => { + return Ordering::Less; + }, + (EmissionTargetRef::Gate(_),EmissionTargetRef::Lifeline(_)) => { + return Ordering::Greater; + }, + (EmissionTargetRef::Gate(self_gt),EmissionTargetRef::Gate(other_gt)) => { + return self_gt.cmp(other_gt); + } + } + } +} + + + +impl Ord for EmissionAction { + fn cmp(&self, other: &Self) -> Ordering { + if self.ms_id < other.ms_id { + return Ordering::Less; + } + if self.ms_id > other.ms_id { + return Ordering::Greater; + } + // *** + if self.origin_lf_id < other.origin_lf_id { + return Ordering::Less; + } + if self.origin_lf_id > other.origin_lf_id { + return Ordering::Greater; + } + // *** + let max_tar_len = self.targets.len().max(other.targets.len()); + for i in 0..max_tar_len { + match (self.targets.get(i) , other.targets.get(i) ) { + ( Some( tar_ref1 ), Some(tar_ref2) ) => { + if tar_ref1 < tar_ref2 { + return Ordering::Less; + } + if tar_ref1 > tar_ref2 { + return Ordering::Greater; + } + }, + (None,Some(_)) => { + return Ordering::Less; + }, + (Some(_),None) => { + return Ordering::Greater; + }, + (None,None) => {} + } + } + // *** + if self.synchronicity < other.synchronicity { + return Ordering::Less; + } + if self.synchronicity > other.synchronicity { + return Ordering::Greater; + } + // *** + return Ordering::Equal; + } +} + + + +impl Ord for ReceptionAction { + fn cmp(&self, other: &Self) -> Ordering { + if self.ms_id < other.ms_id { + return Ordering::Less; + } + if self.ms_id > other.ms_id { + return Ordering::Greater; + } + // *** + match (self.origin_gt_id,other.origin_gt_id) { + (None,Some(_)) => { + return Ordering::Less; + }, + (Some(_),None) => { + return Ordering::Greater; + }, + (None,None) => {}, + (Some( gt_id1),Some(gt_id2)) => { + if gt_id1 < gt_id2 { + return Ordering::Less; + } + if gt_id1 > gt_id2 { + return Ordering::Greater; + } + } + } + // *** + let max_tar_len = self.recipients.len().max(other.recipients.len()); + for i in 0..max_tar_len { + match (self.recipients.get(i) , other.recipients.get(i) ) { + ( Some( tar_lf_id1 ), Some(tar_lf_id2) ) => { + if tar_lf_id1 < tar_lf_id2 { + return Ordering::Less; + } + if tar_lf_id1 > tar_lf_id2 { + return Ordering::Greater; + } + }, + (None,Some(_)) => { + return Ordering::Less; + }, + (Some(_),None) => { + return Ordering::Greater; + }, + (None,None) => {} + } + } + // *** + if self.synchronicity < other.synchronicity { + return Ordering::Less; + } + if self.synchronicity > other.synchronicity { + return Ordering::Greater; + } + // *** + return Ordering::Equal; + } +} + + + + + + diff --git a/src/core/language/ord/interaction.rs b/src/core/language/ord/interaction.rs new file mode 100644 index 0000000..9772069 --- /dev/null +++ b/src/core/language/ord/interaction.rs @@ -0,0 +1,201 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use std::cmp::Ordering; +use crate::core::language::syntax::interaction::Interaction; + +impl Ord for Interaction { + fn cmp(&self, other: &Self) -> Ordering { + match (self,other) { + (Interaction::Empty,Interaction::Empty) => { + return Ordering::Equal; + }, + (Interaction::Empty,_) => { + return Ordering::Less; + }, + (_,Interaction::Empty) => { + return Ordering::Greater; + }, + // *** + (Interaction::Emission(em1),Interaction::Emission(em2)) => { + return em1.cmp(em2); + }, + (Interaction::Emission(_),_) => { + return Ordering::Less; + }, + (_,Interaction::Emission(_)) => { + return Ordering::Greater; + }, + // *** + (Interaction::Reception(rc1),Interaction::Reception(rc2)) => { + return rc1.cmp(rc2); + }, + (Interaction::Reception(_),_) => { + return Ordering::Less; + }, + (_,Interaction::Reception(_)) => { + return Ordering::Greater; + }, + // *** + (Interaction::Par(self_i1,self_i2),Interaction::Par(other_i1,other_i2)) => { + let cmp_left = self_i1.cmp(other_i1); + match &cmp_left { + Ordering::Equal => { + return self_i2.cmp(other_i2); + }, + _ => { + return cmp_left; + } + } + }, + (Interaction::Par(_,_),_) => { + return Ordering::Less; + }, + (_,Interaction::Par(_,_)) => { + return Ordering::Greater; + }, + // *** + (Interaction::CoReg(self_cr,self_i1,self_i2),Interaction::CoReg(other_cr, other_i1,other_i2)) => { + let max_cr_len = self_cr.len().max(other_cr.len()); + for i in 0..max_cr_len { + match (self_cr.get(i) ,other_cr.get(i) ) { + ( Some( cr_ref1 ), Some(cr_ref2) ) => { + if cr_ref1 < cr_ref2 { + return Ordering::Less; + } + if cr_ref1 > cr_ref2 { + return Ordering::Greater; + } + }, + (None,Some(_)) => { + return Ordering::Less; + }, + (Some(_),None) => { + return Ordering::Greater; + }, + (None,None) => {} + } + } + // *** + let cmp_left = self_i1.cmp(other_i1); + match &cmp_left { + Ordering::Equal => { + return self_i2.cmp(other_i2); + }, + _ => { + return cmp_left; + } + } + }, + (Interaction::CoReg(_,_,_),_) => { + return Ordering::Less; + }, + (_,Interaction::CoReg(_,_,_)) => { + return Ordering::Greater; + }, + // *** + (Interaction::Seq(self_i1,self_i2),Interaction::Seq(other_i1,other_i2)) => { + let cmp_left = self_i1.cmp(other_i1); + match &cmp_left { + Ordering::Equal => { + return self_i2.cmp(other_i2); + }, + _ => { + return cmp_left; + } + } + }, + (Interaction::Seq(_,_),_) => { + return Ordering::Less; + }, + (_,Interaction::Seq(_,_)) => { + return Ordering::Greater; + }, + // *** + (Interaction::Strict(self_i1,self_i2),Interaction::Strict(other_i1,other_i2)) => { + let cmp_left = self_i1.cmp(other_i1); + match &cmp_left { + Ordering::Equal => { + return self_i2.cmp(other_i2); + }, + _ => { + return cmp_left; + } + } + }, + (Interaction::Strict(_,_),_) => { + return Ordering::Less; + }, + (_,Interaction::Strict(_,_)) => { + return Ordering::Greater; + }, + // *** + (Interaction::Alt(self_i1,self_i2),Interaction::Alt(other_i1,other_i2)) => { + let cmp_left = self_i1.cmp(other_i1); + match &cmp_left { + Ordering::Equal => { + return self_i2.cmp(other_i2); + }, + _ => { + return cmp_left; + } + } + }, + (Interaction::Alt(_,_),_) => { + return Ordering::Less; + }, + (_,Interaction::Alt(_,_)) => { + return Ordering::Greater; + }, + // *** + (Interaction::Loop(self_lk,self_i1),Interaction::Loop(other_lk,other_i1)) => { + let cmp_lk = self_lk.cmp(other_lk); + match &cmp_lk { + Ordering::Equal => { + return self_i1.cmp(other_i1); + }, + _ => { + return cmp_lk; + } + } + }, + (Interaction::Loop(_,_),_) => { + return Ordering::Less; + }, + (_,Interaction::Loop(_,_)) => { + return Ordering::Greater; + } + (Interaction::And(self_i1,self_i2),Interaction::And(other_i1,other_i2)) => { + let cmp_left = self_i1.cmp(other_i1); + match &cmp_left { + Ordering::Equal => { + return self_i2.cmp(other_i2); + }, + _ => { + return cmp_left; + } + } + }, + (Interaction::And(_,_),_) => { + return Ordering::Less; + }, + (_,Interaction::And(_,_)) => { + return Ordering::Greater; + } + } + } +} \ No newline at end of file diff --git a/src/output/rendering/custom_draw/utils/mod.rs b/src/core/language/ord/mod.rs similarity index 93% rename from src/output/rendering/custom_draw/utils/mod.rs rename to src/core/language/ord/mod.rs index b6c7484..44c28d1 100644 --- a/src/output/rendering/custom_draw/utils/mod.rs +++ b/src/core/language/ord/mod.rs @@ -13,5 +13,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ -pub mod colored_text; -pub mod arrow_heads; \ No newline at end of file + + +mod action; +mod interaction; \ No newline at end of file diff --git a/src/core/language/position/position.rs b/src/core/language/position/position.rs index aa587fa..abdad75 100644 --- a/src/core/language/position/position.rs +++ b/src/core/language/position/position.rs @@ -23,8 +23,38 @@ pub enum Position { Epsilon(Option) } - - +impl Position { + pub fn to_string(&self) -> String { + match self { + Position::Left(ref in_self) => { + let mut my_string = "1".to_string(); + let sub_pos = in_self.to_string(); + if sub_pos != "0".to_string() { + my_string.push_str( &sub_pos ); + } + return my_string; + }, + Position::Right(ref in_self) => { + let mut my_string = "2".to_string(); + let sub_pos = in_self.to_string(); + if sub_pos != "0".to_string() { + my_string.push_str( &sub_pos ); + } + return my_string; + }, + Position::Epsilon(sub_pos) => { + match sub_pos { + None => { + return "0".to_string(); + }, + Some(sbp_idx) => { + return format!("s{:}",sbp_idx); + } + } + } + } + } +} diff --git a/src/core/language/syntax/action.rs b/src/core/language/syntax/action.rs index 0cf482b..a7061b5 100644 --- a/src/core/language/syntax/action.rs +++ b/src/core/language/syntax/action.rs @@ -20,19 +20,19 @@ use std::fmt::Debug; -#[derive(PartialOrd, Ord, Clone, PartialEq, Debug, Eq, Hash)] +#[derive(Clone, PartialEq, Debug, Eq, Hash, PartialOrd)] pub enum EmissionTargetRef { Lifeline(usize), Gate(usize) } -#[derive(PartialOrd, Ord, Clone, PartialEq, Debug, Eq, Hash)] +#[derive(Clone, PartialEq, Debug, Eq, Hash, PartialOrd)] pub enum CommunicationSynchronicity { Asynchronous, Synchronous } -#[derive(Clone, PartialEq, Debug, Eq, Hash)] +#[derive(Clone, PartialEq, Debug, Eq, Hash, PartialOrd)] pub struct EmissionAction { pub origin_lf_id : usize, pub ms_id : usize, @@ -49,7 +49,7 @@ impl EmissionAction { } } -#[derive(Clone, PartialEq, Debug, Eq, Hash)] +#[derive(Clone, PartialEq, Debug, Eq, Hash, PartialOrd)] pub struct ReceptionAction { pub origin_gt_id : Option, pub ms_id : usize, diff --git a/src/core/language/syntax/interaction.rs b/src/core/language/syntax/interaction.rs index c3b2de9..80a4632 100644 --- a/src/core/language/syntax/interaction.rs +++ b/src/core/language/syntax/interaction.rs @@ -28,7 +28,7 @@ pub enum LoopKind { SStrictSeq = 4 } -#[derive(Clone, PartialEq, Debug, Eq, Hash)] +#[derive(Clone, PartialEq, Debug, Eq, Hash, PartialOrd)] pub enum Interaction { Empty, Emission(EmissionAction), diff --git a/src/core/language/syntax/util/fold_recursive_frags.rs b/src/core/language/syntax/util/fold_recursive_frags.rs index c9ba19a..0af6049 100644 --- a/src/core/language/syntax/util/fold_recursive_frags.rs +++ b/src/core/language/syntax/util/fold_recursive_frags.rs @@ -20,6 +20,22 @@ limitations under the License. use crate::core::language::syntax::interaction::Interaction; +pub fn fold_recursive_alt_frags(frags : &mut Vec<&Interaction>) -> Interaction { + let frag_num = frags.len(); + if frag_num == 2 { + let i2 = frags.pop().unwrap(); + let i1 = frags.pop().unwrap(); + return Interaction::Alt( Box::new(i1.clone()), Box::new(i2.clone()) ); + } else if frag_num == 1 { + return frags.pop().unwrap().clone(); + } else if frag_num == 0 { + return Interaction::Empty + } else { + let i1 = frags.remove(0); + return Interaction::Alt( Box::new(i1.clone()), Box::new( fold_recursive_alt_frags(frags) ) ); + } +} + pub fn fold_recursive_strict_frags(frags : &mut Vec<&Interaction>) -> Interaction { let frag_num = frags.len(); if frag_num == 2 { diff --git a/src/output/rendering/custom_draw/transition/mod.rs b/src/core/language/syntax/util/unfold_action.rs similarity index 92% rename from src/output/rendering/custom_draw/transition/mod.rs rename to src/core/language/syntax/util/unfold_action.rs index 7ecd040..7de54bb 100644 --- a/src/output/rendering/custom_draw/transition/mod.rs +++ b/src/core/language/syntax/util/unfold_action.rs @@ -15,7 +15,9 @@ limitations under the License. */ -pub mod draw_firing; -pub mod draw_hiding; +//todo: unfold an atomic action into a term + + +impl \ No newline at end of file diff --git a/src/core/language/unfold/action.rs b/src/core/language/unfold/action.rs new file mode 100644 index 0000000..679c1bc --- /dev/null +++ b/src/core/language/unfold/action.rs @@ -0,0 +1,89 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use crate::core::language::syntax::action::{CommunicationSynchronicity, EmissionAction, EmissionTargetRef, ReceptionAction}; +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::unfold::unfoldable::AtomicUnfoldableAsInteraction; + + + + +impl AtomicUnfoldableAsInteraction for EmissionAction { + fn unfold_as_interaction(&self) -> Interaction { + if self.targets.len() == 0 { + return Interaction::Emission(self.clone()); + } else { + let emission = EmissionAction::new(self.origin_lf_id,self.ms_id,CommunicationSynchronicity::Asynchronous,vec![]); + let mut receptions = vec![]; + for target_ref in &self.targets { + match target_ref { + EmissionTargetRef::Lifeline(tar_lf_id) => { + receptions.push( ReceptionAction::new(None,self.ms_id,CommunicationSynchronicity::Asynchronous,vec![*tar_lf_id])); + }, + _ => { + // nothing + } + } + } + return Interaction::Strict(Box::new(Interaction::Emission(emission)), + Box::new(deploy_receptions(&mut receptions))); + } + } +} + + + +impl AtomicUnfoldableAsInteraction for ReceptionAction { + fn unfold_as_interaction(&self) -> Interaction { + match self.recipients.len() { + 0 => { + return Interaction::Empty; + }, + 1 => { + return Interaction::Reception(self.clone()); + }, + _ => { + let mut receptions = vec![]; + for rcp_lf_id in &self.recipients { + receptions.push( ReceptionAction::new(None,self.ms_id,CommunicationSynchronicity::Asynchronous,vec![*rcp_lf_id])); + } + return deploy_receptions(&mut receptions); + } + } + } +} + + +fn deploy_receptions(rem_targets : &mut Vec) -> Interaction { + let rem_tlen = rem_targets.len(); + if rem_tlen == 0 { + return Interaction::Empty; + } else if rem_tlen == 1 { + let rcp = rem_targets.remove(0); + return Interaction::Reception(rcp); + } else if rem_tlen == 2 { + let rcp1 = rem_targets.remove(0); + let rcp2 = rem_targets.remove(0); + return Interaction::Seq( Box::new(Interaction::Reception(rcp1)), Box::new(Interaction::Reception(rcp2)) ); + } else { + let rcp1 = rem_targets.remove(0); + return Interaction::Seq(Box::new(Interaction::Reception(rcp1)), Box::new(deploy_receptions(rem_targets))); + } +} + + diff --git a/src/core/language/unfold/mod.rs b/src/core/language/unfold/mod.rs new file mode 100644 index 0000000..f7c7786 --- /dev/null +++ b/src/core/language/unfold/mod.rs @@ -0,0 +1,19 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +pub mod unfoldable; +mod action; \ No newline at end of file diff --git a/src/process/canon_proc/node.rs b/src/core/language/unfold/unfoldable.rs similarity index 78% rename from src/process/canon_proc/node.rs rename to src/core/language/unfold/unfoldable.rs index b0c6191..eb20499 100644 --- a/src/process/canon_proc/node.rs +++ b/src/core/language/unfold/unfoldable.rs @@ -16,14 +16,10 @@ limitations under the License. - - use crate::core::language::syntax::interaction::Interaction; -use crate::proc_refactoring::abstract_proc::AbstractNodeKind; -pub struct CanonizationNodeKind { - pub interaction : Interaction -} +pub trait AtomicUnfoldableAsInteraction : Sized { -impl AbstractNodeKind for CanonizationNodeKind {} + fn unfold_as_interaction(&self) -> Interaction; +} diff --git a/src/core/mod.rs b/src/core/mod.rs index c0ff5dd..ec70f43 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -16,10 +16,10 @@ limitations under the License. pub mod language; +pub mod transformation; pub mod execution; pub mod colocalizations; pub mod general_context; pub mod error; -//pub mod trace; diff --git a/src/canonize/transformations/get_all_transfos.rs b/src/core/transformation/get_transfos/get_all_transfos.rs similarity index 71% rename from src/canonize/transformations/get_all_transfos.rs rename to src/core/transformation/get_transfos/get_all_transfos.rs index a923fcc..8c7cdb8 100644 --- a/src/canonize/transformations/get_all_transfos.rs +++ b/src/core/transformation/get_transfos/get_all_transfos.rs @@ -14,44 +14,17 @@ See the License for the specific language governing permissions and limitations under the License. */ -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::general_context::GeneralContext; - -use crate::output::rendering::textual::monochrome::position::position_to_text; - -use crate::canonize::transformations::transfokind::*; -use crate::canonize::transformations::transfodef::*; -use crate::canonize::transformations::phases::*; -pub fn phase_1_all_transfos(interaction : &Interaction) -> Vec { - return get_all_transformations_rec(&transfos_phase1(),interaction); -} - -pub fn phase_2_all_transfos(interaction : &Interaction) -> Vec { - return get_all_transformations_rec(&transfos_phase2(),interaction); -} +use crate::core::language::position::position::Position; +use crate::core::language::syntax::interaction::Interaction; +use crate::core::transformation::transfodef::InteractionTransformation; +use crate::core::transformation::transfokind::InteractionTransformationKind; -fn get_all_transformations_inner(transfos : &Vec<(TransformationKind, &dyn Fn(&Interaction) -> Option)>, - interaction : &Interaction) -> Vec { - let mut results : Vec = Vec::new(); - for (transfo_kind, transfo_func) in transfos { - match transfo_func(interaction) { - None => {}, - Some(new_int) => { - results.push( InteractionTermTransformation::new((*transfo_kind).clone(),Position::Epsilon(None),new_int) ); - } - } - } - return results; -} - -fn get_all_transformations_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Interaction) -> Option)>, - interaction : &Interaction) -> Vec { +pub fn get_all_transformations_rec(transfos : &Vec<(InteractionTransformationKind, &dyn Fn(&Interaction) -> Vec)>, + interaction : &Interaction) -> Vec { let mut results = get_all_transformations_inner(transfos,interaction); match interaction { &Interaction::Empty => { @@ -62,85 +35,85 @@ fn get_all_transformations_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Int // *** }, &Interaction::Strict(ref i1, ref i2) => { for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, + results.push( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Strict(Box::new(left_transfo.result),i2.clone()) ) ); } for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, + results.push( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Strict(i1.clone(), Box::new(right_transfo.result)) ) ); } }, &Interaction::Seq(ref i1, ref i2) => { for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, + results.push( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Seq(Box::new(left_transfo.result),i2.clone()) ) ); } for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, + results.push( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Seq(i1.clone(), Box::new(right_transfo.result)) ) ); } }, &Interaction::CoReg(ref cr, ref i1, ref i2) => { for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, + results.push( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::CoReg(cr.clone(), Box::new(left_transfo.result),i2.clone()) ) ); } for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, + results.push( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::CoReg(cr.clone(), i1.clone(), Box::new(right_transfo.result)) ) ); } }, &Interaction::Par(ref i1, ref i2) => { for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, + results.push( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Par(Box::new(left_transfo.result),i2.clone()) ) ); } for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, + results.push( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Par(i1.clone(), Box::new(right_transfo.result)) ) ); } }, &Interaction::Alt(ref i1, ref i2) => { for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, + results.push( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Alt(Box::new(left_transfo.result),i2.clone()) ) ); } for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, + results.push( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Alt(i1.clone(), Box::new(right_transfo.result)) ) ); } }, &Interaction::Loop(ref lk, ref i1) => { for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, + results.push( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Loop(lk.clone(), Box::new(left_transfo.result)) ) ); } }, &Interaction::And(ref i1, ref i2) => { for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, + results.push( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Strict(Box::new(left_transfo.result),i2.clone()) ) ); } for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, + results.push( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Strict(i1.clone(), Box::new(right_transfo.result)) ) ); @@ -150,4 +123,15 @@ fn get_all_transformations_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Int return results; } +fn get_all_transformations_inner(transfos : &Vec<(InteractionTransformationKind, &dyn Fn(&Interaction) -> Vec)>, + interaction : &Interaction) -> Vec { + + let mut results : Vec = Vec::new(); + for (transfo_kind, transfo_func) in transfos { + let new_transfos : Vec = transfo_func(interaction) + .into_iter().map(|x| InteractionTransformation::new((*transfo_kind).clone(),Position::Epsilon(None),x)).collect(); + results.extend(new_transfos); + } + return results; +} diff --git a/src/canonize/transformations/get_one_transfo.rs b/src/core/transformation/get_transfos/get_one_transfo.rs similarity index 73% rename from src/canonize/transformations/get_one_transfo.rs rename to src/core/transformation/get_transfos/get_one_transfo.rs index c1f36cf..cea2283 100644 --- a/src/canonize/transformations/get_one_transfo.rs +++ b/src/core/transformation/get_transfos/get_one_transfo.rs @@ -18,55 +18,13 @@ limitations under the License. use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; use crate::core::language::position::position::Position; -use crate::core::general_context::GeneralContext; +use crate::core::transformation::transfodef::InteractionTransformation; +use crate::core::transformation::transfokind::InteractionTransformationKind; -use crate::output::rendering::textual::monochrome::position::position_to_text; -use crate::canonize::transformations::transfokind::*; -use crate::canonize::transformations::transfodef::*; - -use crate::canonize::transformations::phases::*; - - -pub fn phase_1_one_transfo(interaction : &Interaction) -> Vec { - match get_one_transformation_rec(&transfos_phase1(),interaction) { - Some( got_transfo ) => { - return vec![got_transfo]; - }, - None => { - return Vec::new(); - } - } -} - -pub fn phase_2_one_transfo(interaction : &Interaction) -> Vec { - match get_one_transformation_rec(&transfos_phase2(),interaction) { - Some( got_transfo ) => { - return vec![got_transfo]; - }, - None => { - return Vec::new(); - } - } -} - -fn get_one_transformation_inner(transfos : &Vec<(TransformationKind, &dyn Fn(&Interaction) -> Option)>, - interaction : &Interaction) -> Option { - for (transfo_kind, transfo_func) in transfos { - match transfo_func(interaction) { - None => {}, - Some(new_int) => { - return Some( InteractionTermTransformation::new((*transfo_kind).clone(),Position::Epsilon(None),new_int) ); - } - } - } - return None; -} - -fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Interaction) -> Option)>, - interaction : &Interaction) -> Option { +pub fn get_one_transformation_rec(transfos : &Vec<(InteractionTransformationKind, &dyn Fn(&Interaction) -> Vec)>, + interaction : &Interaction) -> Option { match get_one_transformation_inner(transfos,interaction) { Some( got_transfo ) => { return Some(got_transfo); @@ -82,7 +40,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte }, &Interaction::Strict(ref i1, ref i2) => { match get_one_transformation_rec(transfos,i1) { Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, + return Some( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Strict(Box::new(left_transfo.result),i2.clone())) ); }, @@ -90,7 +48,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte } match get_one_transformation_rec(transfos,i2) { Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, + return Some( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Strict(i1.clone(), Box::new(right_transfo.result))) ); }, @@ -99,7 +57,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte }, &Interaction::Seq(ref i1, ref i2) => { match get_one_transformation_rec(transfos,i1) { Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, + return Some( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Seq(Box::new(left_transfo.result),i2.clone())) ); }, @@ -107,7 +65,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte } match get_one_transformation_rec(transfos,i2) { Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, + return Some( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Seq(i1.clone(), Box::new(right_transfo.result))) ); }, @@ -116,7 +74,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte }, &Interaction::CoReg(ref cr, ref i1, ref i2) => { match get_one_transformation_rec(transfos,i1) { Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, + return Some( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::CoReg(cr.clone(), Box::new(left_transfo.result),i2.clone())) ); }, @@ -124,7 +82,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte } match get_one_transformation_rec(transfos,i2) { Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, + return Some( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::CoReg(cr.clone(), i1.clone(), Box::new(right_transfo.result))) ); }, @@ -133,7 +91,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte }, &Interaction::Par(ref i1, ref i2) => { match get_one_transformation_rec(transfos,i1) { Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, + return Some( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Par(Box::new(left_transfo.result),i2.clone())) ); }, @@ -141,7 +99,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte } match get_one_transformation_rec(transfos,i2) { Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, + return Some( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Par(i1.clone(), Box::new(right_transfo.result))) ); }, @@ -150,7 +108,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte }, &Interaction::Alt(ref i1, ref i2) => { match get_one_transformation_rec(transfos,i1) { Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, + return Some( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Alt(Box::new(left_transfo.result),i2.clone())) ); }, @@ -158,7 +116,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte } match get_one_transformation_rec(transfos,i2) { Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, + return Some( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Alt(i1.clone(), Box::new(right_transfo.result))) ); }, @@ -167,7 +125,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte }, &Interaction::Loop(ref lk, ref i1) => { match get_one_transformation_rec(transfos,i1) { Some(sub_transfo) => { - return Some( InteractionTermTransformation::new(sub_transfo.kind, + return Some( InteractionTransformation::new(sub_transfo.kind, Position::Left(Box::new(sub_transfo.position)), Interaction::Loop(lk.clone(), Box::new(sub_transfo.result))) ); }, @@ -176,7 +134,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte }, &Interaction::And(ref i1, ref i2) => { match get_one_transformation_rec(transfos,i1) { Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, + return Some( InteractionTransformation::new(left_transfo.kind, Position::Left(Box::new(left_transfo.position)), Interaction::Strict(Box::new(left_transfo.result),i2.clone())) ); }, @@ -184,7 +142,7 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte } match get_one_transformation_rec(transfos,i2) { Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, + return Some( InteractionTransformation::new(right_transfo.kind, Position::Right(Box::new(right_transfo.position)), Interaction::Strict(i1.clone(), Box::new(right_transfo.result))) ); }, @@ -198,3 +156,14 @@ fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Inte } +fn get_one_transformation_inner(transfos : &Vec<(InteractionTransformationKind, &dyn Fn(&Interaction) -> Vec)>, + interaction : &Interaction) -> Option { + for (transfo_kind, transfo_func) in transfos { + let mut new_transfos : Vec = transfo_func(interaction) + .into_iter().map(|x| InteractionTransformation::new((*transfo_kind).clone(),Position::Epsilon(None),x)).collect(); + if new_transfos.len() > 0 { + return Some(new_transfos.remove(0)); + } + } + return None; +} \ No newline at end of file diff --git a/src/core/transformation/get_transfos/get_transfos.rs b/src/core/transformation/get_transfos/get_transfos.rs new file mode 100644 index 0000000..da25ceb --- /dev/null +++ b/src/core/transformation/get_transfos/get_transfos.rs @@ -0,0 +1,42 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::core::language::syntax::interaction::Interaction; +use crate::core::transformation::get_transfos::get_all_transfos::get_all_transformations_rec; +use crate::core::transformation::get_transfos::get_one_transfo::get_one_transformation_rec; +use crate::core::transformation::transfodef::InteractionTransformation; +use crate::core::transformation::transfokind::InteractionTransformationKind; + + +pub fn get_transfos(interaction : &Interaction, + get_all : bool, + transfos : &Vec<(InteractionTransformationKind, &dyn Fn(&Interaction) -> Vec)>) + -> Vec { + if get_all { + return get_all_transformations_rec(transfos,interaction); + } else { + match get_one_transformation_rec(transfos,interaction) { + None => { + return Vec::new(); + }, + Some( got ) => { + return vec![got]; + } + } + } +} + diff --git a/src/core/transformation/get_transfos/mod.rs b/src/core/transformation/get_transfos/mod.rs new file mode 100644 index 0000000..bbeab74 --- /dev/null +++ b/src/core/transformation/get_transfos/mod.rs @@ -0,0 +1,21 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +mod get_all_transfos; +mod get_one_transfo; + +pub mod get_transfos; \ No newline at end of file diff --git a/src/canonize/transformations/mod.rs b/src/core/transformation/mod.rs similarity index 90% rename from src/canonize/transformations/mod.rs rename to src/core/transformation/mod.rs index f69ea25..4c7bc4e 100644 --- a/src/canonize/transformations/mod.rs +++ b/src/core/transformation/mod.rs @@ -17,9 +17,6 @@ limitations under the License. pub mod transfokind; pub mod transfodef; -pub mod phases; - -pub mod get_all_transfos; -pub mod get_one_transfo; - +pub mod transfofunc; +pub mod get_transfos; diff --git a/src/core/transformation/transfodef.rs b/src/core/transformation/transfodef.rs new file mode 100644 index 0000000..b972f20 --- /dev/null +++ b/src/core/transformation/transfodef.rs @@ -0,0 +1,34 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::core::language::position::position::Position; +use crate::core::language::syntax::interaction::Interaction; +use crate::core::transformation::transfokind::InteractionTransformationKind; + +pub struct InteractionTransformation { + pub kind : InteractionTransformationKind, + pub position : Position, + pub result : Interaction +} + +impl InteractionTransformation { + pub fn new(kind : InteractionTransformationKind, + position : Position, + result : Interaction) -> InteractionTransformation { + return InteractionTransformation{kind,position,result}; + } +} \ No newline at end of file diff --git a/src/core/transformation/transfofunc/action.rs b/src/core/transformation/transfofunc/action.rs new file mode 100644 index 0000000..005062e --- /dev/null +++ b/src/core/transformation/transfofunc/action.rs @@ -0,0 +1,44 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + +use crate::core::language::syntax::action::{EmissionAction, ReceptionAction}; +use crate::core::language::syntax::interaction::Interaction; + +pub fn sort_action_content(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Emission(ref em_act) => { + let mut new_targets = em_act.targets.clone(); + new_targets.sort(); + if new_targets != em_act.targets { + let new_emission = EmissionAction::new(em_act.origin_lf_id,em_act.ms_id,em_act.synchronicity.clone(),new_targets); + return vec![Interaction::Emission(new_emission)]; + } + }, + &Interaction::Reception(ref rc_act) => { + let mut new_targets = rc_act.recipients.clone(); + new_targets.sort(); + if new_targets != rc_act.recipients { + let new_reception = ReceptionAction::new(rc_act.origin_gt_id.clone(),rc_act.ms_id,rc_act.synchronicity.clone(),new_targets); + return vec![Interaction::Reception(new_reception)]; + } + }, + _ => {} + } + return vec![]; +} \ No newline at end of file diff --git a/src/core/transformation/transfofunc/dedupl.rs b/src/core/transformation/transfofunc/dedupl.rs new file mode 100644 index 0000000..c9f8f72 --- /dev/null +++ b/src/core/transformation/transfofunc/dedupl.rs @@ -0,0 +1,37 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use std::collections::HashSet; +use itertools::Itertools; +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::syntax::util::fold_recursive_frags::{fold_recursive_alt_frags, fold_recursive_par_frags}; +use crate::core::language::syntax::util::get_recursive_frag::get_recursive_alt_frags; + +pub fn deduplicate(interaction : &Interaction) -> Vec { + let orig_alt_frags = get_recursive_alt_frags(interaction); + let as_set : HashSet<&Interaction> = HashSet::from_iter(orig_alt_frags.iter().cloned()); + if as_set.len() < orig_alt_frags.len() { + let mut new_alt_frags : Vec<&Interaction> = as_set.into_iter().sorted().collect(); // + return vec![fold_recursive_alt_frags(&mut new_alt_frags)]; + } else { + return vec![]; + } +} + + + diff --git a/src/core/transformation/transfofunc/defactorize.rs b/src/core/transformation/transfofunc/defactorize.rs new file mode 100644 index 0000000..e5177a3 --- /dev/null +++ b/src/core/transformation/transfofunc/defactorize.rs @@ -0,0 +1,117 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + +use crate::core::language::syntax::interaction::Interaction; + +pub fn defactorize_left(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Strict(ref i1, ref i2) => { + match **i2 { + Interaction::Alt(ref i21, ref i22) => { + let new_iA = Interaction::Strict( i1.clone(), i21.clone() ); + let new_iB = Interaction::Strict( i1.clone(), i22.clone() ); + return vec![ Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ]; + }, + _ => {} + } + }, + &Interaction::Seq(ref i1, ref i2) => { + match **i2 { + Interaction::Alt(ref i21, ref i22) => { + let new_iA = Interaction::Seq( i1.clone(), i21.clone() ); + let new_iB = Interaction::Seq( i1.clone(), i22.clone() ); + return vec![ Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ]; + }, + _ => {} + } + }, + &Interaction::Par(ref i1, ref i2) => { + match **i2 { + Interaction::Alt(ref i21, ref i22) => { + let new_iA = Interaction::Par( i1.clone(), i21.clone() ); + let new_iB = Interaction::Par( i1.clone(), i22.clone() ); + return vec![ Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ]; + }, + _ => {} + } + }, + &Interaction::CoReg(ref cr, ref i1, ref i2) => { + match **i2 { + Interaction::Alt(ref i21, ref i22) => { + let new_iA = Interaction::CoReg( cr.clone(), i1.clone(), i21.clone() ); + let new_iB = Interaction::CoReg( cr.clone(), i1.clone(), i22.clone() ); + return vec![ Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ]; + }, + _ => {} + } + }, + _ => {} + } + return vec![]; +} + + + +pub fn defactorize_right(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Strict(ref i1, ref i2) => { + match **i1 { + Interaction::Alt(ref i11, ref i12) => { + let new_iA = Interaction::Strict( i11.clone(), i2.clone() ); + let new_iB = Interaction::Strict( i12.clone(), i2.clone() ); + return vec![ Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ]; + }, + _ => {} + } + }, + &Interaction::Seq(ref i1, ref i2) => { + match **i1 { + Interaction::Alt(ref i11, ref i12) => { + let new_iA = Interaction::Seq( i11.clone(), i2.clone() ); + let new_iB = Interaction::Seq( i12.clone(), i2.clone() ); + return vec![ Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ]; + }, + _ => {} + } + }, + &Interaction::Par(ref i1, ref i2) => { + match **i1 { + Interaction::Alt(ref i11, ref i12) => { + let new_iA = Interaction::Par( i11.clone(), i2.clone() ); + let new_iB = Interaction::Par( i12.clone(), i2.clone() ); + return vec![ Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ]; + }, + _ => {} + } + }, + &Interaction::CoReg(ref cr, ref i1, ref i2) => { + match **i1 { + Interaction::Alt(ref i11, ref i12) => { + let new_iA = Interaction::CoReg( cr.clone(), i11.clone(), i2.clone() ); + let new_iB = Interaction::CoReg( cr.clone(), i12.clone(), i2.clone() ); + return vec![ Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ]; + }, + _ => {} + } + }, + _ => {} + } + return vec![]; +} + diff --git a/src/core/transformation/transfofunc/factorize_par.rs b/src/core/transformation/transfofunc/factorize_par.rs new file mode 100644 index 0000000..43aaca9 --- /dev/null +++ b/src/core/transformation/transfofunc/factorize_par.rs @@ -0,0 +1,58 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + + + +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::syntax::util::fold_recursive_frags::*; +use crate::core::language::syntax::util::get_recursive_frag::*; + + + +pub fn factorize_par(interaction : &Interaction) -> Vec { + let mut got_ints = vec![]; + match interaction { + &Interaction::Alt(ref i1, ref i2) => { + let left_par_frags = get_recursive_par_frags(i1); + let right_par_frags = get_recursive_par_frags(i2); + // *** + for (left_frag_id,left_frag) in left_par_frags.iter().enumerate() { + for (right_frag_id,right_frag) in right_par_frags.iter().enumerate() { + if left_frag == right_frag { + let mut new_left_par_frags = left_par_frags.clone(); + new_left_par_frags.remove(left_frag_id); + let mut new_right_par_frags = right_par_frags.clone(); + new_right_par_frags.remove(right_frag_id); + // *** + let new_alt = Interaction::Alt(Box::new(fold_recursive_par_frags(&mut new_left_par_frags)), + Box::new(fold_recursive_par_frags(&mut new_right_par_frags)) + ); + if *left_frag != &Interaction::Empty { + got_ints.push( Interaction::Par( Box::new((*left_frag).clone()), Box::new(new_alt)) ) + } else { + got_ints.push(new_alt); + } + } + } + } + }, + _ => {} + } + return got_ints; +} diff --git a/src/core/transformation/transfofunc/factorize_prefix.rs b/src/core/transformation/transfofunc/factorize_prefix.rs new file mode 100644 index 0000000..42bb7ae --- /dev/null +++ b/src/core/transformation/transfofunc/factorize_prefix.rs @@ -0,0 +1,110 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + + +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::syntax::util::fold_recursive_frags::*; +use crate::core::language::syntax::util::get_recursive_frag::*; + + + +pub fn factorize_prefix_strict(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Alt(ref i1, ref i2) => { + let mut left_strict_frags = get_recursive_strict_frags(i1); + // *** + match **i2 { + Interaction::Alt(ref i21,ref i22) => { + let mut right_strict_frags = get_recursive_strict_frags(i21); + if left_strict_frags[0] == right_strict_frags[0] { + let first_frag = left_strict_frags.remove(0); + right_strict_frags.remove(0); + if first_frag != &Interaction::Empty { + let inner_alt = Interaction::Alt(Box::new(fold_recursive_strict_frags(&mut left_strict_frags)), + Box::new(fold_recursive_strict_frags(&mut right_strict_frags)) + ); + let inner_strict = Interaction::Strict(Box::new(first_frag.clone()), Box::new(inner_alt)); + // *** + return vec![Interaction::Alt( Box::new(inner_strict), i22.clone())]; + } + } + }, + _ => { + let mut right_strict_frags = get_recursive_strict_frags(i2); + if left_strict_frags[0] == right_strict_frags[0] { + let first_frag = left_strict_frags.remove(0); + right_strict_frags.remove(0); + if first_frag != &Interaction::Empty { + let new_alt = Interaction::Alt(Box::new(fold_recursive_strict_frags(&mut left_strict_frags)), + Box::new(fold_recursive_strict_frags(&mut right_strict_frags)) + ); + return vec![Interaction::Strict( Box::new(first_frag.clone()), Box::new(new_alt))]; + } + } + } + } + }, + _ => {} + } + return vec![]; +} + +pub fn factorize_prefix_seq(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Alt(ref i1, ref i2) => { + let mut left_seq_frags = get_recursive_seq_frags(i1); + // *** + match **i2 { + Interaction::Alt(ref i21,ref i22) => { + let mut right_seq_frags = get_recursive_seq_frags(i21); + if left_seq_frags[0] == right_seq_frags[0] { + let first_frag = left_seq_frags.remove(0); + right_seq_frags.remove(0); + if first_frag != &Interaction::Empty { + let inner_alt = Interaction::Alt(Box::new(fold_recursive_seq_frags(&mut left_seq_frags)), + Box::new(fold_recursive_seq_frags(&mut right_seq_frags)) + ); + let inner_seq = Interaction::Seq(Box::new(first_frag.clone()), Box::new(inner_alt)); + // *** + return vec![Interaction::Alt( Box::new(inner_seq), i22.clone())]; + } + } + }, + _ => { + let mut right_seq_frags = get_recursive_seq_frags(i2); + if left_seq_frags[0] == right_seq_frags[0] { + let first_frag = left_seq_frags.remove(0); + right_seq_frags.remove(0); + if first_frag != &Interaction::Empty { + let new_alt = Interaction::Alt(Box::new(fold_recursive_seq_frags(&mut left_seq_frags)), + Box::new(fold_recursive_seq_frags(&mut right_seq_frags)) + ); + return vec![Interaction::Seq( Box::new(first_frag.clone()), Box::new(new_alt))]; + } + } + } + } + }, + _ => {} + } + return vec![]; +} + + + diff --git a/src/core/transformation/transfofunc/factorize_suffix.rs b/src/core/transformation/transfofunc/factorize_suffix.rs new file mode 100644 index 0000000..4f0e147 --- /dev/null +++ b/src/core/transformation/transfofunc/factorize_suffix.rs @@ -0,0 +1,68 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + + +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::syntax::util::fold_recursive_frags::*; +use crate::core::language::syntax::util::get_recursive_frag::*; + + + +pub fn factorize_suffix_strict(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Alt(ref i1, ref i2) => { + let mut left_strict_frags = get_recursive_strict_frags(i1); + let mut right_strict_frags = get_recursive_strict_frags(i2); + if left_strict_frags.last() == right_strict_frags.last() { + let last_frag : &Interaction = left_strict_frags.pop().unwrap(); + right_strict_frags.pop(); + if last_frag != &Interaction::Empty { + let new_alt = Interaction::Alt(Box::new(fold_recursive_strict_frags(&mut left_strict_frags)), + Box::new(fold_recursive_strict_frags(&mut right_strict_frags)) + ); + return vec![Interaction::Strict( Box::new(new_alt), Box::new(last_frag.clone()) )]; + } + } + }, + _ => {} + } + return vec![]; +} + +pub fn factorize_suffix_seq(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Alt(ref i1, ref i2) => { + let mut left_seq_frags = get_recursive_seq_frags(i1); + let mut right_seq_frags = get_recursive_seq_frags(i2); + if left_seq_frags.last() == right_seq_frags.last() { + let last_frag : &Interaction = left_seq_frags.pop().unwrap(); + right_seq_frags.pop(); + if last_frag != &Interaction::Empty { + let new_alt = Interaction::Alt(Box::new(fold_recursive_seq_frags(&mut left_seq_frags)), + Box::new(fold_recursive_seq_frags(&mut right_seq_frags)) + ); + return vec![Interaction::Seq( Box::new(new_alt), Box::new(last_frag.clone()) )]; + } + } + }, + _ => {} + } + return vec![]; +} + diff --git a/src/core/transformation/transfofunc/flush.rs b/src/core/transformation/transfofunc/flush.rs new file mode 100644 index 0000000..fb192b9 --- /dev/null +++ b/src/core/transformation/transfofunc/flush.rs @@ -0,0 +1,130 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use crate::core::language::syntax::interaction::Interaction; + +pub fn flush_right(interaction : &Interaction) -> Vec { + let mut new_int : Option = None; + match interaction { + &Interaction::Alt(ref i1, ref i2) => { + match **i1 { + Interaction::Alt(ref i11,ref i12) => { + new_int = Some(Interaction::Alt( i11.clone(), Box::new(Interaction::Alt(i12.clone(), i2.clone())) ) ); + }, + _ => {} + } + }, + &Interaction::Strict(ref i1, ref i2) => { + match **i1 { + Interaction::Strict(ref i11,ref i12) => { + new_int = Some(Interaction::Strict( i11.clone(), Box::new(Interaction::Strict(i12.clone(), i2.clone())) )); + }, + _ => {} + } + }, + &Interaction::Seq(ref i1, ref i2) => { + match **i1 { + Interaction::Seq(ref i11,ref i12) => { + new_int = Some(Interaction::Seq( i11.clone(), Box::new(Interaction::Seq(i12.clone(), i2.clone())) )); + }, + _ => {} + } + }, + &Interaction::Par(ref i1, ref i2) => { + match **i1 { + Interaction::Par(ref i11,ref i12) => { + new_int = Some(Interaction::Par( i11.clone(), Box::new(Interaction::Par(i12.clone(), i2.clone())) )); + }, + _ => {} + } + }, + &Interaction::CoReg(ref cr1, ref i1, ref i2) => { + match **i1 { + Interaction::CoReg(ref cr2, ref i11,ref i12) => { + if cr1 == cr2 { + new_int = Some(Interaction::CoReg( cr1.clone(), i11.clone(), Box::new(Interaction::CoReg(cr1.clone(), i12.clone(), i2.clone())) )); + } + }, + _ => {} + } + }, + _ => {} + } + match new_int { + None => { + return vec![]; + }, + Some(got_int) => { + if &got_int < interaction { + return vec![got_int]; + } else { + return vec![] + } + } + } +} + +/* +pub fn flush_left(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Alt(ref i1, ref i2) => { + match **i2 { + Interaction::Alt(ref i21,ref i22) => { + return vec![ Interaction::Alt( Box::new(Interaction::Alt(i1.clone(), i21.clone())), i22.clone() ) ]; + }, + _ => {} + } + }, + &Interaction::Strict(ref i1, ref i2) => { + match **i2 { + Interaction::Strict(ref i21,ref i22) => { + return vec![ Interaction::Strict( Box::new(Interaction::Strict(i1.clone(), i21.clone())), i22.clone() ) ]; + }, + _ => {} + } + }, + &Interaction::Seq(ref i1, ref i2) => { + match **i2 { + Interaction::Seq(ref i21,ref i22) => { + return vec![ Interaction::Seq( Box::new(Interaction::Seq(i1.clone(), i21.clone())), i22.clone() ) ]; + }, + _ => {} + } + }, + &Interaction::Par(ref i1, ref i2) => { + match **i2 { + Interaction::Par(ref i21,ref i22) => { + return vec![ Interaction::Par( Box::new(Interaction::Par(i1.clone(), i21.clone())), i22.clone() ) ]; + }, + _ => {} + } + }, + &Interaction::CoReg(ref cr1, ref i1, ref i2) => { + match **i2 { + Interaction::CoReg(ref cr2, ref i21,ref i22) => { + if cr1 == cr2 { + return vec![ Interaction::CoReg( cr1.clone(), Box::new(Interaction::CoReg(cr1.clone(), i1.clone(), i21.clone())), i22.clone() ) ]; + } + }, + _ => {} + } + }, + _ => {} + } + return vec![]; +}*/ \ No newline at end of file diff --git a/src/core/transformation/transfofunc/invert.rs b/src/core/transformation/transfofunc/invert.rs new file mode 100644 index 0000000..9f21bea --- /dev/null +++ b/src/core/transformation/transfofunc/invert.rs @@ -0,0 +1,79 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + + +use itertools::Itertools; +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::syntax::util::fold_recursive_frags::{fold_recursive_alt_frags, fold_recursive_par_frags}; +use crate::core::language::syntax::util::get_recursive_frag::{get_recursive_alt_frags, get_recursive_par_frags}; + +pub fn invert_alt_sorted(interaction : &Interaction) -> Vec { + let orig_alt_frags = get_recursive_alt_frags(interaction); + let mut sorted_alt_frags : Vec<&Interaction> = orig_alt_frags.iter().map(|x| *x).sorted().collect(); + if sorted_alt_frags != orig_alt_frags { + return vec![fold_recursive_alt_frags(&mut sorted_alt_frags)]; + } else { + return vec![]; + } +} + +pub fn invert_par_sorted(interaction : &Interaction) -> Vec { + let orig_par_frags = get_recursive_par_frags(interaction); + let mut sorted_par_frags : Vec<&Interaction> = orig_par_frags.iter().map(|x| *x).sorted().collect(); + if sorted_par_frags != orig_par_frags { + return vec![fold_recursive_par_frags(&mut sorted_par_frags)]; + } else { + return vec![]; + } +} + +/* +pub fn tri_invert_alt_conditional_right_flushed(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Alt(ref i1, ref i_right) => { + match **i_right { + Interaction::Alt(ref i2,ref i3) => { + if i2 < i1 { + return vec![ Interaction::Alt( i2.clone(), Box::new(Interaction::Alt(i1.clone(), i3.clone())) ) ]; + } + }, + _ => {} + } + }, + _ => {} + } + return vec![]; +} + +pub fn tri_invert_par_conditional_right_flushed(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Par(ref i1, ref i_right) => { + match **i_right { + Interaction::Par(ref i2,ref i3) => { + if i2 < i1 { + return vec![Interaction::Par(i2.clone(), Box::new(Interaction::Par(i1.clone(), i3.clone())))]; + } + }, + _ => {} + } + }, + _ => {} + } + return vec![]; +}*/ \ No newline at end of file diff --git a/src/core/transformation/transfofunc/loop_alt_simpl.rs b/src/core/transformation/transfofunc/loop_alt_simpl.rs new file mode 100644 index 0000000..2aa3eb1 --- /dev/null +++ b/src/core/transformation/transfofunc/loop_alt_simpl.rs @@ -0,0 +1,76 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use std::collections::HashSet; +use crate::core::language::syntax::interaction::{Interaction, LoopKind}; +use crate::core::language::syntax::util::fold_recursive_frags::{fold_recursive_par_frags, fold_recursive_seq_frags, fold_recursive_strict_frags}; +use crate::core::language::syntax::util::get_recursive_frag::{get_recursive_par_frags, get_recursive_seq_frags, get_recursive_strict_frags}; + + + + +fn simpl_alt_with_loop(looped_frag : &Interaction, + sched_frags : Vec<&Interaction>) -> bool { + let as_set : HashSet<&Interaction> = HashSet::from_iter(sched_frags.iter().cloned()); + if as_set.len() == 1 { + let got_int : &Interaction = as_set.into_iter().next().unwrap(); + if got_int == looped_frag { + return true; + } + if got_int == &Interaction::Empty { + return true; + } + } + return false; +} + + +pub fn loop_alt_simpl(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Alt(ref i1, ref i2) => { + match **i2 { + Interaction::Loop(ref lk, ref i21) => { + match lk { + LoopKind::PInterleaving => { + let frags = get_recursive_par_frags(i1); + if simpl_alt_with_loop(i21,frags) { + return vec![*i2.clone()]; + } + }, + LoopKind::WWeakSeq => { + let frags = get_recursive_seq_frags(i1); + if simpl_alt_with_loop(i21,frags) { + return vec![*i2.clone()]; + } + }, + LoopKind::SStrictSeq => { + let frags = get_recursive_strict_frags(i1); + if simpl_alt_with_loop(i21,frags) { + return vec![*i2.clone()]; + } + }, + _ => {} + } + }, + _ => {} + } + }, + _ => {} + } + return vec![]; +} diff --git a/src/core/transformation/transfofunc/loop_simpl.rs b/src/core/transformation/transfofunc/loop_simpl.rs new file mode 100644 index 0000000..123b8f5 --- /dev/null +++ b/src/core/transformation/transfofunc/loop_simpl.rs @@ -0,0 +1,160 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use crate::core::language::syntax::interaction::{Interaction, LoopKind}; +use crate::core::language::syntax::util::fold_recursive_frags::{fold_recursive_par_frags, fold_recursive_seq_frags, fold_recursive_strict_frags}; +use crate::core::language::syntax::util::get_recursive_frag::{get_recursive_par_frags, get_recursive_seq_frags, get_recursive_strict_frags}; + +pub fn loop_empty_simpl(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Loop(ref sk, ref i1) => { + match **i1 { + Interaction::Empty => { + return vec![Interaction::Empty]; + }, + _ => {} + } + }, + _ => {} + } + return vec![]; +} + + +pub fn loop_unnest(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Loop(ref lkA, ref i1) => { + match **i1 { + Interaction::Loop(ref lkB, ref i11) => { + return vec![Interaction::Loop((lkA.min(lkB)).clone(), i11.clone())]; + }, + _ => {} + } + }, + _ => {} + } + return vec![]; +} + +pub fn loop_factorize(interaction : &Interaction) -> Vec { + let mut got_ints = vec![]; + match interaction { + &Interaction::Strict(ref i1, ref i2) => { + match **i1 { + Interaction::Loop(ref lk, ref i11) => { + match lk { + LoopKind::SStrictSeq => { + if i2 == i11 { + got_ints.push(*i1.clone()); + } else if i2 == i1 { + got_ints.push(*i1.clone()); + } + }, + _ => {} + } + }, + _ => {} + } + match **i2 { + Interaction::Loop(ref lk, ref i21) => { + match lk { + LoopKind::SStrictSeq => { + if i1 == i21 { + got_ints.push(*i2.clone()); + } else if i1 == i2 { + got_ints.push(*i2.clone()); + } + }, + _ => {} + } + }, + _ => {} + } + }, + &Interaction::Seq(ref i1, ref i2) => { + match **i1 { + Interaction::Loop(ref lk, ref i11) => { + match lk { + LoopKind::WWeakSeq => { + if i2 == i11 { + got_ints.push(*i1.clone()); + } else if i2 == i1 { + got_ints.push(*i1.clone()); + } + }, + _ => {} + } + }, + _ => {} + } + match **i2 { + Interaction::Loop(ref lk, ref i21) => { + match lk { + LoopKind::WWeakSeq => { + if i1 == i21 { + got_ints.push(*i2.clone()); + } else if i1 == i2 { + got_ints.push(*i2.clone()); + } + }, + _ => {} + } + }, + _ => {} + } + }, + &Interaction::Par(ref i1, ref i2) => { + match **i1 { + Interaction::Loop(ref lk, ref i11) => { + match lk { + LoopKind::PInterleaving => { + if i2 == i11 { + got_ints.push(*i1.clone()); + } else if i2 == i1 { + got_ints.push(*i1.clone()); + } + }, + _ => {} + } + }, + _ => {} + } + match **i2 { + Interaction::Loop(ref lk, ref i21) => { + match lk { + LoopKind::PInterleaving => { + if i1 == i21 { + got_ints.push(*i2.clone()); + } else if i1 == i2 { + got_ints.push(*i2.clone()); + } + }, + _ => {} + } + }, + _ => {} + } + }, + _ => {} + } + return got_ints; +} + + + + diff --git a/src/core/transformation/transfofunc/merge_action.rs b/src/core/transformation/transfofunc/merge_action.rs new file mode 100644 index 0000000..8e0a02a --- /dev/null +++ b/src/core/transformation/transfofunc/merge_action.rs @@ -0,0 +1,86 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use crate::core::language::syntax::action::{EmissionAction, EmissionTargetRef, ReceptionAction}; +use crate::core::language::syntax::interaction::Interaction; + + +pub fn merge_action(interaction : &Interaction) -> Option { + match interaction { + Interaction::And(ref i1, ref i2) => { + match (&**i1,&**i2) { + (Interaction::Emission(ref em_act),Interaction::Reception(ref rc_act)) => { + return merge_action_inner(em_act,rc_act); + }, + (Interaction::Reception(ref rc_act),Interaction::Emission(ref em_act)) => { + return merge_action_inner(em_act,rc_act); + }, + _ => {} + } + }, + _ => {} + } + return None; +} + + +fn merge_action_inner(emission : &EmissionAction, + reception : &ReceptionAction) -> Option { + if emission.ms_id != reception.ms_id { + return None; + } + // *** + if emission.synchronicity != reception.synchronicity { + return None; + } + // *** + match &reception.origin_gt_id { + None => { + return None; + }, + Some( gt_id_to_match) => { + let mut is_match = false; + let mut targets = vec![]; + for target_ref in &emission.targets { + match target_ref { + EmissionTargetRef::Lifeline(lf_id) => { + targets.push(EmissionTargetRef::Lifeline(*lf_id)); + }, + EmissionTargetRef::Gate(gt_id) => { + if gt_id == gt_id_to_match { + is_match == true; + for recipient_lf in &reception.recipients { + targets.push(EmissionTargetRef::Lifeline(*recipient_lf)); + } + } else { + targets.push(EmissionTargetRef::Gate(*gt_id)); + } + } + } + } + // *** + if is_match { + let new_action = EmissionAction::new(emission.origin_lf_id,emission.ms_id,emission.synchronicity.clone(),targets); + return Some(Interaction::Emission(new_action)); + } else { + return None; + } + } + } +} + diff --git a/src/core/transformation/transfofunc/merge_shift_left.rs b/src/core/transformation/transfofunc/merge_shift_left.rs new file mode 100644 index 0000000..4145b15 --- /dev/null +++ b/src/core/transformation/transfofunc/merge_shift_left.rs @@ -0,0 +1,91 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::core::language::syntax::interaction::Interaction; + +pub fn merge_shift_left_1(interaction : &Interaction) -> Option { + match interaction { + &Interaction::And(ref i1, ref i2) => { + match **i1 { + Interaction::Strict(ref i11, ref i12) => { + let new_left = Interaction::And( i11.clone(), i2.clone() ); + return Some(Interaction::Strict(Box::new(new_left), i12.clone() )); + }, + Interaction::Seq(ref i11, ref i12) => { + let new_left = Interaction::And( i11.clone(), i2.clone() ); + return Some(Interaction::Seq(Box::new(new_left), i12.clone() )); + }, + Interaction::CoReg(ref cr, ref i11, ref i12) => { + let new_left = Interaction::And( i11.clone(), i2.clone() ); + return Some(Interaction::CoReg(cr.clone(),Box::new(new_left), i12.clone() )); + }, + Interaction::Par(ref i11, ref i12) => { + let new_left = Interaction::And( i11.clone(), i2.clone() ); + return Some(Interaction::Par(Box::new(new_left), i12.clone() )); + }, + Interaction::Alt(ref i11, ref i12) => { + let new_left = Interaction::And( i11.clone(), i2.clone() ); + return Some(Interaction::Alt(Box::new(new_left), i12.clone() )); + }, + Interaction::Loop(ref lk, ref i11) => { + let new_sub = Interaction::And( i11.clone(), i2.clone() ); + return Some(Interaction::Loop(lk.clone(), Box::new(new_sub) )); + }, + _ => {} + } + }, + _ => {} + } + return None; +} + + + +pub fn merge_shift_left_2(interaction : &Interaction) -> Option { + match interaction { + &Interaction::And(ref i1, ref i2) => { + match **i1 { + Interaction::Strict(ref i11, ref i12) => { + let new_right = Interaction::And( i12.clone(), i2.clone() ); + return Some(Interaction::Strict( i11.clone(), Box::new(new_right) )); + }, + Interaction::Seq(ref i11, ref i12) => { + let new_right = Interaction::And( i12.clone(), i2.clone() ); + return Some(Interaction::Seq( i11.clone(), Box::new(new_right) )); + }, + Interaction::CoReg(ref cr, ref i11, ref i12) => { + let new_right = Interaction::And( i12.clone(), i2.clone() ); + return Some(Interaction::CoReg( cr.clone(),i11.clone(), Box::new(new_right) )); + }, + Interaction::Par(ref i11, ref i12) => { + let new_right = Interaction::And( i12.clone(), i2.clone() ); + return Some(Interaction::Par( i11.clone(), Box::new(new_right) )); + }, + Interaction::Alt(ref i11, ref i12) => { + let new_right = Interaction::And( i12.clone(), i2.clone() ); + return Some(Interaction::Alt( i11.clone(), Box::new(new_right) )); + }, + _ => {} + } + }, + _ => {} + } + return None; +} + + + diff --git a/src/core/transformation/transfofunc/merge_shift_right.rs b/src/core/transformation/transfofunc/merge_shift_right.rs new file mode 100644 index 0000000..a18d2c4 --- /dev/null +++ b/src/core/transformation/transfofunc/merge_shift_right.rs @@ -0,0 +1,91 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::core::language::syntax::interaction::Interaction; + +pub fn merge_shift_right_1(interaction : &Interaction) -> Option { + match interaction { + &Interaction::And(ref i1, ref i2) => { + match **i2 { + Interaction::Strict(ref i21, ref i22) => { + let new_left = Interaction::And( i1.clone(), i21.clone() ); + return Some(Interaction::Strict(Box::new(new_left), i22.clone() )); + }, + Interaction::Seq(ref i21, ref i22) => { + let new_left = Interaction::And( i1.clone(), i21.clone() ); + return Some(Interaction::Seq(Box::new(new_left), i22.clone() )); + }, + Interaction::CoReg(ref cr, ref i21, ref i22) => { + let new_left = Interaction::And( i1.clone(), i21.clone() ); + return Some(Interaction::CoReg(cr.clone(),Box::new(new_left), i22.clone() )); + }, + Interaction::Par(ref i21, ref i22) => { + let new_left = Interaction::And( i1.clone(), i21.clone() ); + return Some(Interaction::Par(Box::new(new_left), i22.clone() )); + }, + Interaction::Alt(ref i21, ref i22) => { + let new_left = Interaction::And( i1.clone(), i21.clone() ); + return Some(Interaction::Alt(Box::new(new_left), i22.clone() )); + }, + Interaction::Loop(ref lk, ref i21) => { + let new_sub = Interaction::And( i1.clone(), i21.clone() ); + return Some(Interaction::Loop(lk.clone(), Box::new(new_sub) )); + }, + _ => {} + } + }, + _ => {} + } + return None; +} + + + +pub fn merge_shift_right_2(interaction : &Interaction) -> Option { + match interaction { + &Interaction::And(ref i1, ref i2) => { + match **i2 { + Interaction::Strict(ref i21, ref i22) => { + let new_right = Interaction::And( i1.clone(), i22.clone() ); + return Some(Interaction::Strict( i21.clone(), Box::new(new_right) )); + }, + Interaction::Seq(ref i21, ref i22) => { + let new_right = Interaction::And( i1.clone(), i22.clone() ); + return Some(Interaction::Seq( i21.clone(), Box::new(new_right) )); + }, + Interaction::CoReg(ref cr, ref i21, ref i22) => { + let new_right = Interaction::And( i1.clone(), i22.clone() ); + return Some(Interaction::CoReg( cr.clone(),i21.clone(), Box::new(new_right) )); + }, + Interaction::Par(ref i21, ref i22) => { + let new_right = Interaction::And( i1.clone(), i22.clone() ); + return Some(Interaction::Par( i21.clone(), Box::new(new_right) )); + }, + Interaction::Alt(ref i21, ref i22) => { + let new_right = Interaction::And( i1.clone(), i22.clone() ); + return Some(Interaction::Alt( i21.clone(), Box::new(new_right) )); + }, + _ => {} + } + }, + _ => {} + } + return None; +} + + + diff --git a/src/core/transformation/transfofunc/merge_skip.rs b/src/core/transformation/transfofunc/merge_skip.rs new file mode 100644 index 0000000..556f2a3 --- /dev/null +++ b/src/core/transformation/transfofunc/merge_skip.rs @@ -0,0 +1,57 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::core::language::syntax::interaction::Interaction; + +pub fn merge_skip(interaction : &Interaction) -> Option { + match interaction { + &Interaction::And(ref i1, ref i2) => { + match (&**i1,&**i2) { + (Interaction::Strict(ref i11, ref i12),Interaction::Strict(ref i21, ref i22)) => { + let new_left = Interaction::And( i11.clone(), i21.clone() ); + let new_right = Interaction::And( i12.clone(), i22.clone() ); + return Some(Interaction::Strict(Box::new(new_left), Box::new(new_right) )); + }, + (Interaction::Seq(ref i11, ref i12),Interaction::Seq(ref i21, ref i22)) => { + let new_left = Interaction::And( i11.clone(), i21.clone() ); + let new_right = Interaction::And( i12.clone(), i22.clone() ); + return Some(Interaction::Seq(Box::new(new_left), Box::new(new_right) )); + }, + (Interaction::CoReg(ref cr1, ref i11, ref i12),Interaction::CoReg(ref cr2,ref i21, ref i22)) => { + if cr1 == cr2 { + let new_left = Interaction::And( i11.clone(), i21.clone() ); + let new_right = Interaction::And( i12.clone(), i22.clone() ); + return Some(Interaction::CoReg(cr1.clone(), Box::new(new_left), Box::new(new_right) )); + } + }, + (Interaction::Par(ref i11, ref i12),Interaction::Par(ref i21, ref i22)) => { + let new_left = Interaction::And( i11.clone(), i21.clone() ); + let new_right = Interaction::And( i12.clone(), i22.clone() ); + return Some(Interaction::Par(Box::new(new_left), Box::new(new_right) )); + }, + (Interaction::Alt(ref i11, ref i12),Interaction::Alt(ref i21, ref i22)) => { + let new_left = Interaction::And( i11.clone(), i21.clone() ); + let new_right = Interaction::And( i12.clone(), i22.clone() ); + return Some(Interaction::Alt(Box::new(new_left), Box::new(new_right) )); + }, + _ => {} + } + }, + _ => {} + } + return None; +} \ No newline at end of file diff --git a/src/core/transformation/transfofunc/merge_skip_invert.rs b/src/core/transformation/transfofunc/merge_skip_invert.rs new file mode 100644 index 0000000..fd9c4fd --- /dev/null +++ b/src/core/transformation/transfofunc/merge_skip_invert.rs @@ -0,0 +1,40 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::core::language::syntax::interaction::Interaction; + +pub fn merge_skip_invert(interaction : &Interaction) -> Option { + match interaction { + &Interaction::And(ref i1, ref i2) => { + match (&**i1,&**i2) { + (Interaction::Par(ref i11, ref i12),Interaction::Par(ref i21, ref i22)) => { + let new_left = Interaction::And( i11.clone(), i22.clone() ); + let new_right = Interaction::And( i12.clone(), i21.clone() ); + return Some(Interaction::Par(Box::new(new_left), Box::new(new_right) )); + }, + (Interaction::Alt(ref i11, ref i12),Interaction::Alt(ref i21, ref i22)) => { + let new_left = Interaction::And( i11.clone(), i22.clone() ); + let new_right = Interaction::And( i12.clone(), i21.clone() ); + return Some(Interaction::Alt(Box::new(new_left), Box::new(new_right) )); + }, + _ => {} + } + }, + _ => {} + } + return None; +} \ No newline at end of file diff --git a/src/canonize/mod.rs b/src/core/transformation/transfofunc/mod.rs similarity index 63% rename from src/canonize/mod.rs rename to src/core/transformation/transfofunc/mod.rs index 50399c0..1f4302e 100644 --- a/src/canonize/mod.rs +++ b/src/core/transformation/transfofunc/mod.rs @@ -14,10 +14,19 @@ See the License for the specific language governing permissions and limitations under the License. */ -mod action_repr; -mod term_repr; -pub mod term_repr_out; -mod transformations; -pub mod process; -mod total_order; - +pub mod action; +pub mod dedupl; +pub mod defactorize; +pub mod factorize_par; +pub mod factorize_prefix; +pub mod factorize_suffix; +pub mod flush; +pub mod invert; +pub mod loop_alt_simpl; +pub mod loop_simpl; +pub mod merge_action; +pub mod merge_skip; +pub mod merge_skip_invert; +pub mod merge_shift_left; +pub mod merge_shift_right; +pub mod simpl; diff --git a/src/core/transformation/transfofunc/simpl.rs b/src/core/transformation/transfofunc/simpl.rs new file mode 100644 index 0000000..ecedbc3 --- /dev/null +++ b/src/core/transformation/transfofunc/simpl.rs @@ -0,0 +1,77 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + + +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::syntax::util::fold_recursive_frags::{fold_recursive_coreg_frags, fold_recursive_par_frags, fold_recursive_seq_frags, fold_recursive_strict_frags}; +use crate::core::language::syntax::util::get_recursive_frag::{get_recursive_coreg_frags, get_recursive_par_frags, get_recursive_seq_frags, get_recursive_strict_frags}; + + +pub fn simpl(interaction : &Interaction) -> Vec { + match interaction { + &Interaction::Strict(ref i1, ref i2) => { + let mut old_frags = get_recursive_strict_frags(i1); + old_frags.extend(get_recursive_strict_frags(i2)); + // *** + let old_len = old_frags.len(); + // *** + let mut new_frags : Vec<&Interaction> = old_frags.into_iter().filter(|x| *x != &Interaction::Empty).collect(); + if new_frags.len() < old_len { + return vec![fold_recursive_strict_frags(&mut new_frags)]; + } + }, + &Interaction::Seq(ref i1, ref i2) => { + let mut old_frags = get_recursive_seq_frags(i1); + old_frags.extend(get_recursive_seq_frags(i2)); + // *** + let old_len = old_frags.len(); + // *** + let mut new_frags : Vec<&Interaction> = old_frags.into_iter().filter(|x| *x != &Interaction::Empty).collect(); + if new_frags.len() < old_len { + return vec![fold_recursive_seq_frags(&mut new_frags)]; + } + }, + &Interaction::Par(ref i1, ref i2) => { + let mut old_frags = get_recursive_par_frags(i1); + old_frags.extend(get_recursive_par_frags(i2)); + // *** + let old_len = old_frags.len(); + // *** + let mut new_frags : Vec<&Interaction> = old_frags.into_iter().filter(|x| *x != &Interaction::Empty).collect(); + if new_frags.len() < old_len { + return vec![fold_recursive_par_frags(&mut new_frags)]; + } + }, + &Interaction::CoReg(ref cr, ref i1, ref i2) => { + let mut old_frags = get_recursive_coreg_frags(cr,i1); + old_frags.extend(get_recursive_coreg_frags(cr,i2)); + // *** + let old_len = old_frags.len(); + // *** + let mut new_frags : Vec<&Interaction> = old_frags.into_iter().filter(|x| *x != &Interaction::Empty).collect(); + if new_frags.len() < old_len { + return vec![fold_recursive_coreg_frags(cr,&mut new_frags)]; + } + }, + _ => {} + } + return vec![]; +} + + diff --git a/src/core/transformation/transfokind.rs b/src/core/transformation/transfokind.rs new file mode 100644 index 0000000..db5068e --- /dev/null +++ b/src/core/transformation/transfokind.rs @@ -0,0 +1,126 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +#[derive(Clone, PartialEq, Debug, Eq, Hash)] +pub enum InteractionTransformationKind { + Simpl, + FlushLeft, + FlushRight, + InvertAlt, + InvertPar, + Deduplicate, + FactorizePrefixStrict, + FactorizePrefixSeq, + FactorizeSuffixStrict, + FactorizeSuffixSeq, + FactorizeCommutativePar, + DeFactorizeLeft, + DeFactorizeRight, + LoopSimpl, + LoopAltSimpl, + LoopUnNest, + SortActionContent, // sort emission targets OR reception recipients + // *** + MergeShiftLeft1, + MergeShiftLeft2, + MergeShiftRight1, + MergeShiftRight2, + MergeAction, + MergeSkip, + MergeSkipInvert, +} + + +impl InteractionTransformationKind { + pub fn to_string(&self) -> String { + match self { + &InteractionTransformationKind::Simpl => { + return "Simpl".to_string(); + }, + &InteractionTransformationKind::FlushLeft => { + return "FlushLeft".to_string(); + }, + &InteractionTransformationKind::FlushRight => { + return "FlushRight".to_string(); + }, + &InteractionTransformationKind::InvertAlt => { + return "InvertAlt".to_string(); + }, + &InteractionTransformationKind::InvertPar => { + return "InvertPar".to_string(); + }, + &InteractionTransformationKind::Deduplicate => { + return "Deduplicate".to_string(); + }, + &InteractionTransformationKind::FactorizePrefixStrict => { + return "FactorizePrefixStrict".to_string(); + }, + &InteractionTransformationKind::FactorizePrefixSeq => { + return "FactorizePrefixSeq".to_string(); + }, + &InteractionTransformationKind::FactorizeSuffixStrict => { + return "FactorizeSuffixStrict".to_string(); + }, + &InteractionTransformationKind::FactorizeSuffixSeq => { + return "FactorizeSuffixSeq".to_string(); + }, + &InteractionTransformationKind::FactorizeCommutativePar => { + return "FactorizeCommutativePar".to_string(); + }, + &InteractionTransformationKind::DeFactorizeLeft => { + return "DeFactorizeLeft".to_string(); + }, + &InteractionTransformationKind::DeFactorizeRight => { + return "DeFactorizeRight".to_string(); + }, + &InteractionTransformationKind::LoopSimpl => { + return "LoopSimpl".to_string(); + }, + &InteractionTransformationKind::LoopAltSimpl => { + return "LoopAltSimpl".to_string(); + }, + &InteractionTransformationKind::LoopUnNest => { + return "LoopUnNest".to_string(); + }, + &InteractionTransformationKind::SortActionContent => { + return "SortActionContent".to_string(); + }, + &InteractionTransformationKind::MergeShiftLeft1 => { + return "MergeShiftLeft1".to_string(); + }, + &InteractionTransformationKind::MergeShiftRight1 => { + return "MergeShiftRight1".to_string(); + }, + &InteractionTransformationKind::MergeShiftLeft2 => { + return "MergeShiftLeft2".to_string(); + }, + &InteractionTransformationKind::MergeShiftRight2 => { + return "MergeShiftRight2".to_string(); + }, + &InteractionTransformationKind::MergeAction => { + return "MergeAction".to_string(); + }, + &InteractionTransformationKind::MergeSkip => { + return "MergeSkip".to_string(); + }, + &InteractionTransformationKind::MergeSkipInvert => { + return "MergeSkipInvert".to_string(); + } + } + } +} + diff --git a/src/input/hcf/proc_options/loggers.rs b/src/input/hcf/proc_options/loggers.rs deleted file mode 100644 index cc532a3..0000000 --- a/src/input/hcf/proc_options/loggers.rs +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -use std::collections::HashSet; - -use pest::iterators::Pair; -use crate::core::colocalizations::CoLocalizations; - -use crate::core::general_context::GeneralContext; -use crate::input::error::HibouParsingError; - - -use crate::loggers::graphic::conf::{GraphicProcessLoggerInteractionRepresentation, GraphicProcessLoggerLayout, GraphicProcessLoggerOutputKind}; -use crate::loggers::graphic::graphic_logger::GraphicProcessLogger; -use crate::loggers::tracegen::conf::TracegenProcessLoggerGeneration; -use crate::loggers::tracegen::tracegen_logger::TraceGenProcessLogger; - - -#[allow(unused_imports)] -use crate::pest::Parser; -#[allow(unused_imports)] -use crate::input::hcf::parser::{HcfParser,Rule}; - - -pub fn parse_graphic_logger(file_name : &str, logger_kind_pair : Pair) -> GraphicProcessLogger { - let graphic_logger : GraphicProcessLogger; - // *** - let graphic_logger_opts_pair = logger_kind_pair.into_inner().next(); - match graphic_logger_opts_pair { - None => { - graphic_logger = GraphicProcessLogger::new(file_name.to_string(), - GraphicProcessLoggerOutputKind::png, - GraphicProcessLoggerLayout::vertical, - GraphicProcessLoggerInteractionRepresentation::diagram ); - }, - Some(graphic_logger_opts) => { - let mut output_kind = GraphicProcessLoggerOutputKind::png; - let mut layout_kind = GraphicProcessLoggerLayout::vertical; - for opt_pair in graphic_logger_opts.into_inner() { - match opt_pair.as_rule() { - Rule::GRAPHIC_LOGGER_png => { - output_kind = GraphicProcessLoggerOutputKind::png; - }, - Rule::GRAPHIC_LOGGER_svg => { - output_kind = GraphicProcessLoggerOutputKind::svg; - }, - Rule::GRAPHIC_LOGGER_vertical => { - layout_kind = GraphicProcessLoggerLayout::vertical; - }, - Rule::GRAPHIC_LOGGER_horizontal => { - layout_kind = GraphicProcessLoggerLayout::horizontal; - }, - _ => { - panic!("what rule then ? : {:?}", opt_pair.as_rule()); - } - } - } - graphic_logger = GraphicProcessLogger::new(file_name.to_string(), - output_kind, - layout_kind, - GraphicProcessLoggerInteractionRepresentation::diagram); - } - } - // *** - return graphic_logger; -} - - - -pub fn parse_tracegen_logger(gen_ctx : &GeneralContext, - file_name : &str, - logger_kind_pair : Pair) -> Result { - let tracegen_logger : TraceGenProcessLogger; - // *** - let tracegen_logger_opts_pair = logger_kind_pair.into_inner().next(); - match tracegen_logger_opts_pair { - None => { - tracegen_logger = TraceGenProcessLogger::new(file_name.to_string(), - TracegenProcessLoggerGeneration::exact, - CoLocalizations::get_trivial_partition(gen_ctx.get_lf_num())); - }, - Some(tracegen_logger_opts) => { - let mut generation = TracegenProcessLoggerGeneration::exact; - let mut co_localizations = CoLocalizations::get_trivial_partition(gen_ctx.get_lf_num()); - for opt_pair in tracegen_logger_opts.into_inner() { - match opt_pair.as_rule() { - Rule::TRACEGEN_LOGGER_terminal => { - generation = TracegenProcessLoggerGeneration::terminal; - }, - Rule::TRACEGEN_LOGGER_exact => { - generation = TracegenProcessLoggerGeneration::exact; - }, - Rule::TRACEGEN_LOGGER_prefix => { - generation = TracegenProcessLoggerGeneration::prefixes; - }, - Rule::TRACEGEN_LOGGER_partition_discrete => { - co_localizations = CoLocalizations::get_discrete_partition(gen_ctx.get_lf_num()); - }, - Rule::TRACEGEN_LOGGER_partition_trivial => { - co_localizations = CoLocalizations::get_trivial_partition(gen_ctx.get_lf_num()); - }, - Rule::TRACEGEN_LOGGER_partition_specific => { - let mut colocs : Vec> = vec![]; - // *** - let mut got_lfs = hashset!{}; - // *** - for lfs_list_pair in opt_pair.into_inner() { - let mut coloc = hashset!{}; - for lf_name_pair in lfs_list_pair.into_inner() { - let lf_name : String = lf_name_pair.as_str().chars().filter(|c| !c.is_whitespace()).collect(); - match gen_ctx.get_lf_id(&lf_name) { - None => { - return Err( HibouParsingError::MissingLifelineDeclarationError(lf_name) ); - }, - Some(lf_id) => { - if got_lfs.contains(&lf_id) { - return Err( HibouParsingError::NonDisjointTraceComponents ); - } - got_lfs.insert(lf_id); - coloc.insert(lf_id); - } - } - } - colocs.push(coloc); - } - // *** - co_localizations = CoLocalizations::new(colocs); - }, - _ => { - panic!("what rule then ? : {:?}", opt_pair.as_rule()); - } - } - } - tracegen_logger = TraceGenProcessLogger::new(file_name.to_string(), - generation, - co_localizations); - } - } - // *** - return Ok( tracegen_logger ); -} - diff --git a/src/output/commons/file_extensions.rs b/src/io/file_extensions.rs similarity index 100% rename from src/output/commons/file_extensions.rs rename to src/io/file_extensions.rs diff --git a/src/input/error.rs b/src/io/input/error.rs similarity index 80% rename from src/input/error.rs rename to src/io/input/error.rs index 6c0c5b8..84e9208 100644 --- a/src/input/error.rs +++ b/src/io/input/error.rs @@ -22,16 +22,22 @@ pub enum HibouParsingError { FileFormatError(String,String), FileError(String), MatchError(String), + // *** + HsfSetupError(String), + HcfSetupError(String), + ProcessFilterError(String), + ProcessPriorityError(String), + // *** MissingMessageDeclarationError(String), MissingLifelineDeclarationError(String), + MissingGateDeclarationError(String), MissingLifelineOrGateDeclarationError(String), - WrongGateUsage(String), + // *** EmissionDefinitionError(String), OtherDefinitionError(String), + // *** NonDisjointTraceComponents, - IllDefinedTraceComponents(String), - HsfSetupError(String), - ProcessPriorityError(String) + IllDefinedTraceComponents(String) } impl fmt::Display for HibouParsingError { @@ -46,35 +52,45 @@ impl fmt::Display for HibouParsingError { HibouParsingError::MatchError(sub_e) => { return write!(f, "{}", format!("error while parsing SD string : {:}", sub_e)); }, + // *** + HibouParsingError::HsfSetupError(sub_e) => { + return write!(f, "{}", format!("error while parsing setup section of .hsf file : {:}", sub_e)); + }, + HibouParsingError::HcfSetupError(sub_e) => { + return write!(f, "{}", format!("error while parsing setup section of .hcf file : {:}", sub_e)); + }, + HibouParsingError::ProcessFilterError(sub_e) => { + return write!(f, "{}", format!("error while parsing filters in .hcf file : {:}", sub_e)); + }, + HibouParsingError::ProcessPriorityError(sub_e) => { + return write!(f, "{}", format!("error while parsing priorities in .hcf file : {:}", sub_e)); + }, + // *** HibouParsingError::MissingMessageDeclarationError(sub_e) => { return write!(f, "{}", format!("error while parsing ; missing message declaration : {:}", sub_e)); }, HibouParsingError::MissingLifelineDeclarationError(sub_e) => { return write!(f, "{}", format!("error while parsing ; missing lifeline declaration : {:}", sub_e)); }, + HibouParsingError::MissingGateDeclarationError(sub_e) => { + return write!(f, "{}", format!("error while parsing ; missing gate declaration : {:}", sub_e)); + }, HibouParsingError::MissingLifelineOrGateDeclarationError(sub_e) => { return write!(f, "{}", format!("error while parsing ; missing lifeline or gate declaration : {:}", sub_e)); }, - HibouParsingError::WrongGateUsage(sub_e) => { - return write!(f, "{}", format!("error while parsing ; wrong gate usage : {:}", sub_e)); - }, + // *** HibouParsingError::EmissionDefinitionError(sub_e) => { return write!(f, "{}", format!("error while parsing ; emission definition error : {:}", sub_e)); }, HibouParsingError::OtherDefinitionError(sub_e) => { return write!(f, "{}", format!("error while parsing ; other definition error : {:}", sub_e)); }, + // *** HibouParsingError::NonDisjointTraceComponents => { return write!(f, "{}", format!("error while parsing ; non disjoint trace canals")); }, HibouParsingError::IllDefinedTraceComponents(sub_e) => { return write!(f, "{}", format!("error while parsing ; ill defined trace canals : {:}", sub_e)); - }, - HibouParsingError::HsfSetupError(sub_e) => { - return write!(f, "{}", format!("error while parsing setup section of .hsf file : {:}", sub_e)); - }, - HibouParsingError::ProcessPriorityError(sub_e) => { - return write!(f, "{}", format!("error while parsing priorities in .hsf file : {:}", sub_e)); } } } diff --git a/src/input/hcf/hcf_syntax.pest b/src/io/input/hcf/hcf_syntax.pest similarity index 69% rename from src/input/hcf/hcf_syntax.pest rename to src/io/input/hcf/hcf_syntax.pest index bea993e..df1227b 100644 --- a/src/input/hcf/hcf_syntax.pest +++ b/src/io/input/hcf/hcf_syntax.pest @@ -21,26 +21,66 @@ COMMENT = _{ "/*" ~ (!"*/" ~ ANY)* ~ "*/" } HIBOU_LABEL = @{ LETTER ~ (LETTER | ASCII_DIGIT | "_")* } HIBOU_LABEL_LIST = { "(" ~ HIBOU_LABEL ~ ("," ~ HIBOU_LABEL)* ~ ")" } -// ***** hibou options -GRAPHIC_LOGGER_png = { "png" } -GRAPHIC_LOGGER_svg = { "svg" } -GRAPHIC_LOGGER_horizontal = { "horizontal" } -GRAPHIC_LOGGER_vertical = { "vertical" } -GRAPHIC_LOGGER_opt = _{ GRAPHIC_LOGGER_png | GRAPHIC_LOGGER_svg | GRAPHIC_LOGGER_horizontal | GRAPHIC_LOGGER_vertical } +HIBOU_true = { "⊤" | "true" | "True" | "TRUE" } +HIBOU_false = { "⊥" | "false" | "False" | "FALSE" } + + +// *** + + +GRAPHIC_LOGGER_format_png = { "png" } +GRAPHIC_LOGGER_format_svg = { "svg" } +GRAPHIC_LOGGER_format = _{ ("format" ~ "=")? ~ (GRAPHIC_LOGGER_format_png | GRAPHIC_LOGGER_format_svg) } + +GRAPHIC_LOGGER_layout_horizontal = { "horizontal" } +GRAPHIC_LOGGER_layout_vertical = { "vertical" } +GRAPHIC_LOGGER_layout = _{ ("layout" ~ "=")? ~ (GRAPHIC_LOGGER_layout_horizontal | GRAPHIC_LOGGER_layout_vertical) } + +GRAPHIC_LOGGER_draw_sequence_diagram = { "draw_sd" ~ "=" ~ (HIBOU_true | HIBOU_false) } +GRAPHIC_LOGGER_draw_term_tree = { "draw_tt" ~ "=" ~ (HIBOU_true | HIBOU_false) } + +GRAPHIC_LOGGER_parent_folder = { ("parent"|"parent_folder"|"folder") ~ "=" ~ HIBOU_LABEL } +GRAPHIC_LOGGER_output_file = { ("output"|"name") ~ "=" ~ HIBOU_LABEL } + +GRAPHIC_LOGGER_opt = _{ GRAPHIC_LOGGER_format + | GRAPHIC_LOGGER_layout + | GRAPHIC_LOGGER_draw_sequence_diagram + | GRAPHIC_LOGGER_draw_term_tree + | GRAPHIC_LOGGER_parent_folder + | GRAPHIC_LOGGER_output_file } + GRAPHIC_LOGGER_opts = { "[" ~ GRAPHIC_LOGGER_opt ~ ("," ~ GRAPHIC_LOGGER_opt)* ~ "]" } OPTION_GRAPHIC_LOGGER = { "graphic" ~ GRAPHIC_LOGGER_opts? } + + // *** + + TRACEGEN_LOGGER_terminal = { "terminal" } TRACEGEN_LOGGER_exact = { "exact" } TRACEGEN_LOGGER_prefix = { "prefix" } +TRACEGEN_LOGGER_gen_kind = _{ "generation" ~ "=" ~ ( TRACEGEN_LOGGER_terminal | TRACEGEN_LOGGER_exact | TRACEGEN_LOGGER_prefix ) } + TRACEGEN_LOGGER_partition_discrete = { "discrete" } TRACEGEN_LOGGER_partition_trivial = { "trivial" } TRACEGEN_LOGGER_partition_specific = { "{" ~ HIBOU_LABEL_LIST ~ ("," ~ HIBOU_LABEL_LIST)* ~ "}" } TRACEGEN_LOGGER_partition = _{ "partition" ~ "=" ~ (TRACEGEN_LOGGER_partition_discrete | TRACEGEN_LOGGER_partition_trivial | TRACEGEN_LOGGER_partition_specific) } -TRACEGEN_LOGGER_opt = _{ TRACEGEN_LOGGER_exact | TRACEGEN_LOGGER_prefix | TRACEGEN_LOGGER_terminal | TRACEGEN_LOGGER_partition } + +TRACEGEN_LOGGER_parent_folder = { ("parent"|"parent_folder"|"folder") ~ "=" ~ HIBOU_LABEL } +TRACEGEN_LOGGER_trace_prefix = { ("name_prefix"|"trace_prefix"|"prefix") ~ "=" ~ HIBOU_LABEL } + +TRACEGEN_LOGGER_opt = _{ TRACEGEN_LOGGER_gen_kind + | TRACEGEN_LOGGER_partition + | TRACEGEN_LOGGER_parent_folder + | TRACEGEN_LOGGER_trace_prefix } + TRACEGEN_LOGGER_opts = { "[" ~ TRACEGEN_LOGGER_opt ~ ("," ~ TRACEGEN_LOGGER_opt)* ~ "]" } OPTION_TRACEGEN_LOGGER = { "tracegen" ~ TRACEGEN_LOGGER_opts? } + + // *** + + OPTION_LOGGER_KIND = _{ OPTION_GRAPHIC_LOGGER | OPTION_TRACEGEN_LOGGER } OPTION_LOGGER_DECL = { "loggers" ~ "=" ~ "[" ~ OPTION_LOGGER_KIND ~ ("," ~ OPTION_LOGGER_KIND)* ~ "]" } // *********************************************** @@ -49,17 +89,30 @@ ARITH_INTEGER = { "0" | (ASCII_NONZERO_DIGIT ~ ASCII_DIGIT*) } OPTION_PRIORITY_emission = { "emission" } OPTION_PRIORITY_reception = { "reception" } OPTION_PRIORITY_loop = { "loop" } +OPTION_PRIORITY_multi_rdv = { "multi_rdv" } +// *** OPTION_PRIORITY_hide = { "hide" } OPTION_PRIORITY_simu = { "simu" } -OPTION_PRIORITY_multi_rdv = { "multi_rdv" } -OPTION_PRIORITY_step = { "step" } +// *** +OPTION_PRIORITY_simpl = { "simpl" } +OPTION_PRIORITY_flush = { "flush" } +OPTION_PRIORITY_invert = { "invert" } +OPTION_PRIORITY_deduplicate = { "deduplicate" } +OPTION_PRIORITY_factorize = { "factorize" } +OPTION_PRIORITY_defactorize = { "defactorize" } +// *** OPTION_PRIORITY_KIND = _{ OPTION_PRIORITY_emission | OPTION_PRIORITY_reception | OPTION_PRIORITY_loop - | OPTION_PRIORITY_step | OPTION_PRIORITY_multi_rdv | OPTION_PRIORITY_hide - | OPTION_PRIORITY_simu } + | OPTION_PRIORITY_simu + | OPTION_PRIORITY_simpl + | OPTION_PRIORITY_flush + | OPTION_PRIORITY_invert + | OPTION_PRIORITY_deduplicate + | OPTION_PRIORITY_factorize + | OPTION_PRIORITY_defactorize } OPTION_PRIORITY_LEVEL = { ARITH_INTEGER | ("-" ~ ARITH_INTEGER ) } OPTION_PRIORITY_SPECIFIC_elt = { OPTION_PRIORITY_KIND ~ "=" ~ OPTION_PRIORITY_LEVEL } OPTION_PRIORITY_SPECIFIC = { "[" ~ OPTION_PRIORITY_SPECIFIC_elt ~ ("," ~ OPTION_PRIORITY_SPECIFIC_elt)* ~ "]" } @@ -87,9 +140,14 @@ GENERAL_OPTION_DECL = _{ OPTION_LOGGER_DECL // *********************************************** EXPLORE_OPTION_DECL = _{ GENERAL_OPTION_DECL } EXPLORE_OPTION_SECTION = { "@explore_option" ~ "{" ~ - EXPLORE_OPTION_DECL ~ (";" ~ EXPLORE_OPTION_DECL)* + EXPLORE_OPTION_DECL ~ (";" ~ EXPLORE_OPTION_DECL)* ~ (";")? ~ "}"} + + + // *********************************************** + + OPTION_ANA_KIND_accept = { "accept" } OPTION_ANA_KIND_prefix = { "prefix" } OPTION_ANA_KIND_hide = { "hide" } @@ -126,9 +184,9 @@ OPTION_GOAL_none = { "None" } OPTION_GOAL_KIND = _{ OPTION_GOAL_pass | OPTION_GOAL_weakpass | OPTION_GOAL_none } OPTION_GOAL_DECL = { "goal" ~ "=" ~ OPTION_GOAL_KIND } // *********************************************** -OPTION_LOCANA_yes = { "local_analysis" ~ "=" ~ "true" } +OPTION_LOCANA_yes = { "local_analysis" ~ "=" ~ HIBOU_true } OPTION_LOCANA_onlyfront = { "local_analysis" ~ "=" ~ ("front" | "onlyfront" | "only" ~"front") } -OPTION_LOCANA_no = { "local_analysis" ~ "=" ~ "false" } +OPTION_LOCANA_no = { "local_analysis" ~ "=" ~ HIBOU_false } OPTION_LOCANA = _{ OPTION_LOCANA_yes | OPTION_LOCANA_no } // *********************************************** ANALYZE_OPTION_DECL = _{ GENERAL_OPTION_DECL @@ -136,14 +194,29 @@ ANALYZE_OPTION_DECL = _{ GENERAL_OPTION_DECL | OPTION_GOAL_DECL | OPTION_LOCANA } ANALYZE_OPTION_SECTION = { "@analyze_option" ~ "{" ~ - ANALYZE_OPTION_DECL ~ (";" ~ ANALYZE_OPTION_DECL)* + ANALYZE_OPTION_DECL ~ (";" ~ ANALYZE_OPTION_DECL)* ~ (";")? ~ "}"} // *********************************************** + +OPTION_CANON_searchall_yes = { "search_all" ~ ("=" ~ HIBOU_true)? } +OPTION_CANON_searchall_no = { "search_all" ~ "=" ~ HIBOU_false } +OPTION_CANON_searchall = _{ OPTION_CANON_searchall_yes | OPTION_CANON_searchall_no } +// *** +CANONIZE_OPTION_DECL = _{ GENERAL_OPTION_DECL + | OPTION_CANON_searchall } +CANONIZE_OPTION_SECTION = { "@canonize_option" ~ "{" ~ + CANONIZE_OPTION_DECL ~ (";" ~ CANONIZE_OPTION_DECL)* ~ (";")? + ~ "}"} + + +// *********************************************** + CONFIGURATION_SECTION = _{ EXPLORE_OPTION_SECTION - | ANALYZE_OPTION_SECTION } + | ANALYZE_OPTION_SECTION + | CANONIZE_OPTION_SECTION } HIBOU_CONFIGURATION = { CONFIGURATION_SECTION* } diff --git a/src/input/hcf/implem_ana.rs b/src/io/input/hcf/implem_ana.rs similarity index 90% rename from src/input/hcf/implem_ana.rs rename to src/io/input/hcf/implem_ana.rs index 8a0e255..8d07e46 100644 --- a/src/input/hcf/implem_ana.rs +++ b/src/io/input/hcf/implem_ana.rs @@ -19,15 +19,15 @@ limitations under the License. use pest::iterators::Pair; use crate::core::general_context::GeneralContext; -use crate::input::error::HibouParsingError; +use crate::io::input::error::HibouParsingError; -use crate::input::hcf::proc_options::opt_analyze::{HibouAnalyzeOptions, parse_analyze_options}; +use crate::io::input::hcf::proc_options::opt_analyze::{HibouAnalyzeOptions, parse_analyze_options}; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::hcf::parser::{HcfParser,Rule}; +use crate::io::input::hcf::parser::{HcfParser,Rule}; pub fn parse_hcf_string_for_ana(gen_ctx : &GeneralContext, hcf_string : String, file_name : &str) -> Result { @@ -79,6 +79,9 @@ fn parse_conf_pair_for_ana(gen_ctx : &GeneralContext, Rule::EXPLORE_OPTION_SECTION => { // nothing }, + Rule::CANONIZE_OPTION_SECTION => { + // nothing + }, _ => { panic!("what rule then ? : {:?}", current_pair.as_rule() ); } diff --git a/src/io/input/hcf/implem_canon.rs b/src/io/input/hcf/implem_canon.rs new file mode 100644 index 0000000..49c0e0d --- /dev/null +++ b/src/io/input/hcf/implem_canon.rs @@ -0,0 +1,94 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + +use pest::iterators::Pair; +use crate::core::general_context::GeneralContext; +use crate::io::input::error::HibouParsingError; + + +use crate::io::input::hcf::proc_options::opt_canonize::{HibouCanonizeOptions, parse_canonize_options}; + +#[allow(unused_imports)] +use crate::pest::Parser; +#[allow(unused_imports)] +use crate::io::input::hcf::parser::{HcfParser,Rule}; + + +pub fn parse_hcf_string_for_canonize(gen_ctx : &GeneralContext, + hcf_string : String, + file_name : &str) -> Result { + match HcfParser::parse(Rule::HCF_PEST_FILE, &hcf_string) { + Ok( ref mut got_pair ) => { + let conf_pair = got_pair.next().unwrap(); + match conf_pair.as_rule() { + Rule::HIBOU_CONFIGURATION => { + return parse_conf_pair_for_canonize(gen_ctx,conf_pair, file_name); + }, + _ => { + panic!("what rule then ? : {:?}", conf_pair.as_rule() ); + } + } + }, + Err(e) => { + return Err( HibouParsingError::MatchError(e.to_string()) ); + } + } +} + + +fn parse_conf_pair_for_canonize(gen_ctx : &GeneralContext, + conf_pair : Pair, + file_name : &str) + -> Result { + let mut got_section_canonize_options : bool = false; + let mut canonize_options = HibouCanonizeOptions::default(); + + let mut contents = conf_pair.into_inner(); + + while let Some(current_pair) = contents.next() { + match current_pair.as_rule() { + Rule::CANONIZE_OPTION_SECTION => { + if got_section_canonize_options { + return Err( HibouParsingError::HcfSetupError("several '@canonize_option' sections declared".to_string())); + } + got_section_canonize_options = true; + // *** + match parse_canonize_options(gen_ctx,current_pair,file_name) { + Err(e) => { + return Err(e); + }, + Ok( can_opts ) => { + canonize_options = can_opts; + } + } + }, + Rule::EXPLORE_OPTION_SECTION => { + // nothing + }, + Rule::ANALYZE_OPTION_SECTION => { + // nothing + }, + _ => { + panic!("what rule then ? : {:?}", current_pair.as_rule() ); + } + } + } + + return Ok(canonize_options); +} diff --git a/src/input/hcf/implem_explo.rs b/src/io/input/hcf/implem_explo.rs similarity index 90% rename from src/input/hcf/implem_explo.rs rename to src/io/input/hcf/implem_explo.rs index 7f47286..406b3eb 100644 --- a/src/input/hcf/implem_explo.rs +++ b/src/io/input/hcf/implem_explo.rs @@ -19,15 +19,15 @@ limitations under the License. use pest::iterators::Pair; use crate::core::general_context::GeneralContext; -use crate::input::error::HibouParsingError; +use crate::io::input::error::HibouParsingError; -use crate::input::hcf::proc_options::opt_explore::{HibouExploreOptions, parse_explore_options}; +use crate::io::input::hcf::proc_options::opt_explore::{HibouExploreOptions, parse_explore_options}; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::hcf::parser::{HcfParser,Rule}; +use crate::io::input::hcf::parser::{HcfParser,Rule}; pub fn parse_hcf_string_for_explore(gen_ctx : &GeneralContext, hcf_string : String, file_name : &str) -> Result { @@ -79,6 +79,9 @@ fn parse_conf_pair_for_explore(gen_ctx : &GeneralContext, Rule::ANALYZE_OPTION_SECTION => { // nothing }, + Rule::CANONIZE_OPTION_SECTION => { + // nothing + }, _ => { panic!("what rule then ? : {:?}", current_pair.as_rule() ); } diff --git a/src/input/hcf/interface.rs b/src/io/input/hcf/interface.rs similarity index 62% rename from src/input/hcf/interface.rs rename to src/io/input/hcf/interface.rs index 9c71f5c..f018c84 100644 --- a/src/input/hcf/interface.rs +++ b/src/io/input/hcf/interface.rs @@ -19,14 +19,15 @@ limitations under the License. use std::fs; use std::path::Path; use crate::core::general_context::GeneralContext; -use crate::input::error::HibouParsingError; -use crate::input::hcf::implem_ana::parse_hcf_string_for_ana; -use crate::input::hcf::implem_explo::parse_hcf_string_for_explore; -use crate::output::commons::file_extensions::{HIBOU_CONFIGURATION_FILE_EXTENSION}; - -pub use crate::input::hcf::proc_options::opt_explore::HibouExploreOptions; -pub use crate::input::hcf::proc_options::opt_analyze::HibouAnalyzeOptions; +use crate::io::input::error::HibouParsingError; +use crate::io::input::hcf::implem_ana::parse_hcf_string_for_ana; +use crate::io::input::hcf::implem_explo::parse_hcf_string_for_explore; +use crate::io::file_extensions::{HIBOU_CONFIGURATION_FILE_EXTENSION}; +use crate::io::input::hcf::implem_canon::parse_hcf_string_for_canonize; +pub use crate::io::input::hcf::proc_options::opt_explore::HibouExploreOptions; +pub use crate::io::input::hcf::proc_options::opt_analyze::HibouAnalyzeOptions; +pub use crate::io::input::hcf::proc_options::opt_canonize::HibouCanonizeOptions; pub fn parse_hcf_file_for_explore(gen_ctx : &GeneralContext, file_path : &str) -> Result { @@ -61,4 +62,22 @@ pub fn parse_hcf_file_for_ana(gen_ctx : &GeneralContext, file_path : &str) -> Re return Err( HibouParsingError::FileError(e.to_string()) ); } } -} \ No newline at end of file +} + +pub fn parse_hcf_file_for_canonize(gen_ctx : &GeneralContext, file_path : &str) -> Result { + let path_object = Path::new(file_path); + let file_extension : &str = path_object.extension().unwrap().to_str().unwrap(); + if file_extension != HIBOU_CONFIGURATION_FILE_EXTENSION { + return Err( HibouParsingError::FileFormatError(file_extension.to_string(),HIBOU_CONFIGURATION_FILE_EXTENSION.to_string())); + } + let file_name : &str = path_object.file_stem().unwrap().to_str().unwrap(); + match fs::read_to_string(file_path) { + Ok( unparsed_hcf_str ) => { + return parse_hcf_string_for_canonize(gen_ctx,unparsed_hcf_str, file_name); + }, + Err(e) => { + return Err( HibouParsingError::FileError(e.to_string()) ); + } + } +} + diff --git a/src/input/hcf/mod.rs b/src/io/input/hcf/mod.rs similarity index 97% rename from src/input/hcf/mod.rs rename to src/io/input/hcf/mod.rs index 567d164..bfc8fd1 100644 --- a/src/input/hcf/mod.rs +++ b/src/io/input/hcf/mod.rs @@ -19,4 +19,5 @@ mod parser; mod proc_options; mod implem_explo; mod implem_ana; +mod implem_canon; pub mod interface; \ No newline at end of file diff --git a/src/input/hcf/parser.rs b/src/io/input/hcf/parser.rs similarity index 93% rename from src/input/hcf/parser.rs rename to src/io/input/hcf/parser.rs index 5f7800d..fe704d8 100644 --- a/src/input/hcf/parser.rs +++ b/src/io/input/hcf/parser.rs @@ -22,7 +22,7 @@ use crate::pest::Parser; #[derive(Parser)] -#[grammar = "input/hcf/hcf_syntax.pest"] +#[grammar = "io/input/hcf/hcf_syntax.pest"] pub struct HcfParser; diff --git a/src/io/input/hcf/proc_options/loggers.rs b/src/io/input/hcf/proc_options/loggers.rs new file mode 100644 index 0000000..44a0f0d --- /dev/null +++ b/src/io/input/hcf/proc_options/loggers.rs @@ -0,0 +1,203 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use std::collections::HashSet; + +use pest::iterators::Pair; +use crate::core::colocalizations::CoLocalizations; + +use crate::core::general_context::GeneralContext; +use crate::io::input::error::HibouParsingError; + + +use crate::loggers::graphic::graphic_logger::GraphicProcessLogger; +use crate::loggers::tracegen::conf::TracegenProcessLoggerGeneration; +use crate::loggers::tracegen::tracegen_logger::TraceGenProcessLogger; +use crate::loggers::graphic::conf::{GraphicProcessLoggerLayout,GraphicProcessLoggerOutputFormat}; + + +#[allow(unused_imports)] +use crate::pest::Parser; +#[allow(unused_imports)] +use crate::io::input::hcf::parser::{HcfParser,Rule}; + + +pub fn parse_graphic_logger(logger_id : u32, + file_name : &str, + logger_kind_pair : Pair) -> GraphicProcessLogger { + // default configuration + let mut output_format = GraphicProcessLoggerOutputFormat::svg; + let mut layout = GraphicProcessLoggerLayout::vertical; + let mut int_repr_sd = true; + let mut int_repr_tt = false; + let mut parent_folder = "".to_string(); + let mut output_file_name = format!("{:}_l{:}",file_name,logger_id); + // *** + match logger_kind_pair.into_inner().next() { + None => { + // nothing + }, + Some(graphic_logger_opts) => { + for opt_pair in graphic_logger_opts.into_inner() { + match opt_pair.as_rule() { + Rule::GRAPHIC_LOGGER_format_png => { + output_format = GraphicProcessLoggerOutputFormat::png; + }, + Rule::GRAPHIC_LOGGER_format_svg => { + output_format = GraphicProcessLoggerOutputFormat::svg; + }, + Rule::GRAPHIC_LOGGER_layout_vertical => { + layout = GraphicProcessLoggerLayout::vertical; + }, + Rule::GRAPHIC_LOGGER_layout_horizontal => { + layout = GraphicProcessLoggerLayout::horizontal; + }, + Rule::GRAPHIC_LOGGER_draw_sequence_diagram => { + let inner = opt_pair.into_inner().next().unwrap(); + match inner.as_rule() { + Rule::HIBOU_true => { + int_repr_sd = true; + }, + Rule::HIBOU_false => { + int_repr_sd = false; + }, + _ => { + panic!("what rule then ? : {:?}", inner.as_rule()); + } + } + }, + Rule::GRAPHIC_LOGGER_draw_term_tree => { + let inner = opt_pair.into_inner().next().unwrap(); + match inner.as_rule() { + Rule::HIBOU_true => { + int_repr_tt = true; + }, + Rule::HIBOU_false => { + int_repr_tt = false; + }, + _ => { + panic!("what rule then ? : {:?}", inner.as_rule()); + } + } + }, + Rule::GRAPHIC_LOGGER_parent_folder => { + let inner_pair = opt_pair.into_inner().next().unwrap(); + parent_folder = inner_pair.as_str().chars().filter(|c| !c.is_whitespace()).collect(); + }, + Rule::GRAPHIC_LOGGER_output_file => { + let inner_pair = opt_pair.into_inner().next().unwrap(); + output_file_name = inner_pair.as_str().chars().filter(|c| !c.is_whitespace()).collect(); + }, + _ => { + panic!("what rule then ? : {:?}", opt_pair.as_rule()); + } + } + } + } + } + // *** + return GraphicProcessLogger::new(output_format, + layout, + int_repr_sd, + int_repr_tt, + format!("temp_l{:}", logger_id), + parent_folder, + output_file_name);; +} + + + +pub fn parse_tracegen_logger(logger_id : u32, + gen_ctx : &GeneralContext, + file_name : &str, + logger_kind_pair : Pair) -> Result { + // default configuration + let mut generation = TracegenProcessLoggerGeneration::terminal; + let mut co_localizations = CoLocalizations::get_trivial_partition(gen_ctx.get_lf_num()); + let mut parent_folder = format!("tracegen_{:}",file_name); + let mut files_prefix = "".to_string(); + // *** + match logger_kind_pair.into_inner().next() { + None => { + // nothing + }, + Some(tracegen_logger_opts) => { + for opt_pair in tracegen_logger_opts.into_inner() { + match opt_pair.as_rule() { + Rule::TRACEGEN_LOGGER_parent_folder => { + let inner_pair = opt_pair.into_inner().next().unwrap(); + parent_folder = inner_pair.as_str().chars().filter(|c| !c.is_whitespace()).collect(); + }, + Rule::TRACEGEN_LOGGER_trace_prefix => { + let inner_pair = opt_pair.into_inner().next().unwrap(); + files_prefix = inner_pair.as_str().chars().filter(|c| !c.is_whitespace()).collect(); + }, + Rule::TRACEGEN_LOGGER_terminal => { + generation = TracegenProcessLoggerGeneration::terminal; + }, + Rule::TRACEGEN_LOGGER_exact => { + generation = TracegenProcessLoggerGeneration::exact; + }, + Rule::TRACEGEN_LOGGER_prefix => { + generation = TracegenProcessLoggerGeneration::prefixes; + }, + Rule::TRACEGEN_LOGGER_partition_discrete => { + co_localizations = CoLocalizations::get_discrete_partition(gen_ctx.get_lf_num()); + }, + Rule::TRACEGEN_LOGGER_partition_trivial => { + co_localizations = CoLocalizations::get_trivial_partition(gen_ctx.get_lf_num()); + }, + Rule::TRACEGEN_LOGGER_partition_specific => { + let mut colocs : Vec> = vec![]; + // *** + let mut got_lfs = hashset!{}; + // *** + for lfs_list_pair in opt_pair.into_inner() { + let mut coloc = hashset!{}; + for lf_name_pair in lfs_list_pair.into_inner() { + let lf_name : String = lf_name_pair.as_str().chars().filter(|c| !c.is_whitespace()).collect(); + match gen_ctx.get_lf_id(&lf_name) { + None => { + return Err( HibouParsingError::MissingLifelineDeclarationError(lf_name) ); + }, + Some(lf_id) => { + if got_lfs.contains(&lf_id) { + return Err( HibouParsingError::NonDisjointTraceComponents ); + } + got_lfs.insert(lf_id); + coloc.insert(lf_id); + } + } + } + colocs.push(coloc); + } + // *** + co_localizations = CoLocalizations::new(colocs); + }, + _ => { + panic!("what rule then ? : {:?}", opt_pair.as_rule()); + } + } + } + } + } + return Ok(TraceGenProcessLogger::new(generation, + co_localizations, + parent_folder, + files_prefix)); +} + diff --git a/src/input/hcf/proc_options/mod.rs b/src/io/input/hcf/proc_options/mod.rs similarity index 96% rename from src/input/hcf/proc_options/mod.rs rename to src/io/input/hcf/proc_options/mod.rs index 044ab24..873cd80 100644 --- a/src/input/hcf/proc_options/mod.rs +++ b/src/io/input/hcf/proc_options/mod.rs @@ -17,4 +17,5 @@ limitations under the License. pub mod opt_explore; pub mod opt_analyze; +pub mod opt_canonize; mod loggers; \ No newline at end of file diff --git a/src/input/hcf/proc_options/opt_analyze.rs b/src/io/input/hcf/proc_options/opt_analyze.rs similarity index 91% rename from src/input/hcf/proc_options/opt_analyze.rs rename to src/io/input/hcf/proc_options/opt_analyze.rs index 611a486..c3846fa 100644 --- a/src/input/hcf/proc_options/opt_analyze.rs +++ b/src/io/input/hcf/proc_options/opt_analyze.rs @@ -17,8 +17,8 @@ limitations under the License. use pest::iterators::Pair; -use crate::input::error::HibouParsingError; -use crate::input::hcf::proc_options::loggers::parse_graphic_logger; +use crate::io::input::error::HibouParsingError; +use crate::io::input::hcf::proc_options::loggers::parse_graphic_logger; use crate::process::abstract_proc::common::HibouSearchStrategy; use crate::process::abstract_proc::manager::GenericProcessPriorities; use crate::process::ana_proc::logic::anakind::{AnalysisKind, SimulationActionCriterion, SimulationConfiguration, SimulationLoopCriterion, UseLocalAnalysis}; @@ -32,7 +32,7 @@ use crate::process::ana_proc::logic::verdicts::GlobalVerdict; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::hcf::parser::{HcfParser,Rule}; +use crate::io::input::hcf::parser::{HcfParser,Rule}; pub struct HibouAnalyzeOptions { @@ -87,10 +87,12 @@ pub fn parse_analyze_options(option_pair : Pair, Rule::OPTION_LOGGER_DECL => { loggers = Vec::new(); // *** + let mut logger_id : u32 = 0; for logger_kind_pair in option_decl_pair.into_inner() { + logger_id += 1; match logger_kind_pair.as_rule() { Rule::OPTION_GRAPHIC_LOGGER => { - let glogger = parse_graphic_logger(file_name,logger_kind_pair); + let glogger = parse_graphic_logger(logger_id, file_name,logger_kind_pair); loggers.push( Box::new(glogger)); }, _ => { @@ -281,12 +283,33 @@ fn parse_specific_priorities(priorities_decl_pair : Pair) -> Result { in_loop = priority_level; }, + // *** Rule::OPTION_PRIORITY_hide => { hide = priority_level; }, Rule::OPTION_PRIORITY_simu => { simu = priority_level; }, + // *** + Rule::OPTION_PRIORITY_simpl => { + return Err(HibouParsingError::ProcessPriorityError("found simpl priority in Analysis".to_string())); + }, + Rule::OPTION_PRIORITY_flush => { + return Err(HibouParsingError::ProcessPriorityError("found flush priority in Analysis".to_string())); + }, + Rule::OPTION_PRIORITY_invert => { + return Err(HibouParsingError::ProcessPriorityError("found invert priority in Analysis".to_string())); + }, + Rule::OPTION_PRIORITY_deduplicate => { + return Err(HibouParsingError::ProcessPriorityError("found deduplicate priority in Analysis".to_string())); + }, + Rule::OPTION_PRIORITY_factorize => { + return Err(HibouParsingError::ProcessPriorityError("found factorize priority in Analysis".to_string())); + }, + Rule::OPTION_PRIORITY_defactorize => { + return Err(HibouParsingError::ProcessPriorityError("found defactorize priority in Analysis".to_string())); + }, + // *** _ => { panic!("what rule then ? : {:?}", priority_kind_pair.as_rule() ); } diff --git a/src/io/input/hcf/proc_options/opt_canonize.rs b/src/io/input/hcf/proc_options/opt_canonize.rs new file mode 100644 index 0000000..00a7e03 --- /dev/null +++ b/src/io/input/hcf/proc_options/opt_canonize.rs @@ -0,0 +1,256 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use pest::iterators::Pair; + +use crate::core::general_context::GeneralContext; +use crate::io::input::error::HibouParsingError; +use crate::io::input::hcf::proc_options::loggers::{parse_graphic_logger}; +use crate::process::abstract_proc::common::HibouSearchStrategy; +use crate::process::abstract_proc::manager::GenericProcessPriorities; +use crate::process::canon_proc::interface::logger::CanonizationLogger; +use crate::process::canon_proc::interface::conf::CanonizationConfig; +use crate::process::canon_proc::interface::filter::CanonizationFilter; + +#[allow(unused_imports)] +use crate::pest::Parser; +#[allow(unused_imports)] +use crate::io::input::hcf::parser::{HcfParser,Rule}; +use crate::process::canon_proc::interface::priorities::CanonizationPriorities; + + +pub struct HibouCanonizeOptions { + pub loggers : Vec>, + pub strategy : HibouSearchStrategy, + pub filters : Vec, + pub priorities : GenericProcessPriorities, + pub search_all : bool +} + + + +impl HibouCanonizeOptions { + pub fn new(loggers : Vec>, + strategy : HibouSearchStrategy, + filters : Vec, + priorities : GenericProcessPriorities, + search_all : bool) -> HibouCanonizeOptions { + return HibouCanonizeOptions{loggers,strategy,filters,priorities,search_all}; + } + + pub fn default() -> HibouCanonizeOptions { + return HibouCanonizeOptions::new(Vec::new(), + HibouSearchStrategy::DFS, + vec![], + GenericProcessPriorities::Specific(CanonizationPriorities::default()), + false); + } + +} + + + + +pub fn parse_canonize_options(gen_ctx: &GeneralContext, + option_pair : Pair, + file_name : &str) -> Result { + let mut loggers : Vec> = Vec::new(); + let mut strategy : HibouSearchStrategy = HibouSearchStrategy::BFS; + let mut filters : Vec = Vec::new(); + let mut priorities : GenericProcessPriorities = GenericProcessPriorities::Specific(CanonizationPriorities::default()); + let mut search_all = false; + // *** + for option_decl_pair in option_pair.into_inner() { + match option_decl_pair.as_rule() { + Rule::OPTION_LOGGER_DECL => { + loggers = Vec::new(); + // *** + let mut logger_id : u32 = 0; + for logger_kind_pair in option_decl_pair.into_inner() { + logger_id += 1; + match logger_kind_pair.as_rule() { + Rule::OPTION_GRAPHIC_LOGGER => { + let glogger = parse_graphic_logger(logger_id,file_name,logger_kind_pair); + loggers.push( Box::new(glogger)); + }, + _ => { + panic!("what rule then ? : {:?}", logger_kind_pair.as_rule() ); + } + } + } + }, + Rule::OPTION_STRATEGY_DECL => { + let strategy_pair = option_decl_pair.into_inner().next().unwrap(); + match strategy_pair.as_rule() { + Rule::OPTION_STRATEGY_BFS => { + strategy = HibouSearchStrategy::BFS; + }, + Rule::OPTION_STRATEGY_DFS => { + strategy = HibouSearchStrategy::DFS; + }, + Rule::OPTION_STRATEGY_HCS => { + strategy = HibouSearchStrategy::HCS; + }, + _ => { + panic!("what rule then ? : {:?}", strategy_pair.as_rule() ); + } + } + }, + Rule::OPTION_FILTERS_DECL => { + match parse_filters(option_decl_pair) { + Ok( got_filters) => { + filters = got_filters; + }, + Err(e) => { + return Err(e); + } + } + }, + Rule::OPTION_PRIORITIES_DECL => { + let inner : Pair = option_decl_pair.into_inner().next().unwrap(); + match inner.as_rule() { + Rule::OPTION_PRIORITY_SPECIFIC => { + match parse_specific_priorities(inner) { + Ok( got_priorities) => { + priorities = GenericProcessPriorities::Specific(got_priorities); + }, + Err(e) => { + return Err(e); + } + } + }, + Rule::OPTION_PRIORITY_RANDOM => { + priorities = GenericProcessPriorities::Random; + }, + _ => { + panic!("what rule then ? : {:?}", inner.as_rule() ); + } + } + }, + Rule::OPTION_CANON_searchall_yes => { + search_all = true; + }, + Rule::OPTION_CANON_searchall_no => { + search_all = false; + }, + _ => { + panic!("what rule then ? : {:?}", option_decl_pair.as_rule() ); + } + } + } + // *** + let hoptions = HibouCanonizeOptions::new(loggers,strategy,filters,priorities,search_all); + return Ok(hoptions); +} + + + +fn parse_filters(filters_decl_pair : Pair) -> Result,HibouParsingError> { + let mut filters : Vec = Vec::new(); + for filter_pair in filters_decl_pair.into_inner() { + match filter_pair.as_rule() { + Rule::OPTION_FILTER_MAX_DEPTH => { + let content = filter_pair.into_inner().next().unwrap(); + let content_str : String = content.as_str().chars().filter(|c| !c.is_whitespace()).collect(); + let my_val : u32 = content_str.parse::().unwrap(); + filters.push(CanonizationFilter::MaxProcessDepth(my_val)); + }, + Rule::OPTION_FILTER_MAX_NODE_NUMBER => { + let content = filter_pair.into_inner().next().unwrap(); + let content_str : String = content.as_str().chars().filter(|c| !c.is_whitespace()).collect(); + let my_val : u32 = content_str.parse::().unwrap(); + filters.push(CanonizationFilter::MaxNodeNumber(my_val)); + }, + Rule::OPTION_FILTER_MAX_LOOP_DEPTH => { + return Err(HibouParsingError::ProcessFilterError("found max loop depth filter in Canonization".to_string())); + }, + _ => { + panic!("what rule then ? : {:?}", filter_pair.as_rule() ); + } + } + } + return Ok(filters); +} + + + + +fn parse_specific_priorities(priorities_decl_pair : Pair) -> Result { + let mut simpl : i32 = 0; + let mut flush : i32 = 0; + let mut invert : i32 = 0; + let mut deduplicate : i32 = 0; + let mut factorize : i32 = 0; + let mut defactorize : i32 = 0; + // *** + for priority_pair in priorities_decl_pair.into_inner() { + let mut priority_contents = priority_pair.into_inner(); + let priority_kind_pair = priority_contents.next().unwrap(); + // *** + let priority_level_pair = priority_contents.next().unwrap(); + let priority_level_str : String = priority_level_pair.as_str().chars().filter(|c| !c.is_whitespace()).collect(); + let priority_level : i32 = priority_level_str.parse::().unwrap(); + // *** + match priority_kind_pair.as_rule() { + Rule::OPTION_PRIORITY_simpl => { + simpl = priority_level; + }, + Rule::OPTION_PRIORITY_flush => { + flush = priority_level; + }, + Rule::OPTION_PRIORITY_invert => { + invert = priority_level; + }, + Rule::OPTION_PRIORITY_deduplicate => { + deduplicate = priority_level; + }, + Rule::OPTION_PRIORITY_factorize => { + factorize = priority_level; + }, + Rule::OPTION_PRIORITY_defactorize => { + defactorize = priority_level; + }, + // *** + Rule::OPTION_PRIORITY_emission => { + return Err(HibouParsingError::ProcessPriorityError("found emission priority in Canonization".to_string())); + }, + Rule::OPTION_PRIORITY_reception => { + return Err(HibouParsingError::ProcessPriorityError("found reception priority in Canonization".to_string())); + }, + Rule::OPTION_PRIORITY_multi_rdv => { + return Err(HibouParsingError::ProcessPriorityError("found multi-rdv priority in Canonization".to_string())); + }, + Rule::OPTION_PRIORITY_loop => { + return Err(HibouParsingError::ProcessPriorityError("found loop priority in Canonization".to_string())); + }, + // *** + Rule::OPTION_PRIORITY_hide => { + return Err(HibouParsingError::ProcessPriorityError("found hide priority in Canonization".to_string())); + }, + Rule::OPTION_PRIORITY_simu => { + return Err(HibouParsingError::ProcessPriorityError("found simu priority in Canonization".to_string())); + }, + // *** + _ => { + panic!("what rule then ? : {:?}", priority_kind_pair.as_rule() ); + } + } + } + // *** + let priorities = CanonizationPriorities::new(simpl,flush,invert,deduplicate,factorize,defactorize); + return Ok(priorities); +} \ No newline at end of file diff --git a/src/input/hcf/proc_options/opt_explore.rs b/src/io/input/hcf/proc_options/opt_explore.rs similarity index 81% rename from src/input/hcf/proc_options/opt_explore.rs rename to src/io/input/hcf/proc_options/opt_explore.rs index 2b3c299..5ac30ba 100644 --- a/src/input/hcf/proc_options/opt_explore.rs +++ b/src/io/input/hcf/proc_options/opt_explore.rs @@ -18,8 +18,8 @@ limitations under the License. use pest::iterators::Pair; use crate::core::general_context::GeneralContext; -use crate::input::error::HibouParsingError; -use crate::input::hcf::proc_options::loggers::{parse_graphic_logger, parse_tracegen_logger}; +use crate::io::input::error::HibouParsingError; +use crate::io::input::hcf::proc_options::loggers::{parse_graphic_logger, parse_tracegen_logger}; use crate::process::abstract_proc::common::HibouSearchStrategy; use crate::process::abstract_proc::manager::GenericProcessPriorities; use crate::process::explo_proc::interface::conf::ExplorationConfig; @@ -31,7 +31,7 @@ use crate::process::explo_proc::interface::priorities::ExplorationPriorities; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::hcf::parser::{HcfParser,Rule}; +use crate::io::input::hcf::parser::{HcfParser,Rule}; pub struct HibouExploreOptions { @@ -76,14 +76,16 @@ pub fn parse_explore_options(gen_ctx: &GeneralContext, Rule::OPTION_LOGGER_DECL => { loggers = Vec::new(); // *** + let mut logger_id : u32 = 0; for logger_kind_pair in option_decl_pair.into_inner() { + logger_id += 1; match logger_kind_pair.as_rule() { Rule::OPTION_GRAPHIC_LOGGER => { - let glogger = parse_graphic_logger(file_name,logger_kind_pair); + let glogger = parse_graphic_logger(logger_id,file_name,logger_kind_pair); loggers.push( Box::new(glogger)); }, Rule::OPTION_TRACEGEN_LOGGER => { - match parse_tracegen_logger(gen_ctx,file_name,logger_kind_pair) { + match parse_tracegen_logger(logger_id, gen_ctx,file_name,logger_kind_pair) { Err(e) => { return Err(e); }, @@ -218,6 +220,33 @@ fn parse_specific_priorities(priorities_decl_pair : Pair) -> Result { in_loop = priority_level; }, + // *** + Rule::OPTION_PRIORITY_hide => { + return Err(HibouParsingError::ProcessPriorityError("found hide priority in Exploration".to_string())); + }, + Rule::OPTION_PRIORITY_simu => { + return Err(HibouParsingError::ProcessPriorityError("found simu priority in Exploration".to_string())); + }, + // *** + Rule::OPTION_PRIORITY_simpl => { + return Err(HibouParsingError::ProcessPriorityError("found simpl priority in Exploration".to_string())); + }, + Rule::OPTION_PRIORITY_flush => { + return Err(HibouParsingError::ProcessPriorityError("found flush priority in Exploration".to_string())); + }, + Rule::OPTION_PRIORITY_invert => { + return Err(HibouParsingError::ProcessPriorityError("found invert priority in Exploration".to_string())); + }, + Rule::OPTION_PRIORITY_deduplicate => { + return Err(HibouParsingError::ProcessPriorityError("found deduplicate priority in Exploration".to_string())); + }, + Rule::OPTION_PRIORITY_factorize => { + return Err(HibouParsingError::ProcessPriorityError("found factorize priority in Exploration".to_string())); + }, + Rule::OPTION_PRIORITY_defactorize => { + return Err(HibouParsingError::ProcessPriorityError("found defactorize priority in Exploration".to_string())); + }, + // *** _ => { panic!("what rule then ? : {:?}", priority_kind_pair.as_rule() ); } diff --git a/src/input/hif/action/act_content.rs b/src/io/input/hif/action/act_content.rs similarity index 97% rename from src/input/hif/action/act_content.rs rename to src/io/input/hif/action/act_content.rs index 7b13778..f145956 100644 --- a/src/input/hif/action/act_content.rs +++ b/src/io/input/hif/action/act_content.rs @@ -19,14 +19,14 @@ use pest::iterators::Pair; use crate::core::general_context::GeneralContext; use crate::core::language::syntax::action::CommunicationSynchronicity; -use crate::input::error::HibouParsingError; +use crate::io::input::error::HibouParsingError; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::hif::parser::{HifParser,Rule}; +use crate::io::input::hif::parser::{HifParser,Rule}; pub enum ParsedReference { diff --git a/src/input/hif/action/act_targets.rs b/src/io/input/hif/action/act_targets.rs similarity index 94% rename from src/input/hif/action/act_targets.rs rename to src/io/input/hif/action/act_targets.rs index cc377ea..76f5806 100644 --- a/src/input/hif/action/act_targets.rs +++ b/src/io/input/hif/action/act_targets.rs @@ -19,14 +19,14 @@ use pest::iterators::Pair; use crate::core::general_context::GeneralContext; use crate::core::language::syntax::action::EmissionTargetRef; -use crate::input::error::HibouParsingError; +use crate::io::input::error::HibouParsingError; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::hif::parser::{HifParser,Rule}; +use crate::io::input::hif::parser::{HifParser,Rule}; pub fn parse_comm_act_targets_as_lifelines(gen_ctx : &GeneralContext, target_pair : Pair) -> Result,HibouParsingError> { @@ -53,7 +53,7 @@ pub fn parse_comm_act_targets_as_lifelines(gen_ctx : &GeneralContext, target_pai }, Some( lf_id ) => { if target_lf_ids.contains(&lf_id) { - return Err( HibouParsingError::EmissionDefinitionError( format!("duplicate target {:}",lf_name) ) ); + return Err( HibouParsingError::EmissionDefinitionError( format!("duplicate target lifeline {:}",lf_name) ) ); } else { target_lf_ids.push( lf_id ); } @@ -109,7 +109,7 @@ pub fn parse_comm_act_targets_as_generic_targets(gen_ctx : &GeneralContext, targ Some( tar_gt_id ) => { let new_ref = EmissionTargetRef::Gate( tar_gt_id ); if target_refs.contains(&new_ref) { - return Err( HibouParsingError::EmissionDefinitionError( "duplicate target in emission".to_string() ) ); + return Err( HibouParsingError::EmissionDefinitionError( format!("duplicate target gate {:}",target_name) ) ); } else { target_refs.push(new_ref); } @@ -119,7 +119,7 @@ pub fn parse_comm_act_targets_as_generic_targets(gen_ctx : &GeneralContext, targ Some( tar_lf_id ) => { let new_ref = EmissionTargetRef::Lifeline( tar_lf_id ); if target_refs.contains(&new_ref) { - return Err( HibouParsingError::EmissionDefinitionError( "duplicate target in emission".to_string() ) ); + return Err( HibouParsingError::EmissionDefinitionError( format!("duplicate target lifeline {:}",target_name) ) ); } else { target_refs.push(new_ref); } diff --git a/src/input/hif/action/action.rs b/src/io/input/hif/action/action.rs similarity index 95% rename from src/input/hif/action/action.rs rename to src/io/input/hif/action/action.rs index af29b23..04ea51f 100644 --- a/src/input/hif/action/action.rs +++ b/src/io/input/hif/action/action.rs @@ -20,16 +20,16 @@ use pest::iterators::{Pair, Pairs}; use crate::core::general_context::GeneralContext; use crate::core::language::syntax::action::{EmissionAction, ReceptionAction}; use crate::core::language::syntax::interaction::Interaction; -use crate::input::hif::action::act_content::*; -use crate::input::hif::action::act_targets::*; -use crate::input::error::HibouParsingError; +use crate::io::input::hif::action::act_content::*; +use crate::io::input::hif::action::act_targets::*; +use crate::io::input::error::HibouParsingError; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::hif::parser::{HifParser,Rule}; +use crate::io::input::hif::parser::{HifParser,Rule}; pub fn parse_communication_action(gen_ctx : &GeneralContext, contents : &mut Pairs) -> Result { diff --git a/src/input/hif/action/mod.rs b/src/io/input/hif/action/mod.rs similarity index 100% rename from src/input/hif/action/mod.rs rename to src/io/input/hif/action/mod.rs diff --git a/src/input/hif/hif_syntax.pest b/src/io/input/hif/hif_syntax.pest similarity index 100% rename from src/input/hif/hif_syntax.pest rename to src/io/input/hif/hif_syntax.pest diff --git a/src/input/hif/interaction.rs b/src/io/input/hif/interaction.rs similarity index 96% rename from src/input/hif/interaction.rs rename to src/io/input/hif/interaction.rs index 9c27dea..1a52123 100644 --- a/src/input/hif/interaction.rs +++ b/src/io/input/hif/interaction.rs @@ -20,14 +20,14 @@ use pest::iterators::{Pair, Pairs}; use crate::core::general_context::GeneralContext; use crate::core::language::syntax::interaction::{Interaction, LoopKind}; -use crate::input::error::HibouParsingError; -use crate::input::hif::action::action::parse_communication_action; +use crate::io::input::error::HibouParsingError; +use crate::io::input::hif::action::action::parse_communication_action; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::hif::parser::{HifParser,Rule}; +use crate::io::input::hif::parser::{HifParser,Rule}; pub fn parse_hif_string(gen_ctx : &GeneralContext, hif_string : String) -> Result { @@ -93,11 +93,11 @@ fn parse_interaction(gen_ctx : &GeneralContext, interaction_pair : Pair) - // *** match gen_ctx.get_lf_id( &target_lf_name ) { None => { - return Err( HibouParsingError::MissingLifelineOrGateDeclarationError( target_lf_name ) ); + return Err( HibouParsingError::MissingLifelineDeclarationError( target_lf_name ) ); }, Some( tar_lf_id ) => { if target_lfs.contains(&tar_lf_id) { - return Err( HibouParsingError::OtherDefinitionError( "duplicate lifeline in co-region".to_string() ) ); + return Err( HibouParsingError::OtherDefinitionError( format!("duplicate lifeline in co-region : {:}", target_lf_name) ) ); } else { target_lfs.push(tar_lf_id); } diff --git a/src/input/hif/interface.rs b/src/io/input/hif/interface.rs similarity index 88% rename from src/input/hif/interface.rs rename to src/io/input/hif/interface.rs index 7fe367f..6f022da 100644 --- a/src/input/hif/interface.rs +++ b/src/io/input/hif/interface.rs @@ -22,10 +22,10 @@ use std::path::Path; use crate::core::general_context::GeneralContext; use crate::core::language::syntax::interaction::Interaction; -use crate::input::error::HibouParsingError; -use crate::input::hif::interaction::parse_hif_string; +use crate::io::input::error::HibouParsingError; +use crate::io::input::hif::interaction::parse_hif_string; -use crate::output::commons::file_extensions::{HIBOU_INTERACTION_FILE_EXTENSION}; +use crate::io::file_extensions::{HIBOU_INTERACTION_FILE_EXTENSION}; pub fn parse_hif_file(gen_ctx : &GeneralContext, file_path : &str) -> Result { diff --git a/src/input/hif/mod.rs b/src/io/input/hif/mod.rs similarity index 100% rename from src/input/hif/mod.rs rename to src/io/input/hif/mod.rs diff --git a/src/input/hif/parser.rs b/src/io/input/hif/parser.rs similarity index 93% rename from src/input/hif/parser.rs rename to src/io/input/hif/parser.rs index 8186c78..553b55b 100644 --- a/src/input/hif/parser.rs +++ b/src/io/input/hif/parser.rs @@ -22,7 +22,7 @@ use crate::pest::Parser; #[derive(Parser)] -#[grammar = "input/hif/hif_syntax.pest"] +#[grammar = "io/input/hif/hif_syntax.pest"] pub struct HifParser; diff --git a/src/input/hsf/hsf_syntax.pest b/src/io/input/hsf/hsf_syntax.pest similarity index 100% rename from src/input/hsf/hsf_syntax.pest rename to src/io/input/hsf/hsf_syntax.pest diff --git a/src/input/hsf/implem.rs b/src/io/input/hsf/implem.rs similarity index 97% rename from src/input/hsf/implem.rs rename to src/io/input/hsf/implem.rs index 813fcc0..48d5d67 100644 --- a/src/input/hsf/implem.rs +++ b/src/io/input/hsf/implem.rs @@ -19,12 +19,12 @@ limitations under the License. use pest::iterators::Pair; use crate::core::general_context::GeneralContext; -use crate::input::error::HibouParsingError; +use crate::io::input::error::HibouParsingError; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::hsf::parser::*; +use crate::io::input::hsf::parser::*; pub fn parse_hsf_string(hsf_string : String) -> Result { diff --git a/src/input/hsf/interface.rs b/src/io/input/hsf/interface.rs similarity index 88% rename from src/input/hsf/interface.rs rename to src/io/input/hsf/interface.rs index 80dd3c5..6cf1818 100644 --- a/src/input/hsf/interface.rs +++ b/src/io/input/hsf/interface.rs @@ -19,10 +19,10 @@ limitations under the License. use std::fs; use std::path::Path; use crate::core::general_context::GeneralContext; -use crate::input::error::HibouParsingError; -use crate::output::commons::file_extensions::HIBOU_SIGNATURE_FILE_EXTENSION; +use crate::io::file_extensions::HIBOU_SIGNATURE_FILE_EXTENSION; +use crate::io::input::error::HibouParsingError; -use crate::input::hsf::implem::parse_hsf_string; +use crate::io::input::hsf::implem::parse_hsf_string; pub fn parse_hsf_file(file_path : &str) -> Result { let path_object = Path::new(file_path); diff --git a/src/input/hsf/mod.rs b/src/io/input/hsf/mod.rs similarity index 100% rename from src/input/hsf/mod.rs rename to src/io/input/hsf/mod.rs diff --git a/src/input/hsf/parser.rs b/src/io/input/hsf/parser.rs similarity index 93% rename from src/input/hsf/parser.rs rename to src/io/input/hsf/parser.rs index 14c72a7..69e6e59 100644 --- a/src/input/hsf/parser.rs +++ b/src/io/input/hsf/parser.rs @@ -22,7 +22,7 @@ use crate::pest::Parser; #[derive(Parser)] -#[grammar = "input/hsf/hsf_syntax.pest"] +#[grammar = "io/input/hsf/hsf_syntax.pest"] pub struct HsfParser; diff --git a/src/input/htf/htf_syntax.pest b/src/io/input/htf/htf_syntax.pest similarity index 100% rename from src/input/htf/htf_syntax.pest rename to src/io/input/htf/htf_syntax.pest diff --git a/src/input/htf/implem.rs b/src/io/input/htf/implem.rs similarity index 94% rename from src/input/htf/implem.rs rename to src/io/input/htf/implem.rs index 45caa7c..1034ecd 100644 --- a/src/input/htf/implem.rs +++ b/src/io/input/htf/implem.rs @@ -23,15 +23,15 @@ use crate::core::colocalizations::CoLocalizations; use crate::core::general_context::GeneralContext; use crate::core::execution::trace::multitrace::MultiTrace; -use crate::input::error::HibouParsingError; -use crate::input::htf::multi_trace::trace_canal_from_pair; -use crate::input::htf::trace::trace_sequence_from_pair; +use crate::io::input::error::HibouParsingError; +use crate::io::input::htf::multi_trace::trace_canal_from_pair; +use crate::io::input::htf::trace::trace_sequence_from_pair; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::htf::parser::{HtfParser,Rule}; +use crate::io::input::htf::parser::{HtfParser,Rule}; diff --git a/src/input/htf/interface.rs b/src/io/input/htf/interface.rs similarity index 88% rename from src/input/htf/interface.rs rename to src/io/input/htf/interface.rs index f900d65..3295ea0 100644 --- a/src/input/htf/interface.rs +++ b/src/io/input/htf/interface.rs @@ -25,9 +25,9 @@ use crate::core::colocalizations::CoLocalizations; use crate::core::general_context::GeneralContext; use crate::core::execution::trace::multitrace::MultiTrace; -use crate::input::error::HibouParsingError; -use crate::input::htf::implem::multitrace_from_text; -use crate::output::commons::file_extensions::HIBOU_TRACE_FILE_EXTENSION; +use crate::io::input::error::HibouParsingError; +use crate::io::input::htf::implem::multitrace_from_text; +use crate::io::file_extensions::HIBOU_TRACE_FILE_EXTENSION; @@ -58,8 +58,8 @@ use crate::core::execution::trace::trace::TraceAction; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::htf::parser::{HtfParser,Rule}; -use crate::input::htf::trace::trace_element_from_pair; +use crate::io::input::htf::parser::{HtfParser,Rule}; +use crate::io::input::htf::trace::trace_element_from_pair; pub fn multi_action_from_text(gen_ctx : &GeneralContext, diff --git a/src/input/htf/mod.rs b/src/io/input/htf/mod.rs similarity index 100% rename from src/input/htf/mod.rs rename to src/io/input/htf/mod.rs diff --git a/src/input/htf/multi_trace.rs b/src/io/input/htf/multi_trace.rs similarity index 95% rename from src/input/htf/multi_trace.rs rename to src/io/input/htf/multi_trace.rs index 1baaf8f..a86753c 100644 --- a/src/input/htf/multi_trace.rs +++ b/src/io/input/htf/multi_trace.rs @@ -22,15 +22,15 @@ use pest::iterators::Pair; use crate::core::execution::trace::multitrace::MultiTrace; use crate::core::general_context::GeneralContext; -use crate::input::error::HibouParsingError; -use crate::input::htf::trace::trace_sequence_from_pair; +use crate::io::input::error::HibouParsingError; +use crate::io::input::htf::trace::trace_sequence_from_pair; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::htf::parser::{HtfParser,Rule}; +use crate::io::input::htf::parser::{HtfParser,Rule}; @@ -79,7 +79,7 @@ pub fn trace_canal_from_pair(gen_ctx : &GeneralContext, let lf_name : String = trace_lf_pair.as_str().chars().filter(|c| !c.is_whitespace()).collect(); match gen_ctx.get_lf_id(&lf_name) { None => { - return Err( HibouParsingError::MissingLifelineOrGateDeclarationError(lf_name)); + return Err( HibouParsingError::MissingLifelineDeclarationError(lf_name)); }, Some( lf_id ) => { lifelines.insert(lf_id); diff --git a/src/input/htf/parser.rs b/src/io/input/htf/parser.rs similarity index 93% rename from src/input/htf/parser.rs rename to src/io/input/htf/parser.rs index 3148f6e..948be0a 100644 --- a/src/input/htf/parser.rs +++ b/src/io/input/htf/parser.rs @@ -22,7 +22,7 @@ use crate::pest::Parser; #[derive(Parser)] -#[grammar = "input/htf/htf_syntax.pest"] +#[grammar = "io/input/htf/htf_syntax.pest"] pub struct HtfParser; diff --git a/src/input/htf/trace.rs b/src/io/input/htf/trace.rs similarity index 97% rename from src/input/htf/trace.rs rename to src/io/input/htf/trace.rs index abf973d..f1505a5 100644 --- a/src/input/htf/trace.rs +++ b/src/io/input/htf/trace.rs @@ -22,13 +22,13 @@ use pest::iterators::Pair; use crate::core::general_context::GeneralContext; use crate::core::execution::trace::multitrace::Trace; use crate::core::execution::trace::trace::{TraceAction, TraceActionKind}; -use crate::input::error::HibouParsingError; +use crate::io::input::error::HibouParsingError; #[allow(unused_imports)] use crate::pest::Parser; #[allow(unused_imports)] -use crate::input::htf::parser::{HtfParser,Rule}; +use crate::io::input::htf::parser::{HtfParser,Rule}; @@ -137,7 +137,7 @@ fn trace_action_from_text(gen_ctx : &GeneralContext, let got_lf_id : usize; match gen_ctx.get_lf_id(&lf_name) { None => { - return Err( HibouParsingError::MissingLifelineOrGateDeclarationError(lf_name) ); + return Err( HibouParsingError::MissingLifelineDeclarationError(lf_name) ); }, Some( lf_id ) => { got_lf_id = lf_id; diff --git a/src/input/mod.rs b/src/io/input/mod.rs similarity index 100% rename from src/input/mod.rs rename to src/io/input/mod.rs diff --git a/src/output/commons/mod.rs b/src/io/mod.rs similarity index 91% rename from src/output/commons/mod.rs rename to src/io/mod.rs index 16cafe4..cc51de3 100644 --- a/src/output/commons/mod.rs +++ b/src/io/mod.rs @@ -14,7 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ -pub mod textual_convention; pub mod file_extensions; -pub mod textual_representation; +mod textual_convention; +pub mod input; +pub mod output; \ No newline at end of file diff --git a/src/output/rendering/DejaVuFontsLicense.txt b/src/io/output/draw_commons/DejaVuFontsLicense.txt similarity index 100% rename from src/output/rendering/DejaVuFontsLicense.txt rename to src/io/output/draw_commons/DejaVuFontsLicense.txt diff --git a/src/output/rendering/DejaVuSansMono.ttf b/src/io/output/draw_commons/DejaVuSansMono.ttf similarity index 100% rename from src/output/rendering/DejaVuSansMono.ttf rename to src/io/output/draw_commons/DejaVuSansMono.ttf diff --git a/src/output/rendering/custom_draw/utils/colored_text.rs b/src/io/output/draw_commons/colored_text/draw_ttp.rs similarity index 92% rename from src/output/rendering/custom_draw/utils/colored_text.rs rename to src/io/output/draw_commons/colored_text/draw_ttp.rs index 3649b3b..c0a23ba 100644 --- a/src/output/rendering/custom_draw/utils/colored_text.rs +++ b/src/io/output/draw_commons/colored_text/draw_ttp.rs @@ -20,10 +20,10 @@ use image::{Rgb, RgbImage}; use imageproc::drawing::{draw_filled_rect_mut, draw_text_mut}; use imageproc::rect::Rect; use rusttype::{Font, Scale}; -use crate::output::rendering::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::HCP_White; +use crate::io::output::draw_commons::sd_drawing_conf::{FONT_HEIGHT, FONT_WIDTH, HIBOU_GRAPHIC_FONT, MARGIN, VERTICAL_SIZE}; -use crate::output::rendering::hibou_color_palette::HCP_White; -use crate::output::rendering::sd_drawing_conf::*; pub enum DrawnColoredTextAlignment { Left, diff --git a/src/io/output/draw_commons/colored_text/mod.rs b/src/io/output/draw_commons/colored_text/mod.rs new file mode 100644 index 0000000..9694ec0 --- /dev/null +++ b/src/io/output/draw_commons/colored_text/mod.rs @@ -0,0 +1,19 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +pub mod draw_ttp; +pub mod ttp; + diff --git a/src/output/rendering/colored_text/ttp.rs b/src/io/output/draw_commons/colored_text/ttp.rs similarity index 100% rename from src/output/rendering/colored_text/ttp.rs rename to src/io/output/draw_commons/colored_text/ttp.rs diff --git a/src/output/rendering/hibou_color_palette.rs b/src/io/output/draw_commons/hibou_color_palette.rs similarity index 100% rename from src/output/rendering/hibou_color_palette.rs rename to src/io/output/draw_commons/hibou_color_palette.rs diff --git a/src/output/rendering/mod.rs b/src/io/output/draw_commons/mod.rs similarity index 91% rename from src/output/rendering/mod.rs rename to src/io/output/draw_commons/mod.rs index c94f9aa..61f46e6 100644 --- a/src/output/rendering/mod.rs +++ b/src/io/output/draw_commons/mod.rs @@ -17,7 +17,5 @@ limitations under the License. pub mod hibou_color_palette; pub mod sd_drawing_conf; -pub mod colored_text; -pub mod graphviz; -pub mod custom_draw; +pub mod colored_text; \ No newline at end of file diff --git a/src/output/rendering/sd_drawing_conf.rs b/src/io/output/draw_commons/sd_drawing_conf.rs similarity index 100% rename from src/output/rendering/sd_drawing_conf.rs rename to src/io/output/draw_commons/sd_drawing_conf.rs diff --git a/src/output/rendering/custom_draw/seqdiag/action/common.rs b/src/io/output/draw_interactions/as_sd/action_repr/common.rs similarity index 96% rename from src/output/rendering/custom_draw/seqdiag/action/common.rs rename to src/io/output/draw_interactions/as_sd/action_repr/common.rs index d704cfa..59253e8 100644 --- a/src/output/rendering/custom_draw/seqdiag/action/common.rs +++ b/src/io/output/draw_interactions/as_sd/action_repr/common.rs @@ -19,12 +19,12 @@ use imageproc::drawing::draw_line_segment_mut; use crate::core::language::syntax::action::*; use crate::core::language::syntax::action::CommunicationSynchronicity; -use crate::output::rendering::hibou_color_palette::*; +use crate::io::output::draw_commons::hibou_color_palette::HCP_Black; -// ********** // ********** + pub fn draw_line_for_message_exchange(image : &mut RgbImage, synchronicity : &CommunicationSynchronicity, x_left : f32, x_right : f32, y_pos : f32) { match synchronicity { CommunicationSynchronicity::Asynchronous => { diff --git a/src/output/rendering/custom_draw/seqdiag/action/emission.rs b/src/io/output/draw_interactions/as_sd/action_repr/emission.rs similarity index 91% rename from src/output/rendering/custom_draw/seqdiag/action/emission.rs rename to src/io/output/draw_interactions/as_sd/action_repr/emission.rs index bd856db..0db8f39 100644 --- a/src/output/rendering/custom_draw/seqdiag/action/emission.rs +++ b/src/io/output/draw_interactions/as_sd/action_repr/emission.rs @@ -24,15 +24,15 @@ use imageproc::drawing::draw_filled_rect_mut; use imageproc::rect::Rect; use crate::core::general_context::GeneralContext; -use crate::core::language::syntax::action::*; -use crate::output::rendering::colored_text::ttp::TextToPrint; -use crate::output::rendering::custom_draw::seqdiag::action::common::draw_line_for_message_exchange; -use crate::output::rendering::custom_draw::seqdiag::dimensions_tools::*; -use crate::output::rendering::custom_draw::seqdiag::lf_coords::DrawingLifelineCoords; -use crate::output::rendering::custom_draw::utils::arrow_heads::*; -use crate::output::rendering::custom_draw::utils::colored_text::draw_colored_text; -use crate::output::rendering::hibou_color_palette::*; -use crate::output::rendering::sd_drawing_conf::*; +use crate::core::language::syntax::action::{EmissionAction, EmissionTargetRef}; +use crate::io::output::draw_commons::colored_text::draw_ttp::draw_colored_text; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::{HC_Message, HCP_Black}; +use crate::io::output::draw_commons::sd_drawing_conf::{FONT_WIDTH, GATE_SIZE, HORIZONTAL_SIZE, MARGIN}; +use crate::io::output::draw_interactions::as_sd::action_repr::common::draw_line_for_message_exchange; +use crate::io::output::draw_interactions::as_sd::util::arrow_heads::{draw_arrowhead_leftward, draw_arrowhead_rightward}; +use crate::io::output::draw_interactions::as_sd::util::dimensions_tools::get_y_pos_from_yshift; +use crate::io::output::draw_interactions::as_sd::util::lf_coords::DrawingLifelineCoords; // ********** diff --git a/src/output/rendering/custom_draw/seqdiag/action/mod.rs b/src/io/output/draw_interactions/as_sd/action_repr/mod.rs similarity index 100% rename from src/output/rendering/custom_draw/seqdiag/action/mod.rs rename to src/io/output/draw_interactions/as_sd/action_repr/mod.rs diff --git a/src/output/rendering/custom_draw/seqdiag/action/reception.rs b/src/io/output/draw_interactions/as_sd/action_repr/reception.rs similarity index 84% rename from src/output/rendering/custom_draw/seqdiag/action/reception.rs rename to src/io/output/draw_interactions/as_sd/action_repr/reception.rs index eda77ec..c31afa3 100644 --- a/src/output/rendering/custom_draw/seqdiag/action/reception.rs +++ b/src/io/output/draw_interactions/as_sd/action_repr/reception.rs @@ -23,15 +23,15 @@ use imageproc::drawing::draw_filled_rect_mut; use imageproc::rect::Rect; use crate::core::general_context::GeneralContext; -use crate::core::language::syntax::action::*; -use crate::output::rendering::colored_text::ttp::TextToPrint; -use crate::output::rendering::custom_draw::seqdiag::action::common::draw_line_for_message_exchange; -use crate::output::rendering::custom_draw::seqdiag::dimensions_tools::*; -use crate::output::rendering::custom_draw::seqdiag::lf_coords::DrawingLifelineCoords; -use crate::output::rendering::custom_draw::utils::arrow_heads::*; -use crate::output::rendering::custom_draw::utils::colored_text::draw_colored_text; -use crate::output::rendering::hibou_color_palette::*; -use crate::output::rendering::sd_drawing_conf::*; +use crate::core::language::syntax::action::ReceptionAction; +use crate::io::output::draw_commons::colored_text::draw_ttp::draw_colored_text; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::{HC_Message, HCP_Black}; +use crate::io::output::draw_commons::sd_drawing_conf::{FONT_WIDTH, GATE_SIZE, HORIZONTAL_SIZE}; +use crate::io::output::draw_interactions::as_sd::action_repr::common::draw_line_for_message_exchange; +use crate::io::output::draw_interactions::as_sd::util::arrow_heads::draw_arrowhead_rightward; +use crate::io::output::draw_interactions::as_sd::util::dimensions_tools::get_y_pos_from_yshift; +use crate::io::output::draw_interactions::as_sd::util::lf_coords::DrawingLifelineCoords; // ********** diff --git a/src/output/rendering/custom_draw/seqdiag/img_content.rs b/src/io/output/draw_interactions/as_sd/interaction_repr/img_content.rs similarity index 81% rename from src/output/rendering/custom_draw/seqdiag/img_content.rs rename to src/io/output/draw_interactions/as_sd/interaction_repr/img_content.rs index 92cf698..f3a5488 100644 --- a/src/output/rendering/custom_draw/seqdiag/img_content.rs +++ b/src/io/output/draw_interactions/as_sd/interaction_repr/img_content.rs @@ -23,16 +23,16 @@ use rusttype::{Font, Scale}; use crate::core::general_context::GeneralContext; use crate::core::language::syntax::interaction::{Interaction, LoopKind}; -use crate::core::language::syntax::util::get_recursive_frag::*; -use crate::output::rendering::custom_draw::seqdiag::action::emission::draw_emission; -use crate::output::rendering::custom_draw::seqdiag::action::reception::draw_reception; -use crate::output::rendering::custom_draw::seqdiag::dimensions_tools::*; -use crate::output::rendering::custom_draw::seqdiag::lf_coords::DrawingLifelineCoords; -use crate::output::rendering::custom_draw::utils::colored_text::draw_colored_text; -use crate::output::rendering::hibou_color_palette::*; -use crate::output::rendering::sd_drawing_conf::*; -use crate::output::commons::textual_convention::*; -use crate::output::rendering::colored_text::ttp::TextToPrint; +use crate::core::language::syntax::util::get_recursive_frag::{get_recursive_strict_frags,get_recursive_seq_frags,get_recursive_par_frags,get_recursive_alt_frags,get_recursive_coreg_frags}; +use crate::io::output::draw_commons::colored_text::draw_ttp::draw_colored_text; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::HCP_Black; +use crate::io::output::draw_commons::sd_drawing_conf::{FONT_HEIGHT, FONT_WIDTH, FRAGMENT_PADDING, FRAGMENT_TITLE_MARGIN, HIBOU_GRAPHIC_FONT, VERTICAL_SIZE}; +use crate::io::output::draw_interactions::as_sd::action_repr::emission::draw_emission; +use crate::io::output::draw_interactions::as_sd::action_repr::reception::draw_reception; +use crate::io::output::draw_interactions::as_sd::util::dimensions_tools::get_y_pos_from_yshift; +use crate::io::output::draw_interactions::as_sd::util::lf_coords::DrawingLifelineCoords; +use crate::io::textual_convention::*; // ********** @@ -207,40 +207,43 @@ fn draw_combined_fragment_frame( image : &mut RgbImage, left_bound : usize, right_bound : usize, y_drafts : Vec) { - let left_lf_coords = lf_x_widths.get(&left_bound).unwrap(); - let x_left : f32 = left_lf_coords.x_start + (nest_shift as f32)*FRAGMENT_PADDING; - let right_lf_coords = lf_x_widths.get(&right_bound).unwrap(); - let x_right : f32 = (right_lf_coords.x_start + right_lf_coords.x_span_outer) - (nest_shift as f32)*FRAGMENT_PADDING; + match (lf_x_widths.get(&left_bound), lf_x_widths.get(&right_bound)) { + (Some(left_lf_coords),Some(right_lf_coords)) => { + let x_left : f32 = left_lf_coords.x_start + (nest_shift as f32)*FRAGMENT_PADDING; + let x_right : f32 = (right_lf_coords.x_start + right_lf_coords.x_span_outer) - (nest_shift as f32)*FRAGMENT_PADDING; - let mut y_coords : Vec = y_drafts.into_iter().map(|y| get_y_pos_from_yshift(y) ).collect::< Vec >(); - let y_start : f32 = y_coords.remove(0); - let y_end : f32 = y_coords.pop().unwrap();// - (nest_shift as f32)*FRAGMENT_PADDING; - draw_line_segment_mut(image, - (x_left, y_start), - (x_left, y_end), - Rgb(HCP_Black)); - draw_line_segment_mut(image, - (x_right, y_start), - (x_right, y_end), - Rgb(HCP_Black)); - draw_line_segment_mut(image, - (x_left, y_start), - (x_right, y_start), - Rgb(HCP_Black)); - draw_line_segment_mut(image, - (x_left, y_end), - (x_right, y_end), - Rgb(HCP_Black)); - for y_coord in y_coords { - draw_line_segment_mut(image, - (x_left, y_coord), - (x_right, y_coord), - Rgb(HCP_Black)); - } - let font = Font::try_from_bytes(HIBOU_GRAPHIC_FONT).unwrap(); + let mut y_coords : Vec = y_drafts.into_iter().map(|y| get_y_pos_from_yshift(y) ).collect::< Vec >(); + let y_start : f32 = y_coords.remove(0); + let y_end : f32 = y_coords.pop().unwrap();// - (nest_shift as f32)*FRAGMENT_PADDING; + draw_line_segment_mut(image, + (x_left, y_start), + (x_left, y_end), + Rgb(HCP_Black)); + draw_line_segment_mut(image, + (x_right, y_start), + (x_right, y_end), + Rgb(HCP_Black)); + draw_line_segment_mut(image, + (x_left, y_start), + (x_right, y_start), + Rgb(HCP_Black)); + draw_line_segment_mut(image, + (x_left, y_end), + (x_right, y_end), + Rgb(HCP_Black)); + for y_coord in y_coords { + draw_line_segment_mut(image, + (x_left, y_coord), + (x_right, y_coord), + Rgb(HCP_Black)); + } + let font = Font::try_from_bytes(HIBOU_GRAPHIC_FONT).unwrap(); - let scale = Scale { x: FONT_WIDTH, y: FONT_HEIGHT }; - draw_colored_text(image,&label,x_left+FRAGMENT_TITLE_MARGIN,y_start + VERTICAL_SIZE); + let scale = Scale { x: FONT_WIDTH, y: FONT_HEIGHT }; + draw_colored_text(image,&label,x_left+FRAGMENT_TITLE_MARGIN,y_start + VERTICAL_SIZE); + }, + _ => {} + } } diff --git a/src/output/rendering/custom_draw/seqdiag/img_frame.rs b/src/io/output/draw_interactions/as_sd/interaction_repr/img_frame.rs similarity index 88% rename from src/output/rendering/custom_draw/seqdiag/img_frame.rs rename to src/io/output/draw_interactions/as_sd/interaction_repr/img_frame.rs index 4a013a9..d3ca3a0 100644 --- a/src/output/rendering/custom_draw/seqdiag/img_frame.rs +++ b/src/io/output/draw_interactions/as_sd/interaction_repr/img_frame.rs @@ -27,11 +27,11 @@ use imageproc::rect::Rect; use rusttype::{Font, Scale}; use crate::core::general_context::GeneralContext; -use crate::output::rendering::colored_text::ttp::TextToPrint; -use crate::output::rendering::custom_draw::seqdiag::lf_coords::DrawingLifelineCoords; -use crate::output::rendering::custom_draw::utils::colored_text::draw_colored_text; -use crate::output::rendering::hibou_color_palette::*; -use crate::output::rendering::sd_drawing_conf::*; +use crate::io::output::draw_commons::colored_text::draw_ttp::draw_colored_text; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::*; +use crate::io::output::draw_commons::sd_drawing_conf::*; +use crate::io::output::draw_interactions::as_sd::util::lf_coords::DrawingLifelineCoords; // ********** diff --git a/src/output/rendering/custom_draw/seqdiag/interaction.rs b/src/io/output/draw_interactions/as_sd/interaction_repr/interaction.rs similarity index 77% rename from src/output/rendering/custom_draw/seqdiag/interaction.rs rename to src/io/output/draw_interactions/as_sd/interaction_repr/interaction.rs index 08cd659..559c6e4 100644 --- a/src/output/rendering/custom_draw/seqdiag/interaction.rs +++ b/src/io/output/draw_interactions/as_sd/interaction_repr/interaction.rs @@ -16,25 +16,21 @@ limitations under the License. use std::collections::HashMap; -use std::path::Path; use image::RgbImage; use crate::core::general_context::GeneralContext; use crate::core::language::involve::involves::InvolvesLifelines; -use crate::core::language::syntax::interaction::*; -use crate::output::rendering::custom_draw::seqdiag::dimensions_tools::*; -use crate::output::rendering::custom_draw::seqdiag::img_content::*; -use crate::output::rendering::custom_draw::seqdiag::img_frame::*; -use crate::output::rendering::custom_draw::seqdiag::lf_coords::DrawingLifelineCoords; -use crate::output::rendering::sd_drawing_conf::*; +use crate::core::language::syntax::interaction::Interaction; +use crate::io::output::draw_commons::sd_drawing_conf::*; +use crate::io::output::draw_interactions::as_sd::interaction_repr::img_content::draw_interaction_rec; +use crate::io::output::draw_interactions::as_sd::interaction_repr::img_frame::{draw_frame, draw_lifelines}; +use crate::io::output::draw_interactions::as_sd::util::dimensions_tools::get_interaction_max_yshift; +use crate::io::output::draw_interactions::as_sd::util::lf_coords::DrawingLifelineCoords; -// ********** -pub fn draw_interaction(gen_ctx : &GeneralContext, - path_str : &String, - interaction : &Interaction) { - let path = Path::new( path_str ); +pub fn make_interaction_image(gen_ctx : &GeneralContext, + interaction : &Interaction) -> RgbImage { // *** let mut lf_x_widths : HashMap = HashMap::new(); let mut current_x : f32 = MARGIN; @@ -71,5 +67,5 @@ pub fn draw_interaction(gen_ctx : &GeneralContext, let mut yshift : u32 = 3; draw_interaction_rec(&mut image, gen_ctx, interaction, &lf_x_widths, gen_ctx.get_lf_num(), &mut nest_shift, &mut yshift); // *** - image.save(path).unwrap(); + return image; } \ No newline at end of file diff --git a/src/output/commons/textual_representation/mod.rs b/src/io/output/draw_interactions/as_sd/interaction_repr/mod.rs similarity index 91% rename from src/output/commons/textual_representation/mod.rs rename to src/io/output/draw_interactions/as_sd/interaction_repr/mod.rs index f601a2e..ea370dc 100644 --- a/src/output/commons/textual_representation/mod.rs +++ b/src/io/output/draw_interactions/as_sd/interaction_repr/mod.rs @@ -14,7 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. */ - -pub mod position; -pub mod trace; -pub mod model; +mod img_content; +mod img_frame; +pub mod interaction; \ No newline at end of file diff --git a/src/io/output/draw_interactions/as_sd/interface.rs b/src/io/output/draw_interactions/as_sd/interface.rs new file mode 100644 index 0000000..0d23483 --- /dev/null +++ b/src/io/output/draw_interactions/as_sd/interface.rs @@ -0,0 +1,37 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use std::path::PathBuf; +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::interaction::Interaction; +use crate::io::output::draw_interactions::as_sd::interaction_repr::interaction::make_interaction_image; + + +pub fn draw_int_as_sd(gen_ctx : &GeneralContext, + interaction : &Interaction, + temp_folder : &String, + parent_folder : &String, + output_file_name : &String) { + // *** + let output_file_name = format!("{:}.png", output_file_name); + let output_path : PathBuf = [parent_folder, &output_file_name].iter().collect(); + let image = make_interaction_image(gen_ctx,interaction); + image.save(output_path.as_path()); +} + + + diff --git a/src/output/rendering/custom_draw/term/mod.rs b/src/io/output/draw_interactions/as_sd/mod.rs similarity index 93% rename from src/output/rendering/custom_draw/term/mod.rs rename to src/io/output/draw_interactions/as_sd/mod.rs index 40b8553..388f8fa 100644 --- a/src/output/rendering/custom_draw/term/mod.rs +++ b/src/io/output/draw_interactions/as_sd/mod.rs @@ -14,7 +14,11 @@ See the License for the specific language governing permissions and limitations under the License. */ -mod util; + mod action_repr; -mod term_repr; -pub mod term_repr_out; \ No newline at end of file +mod interaction_repr; +mod util; + +pub mod interface; + + diff --git a/src/output/rendering/custom_draw/utils/arrow_heads.rs b/src/io/output/draw_interactions/as_sd/util/arrow_heads.rs similarity index 98% rename from src/output/rendering/custom_draw/utils/arrow_heads.rs rename to src/io/output/draw_interactions/as_sd/util/arrow_heads.rs index 7806f8d..73ba04f 100644 --- a/src/output/rendering/custom_draw/utils/arrow_heads.rs +++ b/src/io/output/draw_interactions/as_sd/util/arrow_heads.rs @@ -19,7 +19,7 @@ use image::{Rgb, RgbImage}; use imageproc::drawing::draw_line_segment_mut; use imageproc::drawing::draw_cubic_bezier_curve_mut; -use crate::output::rendering::sd_drawing_conf::ARROW_HEAD_LENGTH; +use crate::io::output::draw_commons::sd_drawing_conf::ARROW_HEAD_LENGTH; // ********** diff --git a/src/output/rendering/custom_draw/seqdiag/dimensions_tools.rs b/src/io/output/draw_interactions/as_sd/util/dimensions_tools.rs similarity index 98% rename from src/output/rendering/custom_draw/seqdiag/dimensions_tools.rs rename to src/io/output/draw_interactions/as_sd/util/dimensions_tools.rs index 17afaeb..c475833 100644 --- a/src/output/rendering/custom_draw/seqdiag/dimensions_tools.rs +++ b/src/io/output/draw_interactions/as_sd/util/dimensions_tools.rs @@ -17,7 +17,7 @@ limitations under the License. use crate::core::language::syntax::interaction::Interaction; use crate::core::language::syntax::util::get_recursive_frag::*; -use crate::output::rendering::sd_drawing_conf::*; +use crate::io::output::draw_commons::sd_drawing_conf::*; pub fn get_interaction_max_yshift(interaction : &Interaction) -> usize { let mut cpt = 4; diff --git a/src/output/rendering/custom_draw/seqdiag/lf_coords.rs b/src/io/output/draw_interactions/as_sd/util/lf_coords.rs similarity index 100% rename from src/output/rendering/custom_draw/seqdiag/lf_coords.rs rename to src/io/output/draw_interactions/as_sd/util/lf_coords.rs diff --git a/src/io/output/draw_interactions/as_sd/util/mod.rs b/src/io/output/draw_interactions/as_sd/util/mod.rs new file mode 100644 index 0000000..8805763 --- /dev/null +++ b/src/io/output/draw_interactions/as_sd/util/mod.rs @@ -0,0 +1,19 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +pub mod arrow_heads; +pub mod lf_coords; +pub mod dimensions_tools; \ No newline at end of file diff --git a/src/io/output/draw_interactions/as_term/action_repr/emission.rs b/src/io/output/draw_interactions/as_term/action_repr/emission.rs new file mode 100644 index 0000000..94e3fe0 --- /dev/null +++ b/src/io/output/draw_interactions/as_term/action_repr/emission.rs @@ -0,0 +1,56 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::action::{CommunicationSynchronicity, EmissionAction, EmissionTargetRef}; +use crate::io::textual_convention::{SYNTAX_EMISSION, SYNTAX_EMISSION_SYNCHRONOUS}; + + +pub fn emission_as_gv_label(gen_ctx : &GeneralContext, + em_act : &EmissionAction) -> String { + // *** + let ms_name = gen_ctx.get_ms_name(em_act.ms_id).unwrap(); + let lf_name = gen_ctx.get_lf_name(em_act.origin_lf_id).unwrap(); + // *** + let mut targ_names : Vec = Vec::new(); + for targ_ref in &em_act.targets { + match targ_ref { + EmissionTargetRef::Lifeline(tar_lf_id) => { + targ_names.push( gen_ctx.get_lf_name(*tar_lf_id).unwrap() ); + }, + EmissionTargetRef::Gate(tar_gt_id) => { + targ_names.push( gen_ctx.get_gt_name(*tar_gt_id).unwrap() ); + } + } + } + // *** + let emission_symb : &'static str; + match em_act.synchronicity { + CommunicationSynchronicity::Asynchronous => { + emission_symb = SYNTAX_EMISSION; + }, + CommunicationSynchronicity::Synchronous => { + emission_symb = SYNTAX_EMISSION_SYNCHRONOUS; + } + } + // *** + if targ_names.len() == 0 { + return format!("{}{}{}", &lf_name, emission_symb, &ms_name); + } else { + return format!("{}{}{}({})", &lf_name, emission_symb, &ms_name, &targ_names.join(",")); + } +} \ No newline at end of file diff --git a/src/io/output/draw_interactions/as_term/action_repr/mod.rs b/src/io/output/draw_interactions/as_term/action_repr/mod.rs new file mode 100644 index 0000000..ece860c --- /dev/null +++ b/src/io/output/draw_interactions/as_term/action_repr/mod.rs @@ -0,0 +1,19 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +pub mod emission; +pub mod reception; \ No newline at end of file diff --git a/src/io/output/draw_interactions/as_term/action_repr/reception.rs b/src/io/output/draw_interactions/as_term/action_repr/reception.rs new file mode 100644 index 0000000..95a6d5e --- /dev/null +++ b/src/io/output/draw_interactions/as_term/action_repr/reception.rs @@ -0,0 +1,62 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::action::{CommunicationSynchronicity, ReceptionAction}; +use crate::io::textual_convention::{SYNTAX_RECEPTION, SYNTAX_RECEPTION_SYNCHRONOUS}; + + +pub fn reception_as_gv_label (gen_ctx : &GeneralContext, + rc_act : &ReceptionAction) -> String { + // *** + let ms_name = gen_ctx.get_ms_name(rc_act.ms_id).unwrap(); + // *** + let mut targ_names : Vec = Vec::new(); + for rcp_lf_id in &rc_act.recipients { + targ_names.push( gen_ctx.get_lf_name(*rcp_lf_id).unwrap() ); + } + // *** + let reception_symb : &'static str; + match rc_act.synchronicity { + CommunicationSynchronicity::Asynchronous => { + reception_symb = SYNTAX_RECEPTION; + }, + CommunicationSynchronicity::Synchronous => { + reception_symb = SYNTAX_RECEPTION_SYNCHRONOUS; + } + } + // *** + let rcp_gate_str : String; + match rc_act.origin_gt_id { + None => { + rcp_gate_str = "".to_string(); + }, + Some(orig_gt_id) => { + rcp_gate_str = format!("[{:}]", gen_ctx.get_gt_name(orig_gt_id).unwrap()); + } + } + // *** + let rcp_num = targ_names.len(); + if rcp_num == 1 { + return format!("{}{}{}{}", targ_names.get(0).unwrap(), reception_symb, &rcp_gate_str, &ms_name); + } else if rcp_num > 1 { + return format!("({}){}{}{}", &targ_names.join(","), reception_symb, &rcp_gate_str, &ms_name); + } else { + panic!(); + } +} + diff --git a/src/io/output/draw_interactions/as_term/draw_as_term_TODO.txt b/src/io/output/draw_interactions/as_term/draw_as_term_TODO.txt new file mode 100644 index 0000000..e81607a --- /dev/null +++ b/src/io/output/draw_interactions/as_term/draw_as_term_TODO.txt @@ -0,0 +1,10 @@ + +In order to have a more homogeneous and detail graphical representation, +write the term with the same Font and color scheme as the interaction diagrams + +To do so: +- create a png for each node with draw_colored_text or whatev +- compose with dot, do not draw node frames +- use nodesep=0 and ranksep=x on the graph for managing spacing and have a better handling of layout + + diff --git a/src/output/to_hfiles/mod.rs b/src/io/output/draw_interactions/as_term/interaction_repr/mod.rs similarity index 95% rename from src/output/to_hfiles/mod.rs rename to src/io/output/draw_interactions/as_term/interaction_repr/mod.rs index a2e4009..4fa8be1 100644 --- a/src/output/to_hfiles/mod.rs +++ b/src/io/output/draw_interactions/as_term/interaction_repr/mod.rs @@ -14,5 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. */ -pub mod multitrace_to_htf; + +pub mod repr; diff --git a/src/output/rendering/custom_draw/term/term_repr.rs b/src/io/output/draw_interactions/as_term/interaction_repr/repr.rs similarity index 67% rename from src/output/rendering/custom_draw/term/term_repr.rs rename to src/io/output/draw_interactions/as_term/interaction_repr/repr.rs index 6a17ef1..8c7bfdb 100644 --- a/src/output/rendering/custom_draw/term/term_repr.rs +++ b/src/io/output/draw_interactions/as_term/interaction_repr/repr.rs @@ -17,43 +17,31 @@ limitations under the License. use crate::core::general_context::GeneralContext; use crate::core::language::syntax::interaction::{Interaction, LoopKind}; use crate::core::language::position::position::Position; -use crate::output::rendering::custom_draw::term::action_repr::{emission_repr, reception_repr}; -use crate::output::rendering::custom_draw::term::util::position_to_id; -use crate::output::rendering::graphviz::common::*; -use crate::output::rendering::graphviz::edge_style::*; -use crate::output::rendering::graphviz::graph::*; -use crate::output::rendering::graphviz::node_style::*; -use crate::output::commons::textual_convention::*; +use crate::io::output::draw_interactions::as_term::action_repr::emission::{emission_as_gv_label}; +use crate::io::output::draw_interactions::as_term::action_repr::reception::{reception_as_gv_label}; +use crate::io::output::graphviz::colors::DotTranslatable; +use crate::io::output::graphviz::edge::edge::GraphVizEdge; +use crate::io::output::graphviz::edge::style::{GraphvizEdgeStyleItem, GvArrowHeadStyle}; +use crate::io::output::graphviz::node::node::GraphVizNode; +use crate::io::output::graphviz::node::style::{GraphvizNodeStyle, GraphvizNodeStyleItem, GvNodeShape}; +use crate::io::textual_convention::{SYNTAX_ALT, SYNTAX_LOOP_H, SYNTAX_LOOP_P, SYNTAX_LOOP_S, SYNTAX_LOOP_W, SYNTAX_PAR, SYNTAX_SEQ, SYNTAX_STRICT}; -pub fn interaction_repr(interaction : &Interaction, - gen_ctx : &GeneralContext, - name : &String, - as_subgraph : bool) -> String { + +pub fn interaction_gv_repr(gen_ctx : &GeneralContext, + interaction : &Interaction) -> String { let mut repr : String = String::new(); - if as_subgraph { - repr.push_str( &format!("subgraph cluster_{} {{\n", name) ); - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - node_gv_options.push( GraphvizNodeStyleItem::Style(vec![GvNodeStyleKind::Filled]) ); - node_gv_options.push( GraphvizNodeStyleItem::Label("".to_string()) ); - let gv_node = GraphVizNode{id : format!("{}_anchor",name), style : node_gv_options}; - repr.push_str( &gv_node.to_dot_string() ); - repr.push_str("\n"); - } else { - repr.push_str( &format!("digraph {} {{\n", name) ); - } - interaction_repr_rec(&mut repr, interaction, gen_ctx, name, Position::Epsilon(None)); + repr.push_str( "digraph G {\n" ); + interaction_gv_repr_rec(&mut repr, gen_ctx, interaction,Position::Epsilon(None)); repr.push_str( "}\n" ); return repr; } -fn interaction_repr_rec(to_write : &mut String, - interaction : &Interaction, +fn interaction_gv_repr_rec(to_write : &mut String, gen_ctx : &GeneralContext, - interaction_name : &String, + interaction : &Interaction, current_pos : Position) -> String { - let node_name = format!("{}p{}",interaction_name,position_to_id(¤t_pos)); + let node_name = format!("p{}",current_pos.to_string()); match interaction { &Interaction::Empty => { let mut node_gv_options : GraphvizNodeStyle = Vec::new(); @@ -64,16 +52,26 @@ fn interaction_repr_rec(to_write : &mut String, to_write.push_str("\n"); }, &Interaction::Emission(ref em_act) => { - emission_repr(to_write,em_act,gen_ctx,interaction_name,current_pos); + let mut node_gv_options : GraphvizNodeStyle = Vec::new(); + node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::PlainText) ); + node_gv_options.push( GraphvizNodeStyleItem::Label( emission_as_gv_label(gen_ctx,em_act) ) ); + let gv_node = GraphVizNode{id : node_name.clone(), style : node_gv_options}; + to_write.push_str( &gv_node.to_dot_string() ); + to_write.push_str("\n"); }, &Interaction::Reception(ref rc_act) => { - reception_repr(to_write,rc_act,gen_ctx,interaction_name,current_pos); + let mut node_gv_options : GraphvizNodeStyle = Vec::new(); + node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::PlainText) ); + node_gv_options.push( GraphvizNodeStyleItem::Label( reception_as_gv_label(gen_ctx,rc_act) ) ); + let gv_node = GraphVizNode{id : node_name.clone(), style : node_gv_options}; + to_write.push_str( &gv_node.to_dot_string() ); + to_write.push_str("\n"); }, &Interaction::Strict(ref i1, ref i2) => { - repr_binary_operator(to_write, i1, i2, SYNTAX_STRICT, gen_ctx, interaction_name, current_pos); + repr_binary_operator(to_write, gen_ctx,i1, i2, SYNTAX_STRICT, current_pos); }, &Interaction::Seq(ref i1, ref i2) => { - repr_binary_operator(to_write, i1, i2, SYNTAX_SEQ, gen_ctx, interaction_name, current_pos); + repr_binary_operator(to_write, gen_ctx, i1, i2, SYNTAX_SEQ, current_pos); }, &Interaction::CoReg(ref cr, ref i1, ref i2) => { let mut op_label = "coreg(".to_string(); @@ -87,13 +85,13 @@ fn interaction_repr_rec(to_write : &mut String, } } op_label.push_str(")"); - repr_binary_operator(to_write, i1, i2, &op_label, gen_ctx, interaction_name, current_pos); + repr_binary_operator(to_write, gen_ctx, i1, i2, &op_label, current_pos); }, &Interaction::Par(ref i1, ref i2) => { - repr_binary_operator(to_write, i1, i2, SYNTAX_PAR, gen_ctx, interaction_name, current_pos); + repr_binary_operator(to_write, gen_ctx, i1, i2, SYNTAX_PAR, current_pos); }, &Interaction::Alt(ref i1, ref i2) => { - repr_binary_operator(to_write, i1, i2, SYNTAX_ALT, gen_ctx, interaction_name, current_pos); + repr_binary_operator(to_write, gen_ctx, i1, i2, SYNTAX_ALT, current_pos); }, &Interaction::Loop(ref lp_kind, ref i1) => { // the parent loop node @@ -121,7 +119,7 @@ fn interaction_repr_rec(to_write : &mut String, // then the left sub-interaction { let left_position = Position::Left(Box::new(current_pos.clone())); - let child_node_name = interaction_repr_rec(to_write,i1,gen_ctx,interaction_name,left_position); + let child_node_name = interaction_gv_repr_rec(to_write,gen_ctx,i1,left_position); let gv_edge = GraphVizEdge{origin_id : node_name.clone(), target_id : child_node_name, style : vec![ GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::NoArrow )]}; @@ -130,20 +128,19 @@ fn interaction_repr_rec(to_write : &mut String, } }, &Interaction::And(ref i1, ref i2) => { - repr_binary_operator(to_write, i1, i2, "and", gen_ctx, interaction_name, current_pos); + repr_binary_operator(to_write, gen_ctx, i1, i2, "and", current_pos); } } return node_name; } fn repr_binary_operator(to_write : &mut String, + gen_ctx : &GeneralContext, i1 : &Interaction, i2 : &Interaction, operator_label : &str, - gen_ctx : &GeneralContext, - interaction_name : &String, current_pos : Position) { - let node_name = format!("{}p{}",interaction_name,position_to_id(¤t_pos)); + let node_name = format!("p{}",current_pos.to_string()); // the parent strict node { let mut strict_node_gv_options : GraphvizNodeStyle = Vec::new(); @@ -156,7 +153,7 @@ fn repr_binary_operator(to_write : &mut String, // then the left sub-interaction { let left_position = Position::Left(Box::new(current_pos.clone())); - let child_node_name = interaction_repr_rec(to_write,i1,gen_ctx,interaction_name,left_position.clone()); + let child_node_name = interaction_gv_repr_rec(to_write,gen_ctx,i1,left_position.clone()); let gv_edge = GraphVizEdge{origin_id : node_name.clone(), target_id : child_node_name, style : vec![ GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::NoArrow )]}; @@ -166,7 +163,7 @@ fn repr_binary_operator(to_write : &mut String, // then the right sub-interaction { let right_position = Position::Right(Box::new(current_pos.clone())); - let child_node_name = interaction_repr_rec(to_write,i2,gen_ctx,interaction_name,right_position.clone()); + let child_node_name = interaction_gv_repr_rec(to_write,gen_ctx,i2,right_position.clone()); let gv_edge = GraphVizEdge{origin_id : node_name, target_id : child_node_name, style : vec![ GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::NoArrow )]}; diff --git a/src/io/output/draw_interactions/as_term/interface.rs b/src/io/output/draw_interactions/as_term/interface.rs new file mode 100644 index 0000000..a69f32d --- /dev/null +++ b/src/io/output/draw_interactions/as_term/interface.rs @@ -0,0 +1,60 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use std::fs; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; +use std::process::Command; + +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::interaction::Interaction; +use crate::io::output::draw_interactions::as_term::interaction_repr::repr::interaction_gv_repr; + + + + +pub fn draw_int_as_term(gen_ctx : &GeneralContext, + interaction : &Interaction, + temp_folder : &String, + parent_folder : &String, + output_file_name : &String) { + // *** + // creates directories if not exist + fs::create_dir_all(&temp_folder).unwrap(); + // *** + let temp_file_name = format!("{:}.dot", output_file_name); + let temp_path : PathBuf = [temp_folder, &temp_file_name].iter().collect(); + let mut file = File::create(temp_path.as_path()).unwrap(); + file.write( interaction_gv_repr(gen_ctx,interaction).as_bytes() ); + // *** + let output_file_name = format!("{:}.png", output_file_name); + let output_path : PathBuf = [parent_folder, &output_file_name].iter().collect(); + // *** + let status = Command::new("dot") + .arg("-Tpng") + .arg(temp_path.as_path()) + .arg("-o") + .arg(output_path.as_path()) + .output(); +} + + + + + + diff --git a/src/io/output/draw_interactions/as_term/mod.rs b/src/io/output/draw_interactions/as_term/mod.rs new file mode 100644 index 0000000..77cc439 --- /dev/null +++ b/src/io/output/draw_interactions/as_term/mod.rs @@ -0,0 +1,20 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +mod action_repr; +mod interaction_repr; +pub mod interface; \ No newline at end of file diff --git a/src/io/output/draw_interactions/interface.rs b/src/io/output/draw_interactions/interface.rs new file mode 100644 index 0000000..9a42bf5 --- /dev/null +++ b/src/io/output/draw_interactions/interface.rs @@ -0,0 +1,46 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::interaction::Interaction; +use crate::io::output::draw_interactions::as_sd::interface::draw_int_as_sd; +use crate::io::output::draw_interactions::as_term::interface::draw_int_as_term; + + + + +pub enum InteractionGraphicalRepresentation { + AsSequenceDiagram, + AsTerm +} + +pub fn draw_interaction(gen_ctx : &GeneralContext, + int : &Interaction, + repr : &InteractionGraphicalRepresentation, + temp_folder : &String, + parent_folder : &String, + output_file_name : &String) { + match repr { + InteractionGraphicalRepresentation::AsSequenceDiagram => { + draw_int_as_sd(gen_ctx,int,temp_folder,parent_folder,output_file_name); + }, + InteractionGraphicalRepresentation::AsTerm => { + draw_int_as_term(gen_ctx,int,temp_folder,parent_folder,output_file_name); + } + } +} \ No newline at end of file diff --git a/src/output/commons/textual_representation/trace/mod.rs b/src/io/output/draw_interactions/mod.rs similarity index 93% rename from src/output/commons/textual_representation/trace/mod.rs rename to src/io/output/draw_interactions/mod.rs index e49f2af..b0e69b2 100644 --- a/src/output/commons/textual_representation/trace/mod.rs +++ b/src/io/output/draw_interactions/mod.rs @@ -14,8 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ +mod as_term; +mod as_sd; +pub mod interface; -pub mod trace_action; -pub mod multi_trace; diff --git a/src/output/rendering/custom_draw/multitrace/ext_mu.rs b/src/io/output/draw_traces/implem/ext_mu.rs similarity index 91% rename from src/output/rendering/custom_draw/multitrace/ext_mu.rs rename to src/io/output/draw_traces/implem/ext_mu.rs index 62eb9c4..0d73efa 100644 --- a/src/output/rendering/custom_draw/multitrace/ext_mu.rs +++ b/src/io/output/draw_traces/implem/ext_mu.rs @@ -24,9 +24,10 @@ use crate::core::execution::trace::multitrace::{MultiTrace, Trace}; use crate::core::general_context::GeneralContext; use crate::core::execution::trace::trace::TraceAction; -use crate::output::rendering::colored_text::trace_action::diagram_repr_trace_actions; -use crate::output::rendering::colored_text::ttp::TextToPrint; -use crate::output::rendering::hibou_color_palette::*; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::{HC_Grammar_Symbol, HC_Lifeline, HCP_Black, HCP_LightGray}; +use crate::io::output::draw_traces::implem::trace_action::diagram_repr_trace_actions; +use crate::io::output::draw_commons::hibou_color_palette::*; use crate::process::ana_proc::logic::flags::{MultiTraceAnalysisFlags, TraceAnalysisFlags}; fn extract_texts_on_canal_hidden(gen_ctx : &GeneralContext, @@ -169,15 +170,3 @@ fn add_trace_text_to_canal<'a>(gen_ctx: &GeneralContext, } } -/* -fn add_trace_text_to_canal<'a>(gen_ctx: &GeneralContext, - canal_text : &mut Vec, - rem_actions : &[HashSet]) { - //rem_actions : &mut impl Iterator> ) { - while let Some(actions) = rem_actions.next() { - canal_text.append(&mut diagram_repr_trace_actions(actions,gen_ctx)); - if !rem_actions.peekable().peek().is_none() { - canal_text.push( TextToPrint{text:".".to_string(), color:Rgb(HC_Grammar_Symbol)} ); - } - } -}*/ \ No newline at end of file diff --git a/src/output/rendering/colored_text/mod.rs b/src/io/output/draw_traces/implem/mod.rs similarity index 97% rename from src/output/rendering/colored_text/mod.rs rename to src/io/output/draw_traces/implem/mod.rs index 6809bde..b0eb97d 100644 --- a/src/output/rendering/colored_text/mod.rs +++ b/src/io/output/draw_traces/implem/mod.rs @@ -14,6 +14,5 @@ See the License for the specific language governing permissions and limitations under the License. */ - -pub mod ttp; pub mod trace_action; +pub mod ext_mu; \ No newline at end of file diff --git a/src/output/rendering/colored_text/trace_action.rs b/src/io/output/draw_traces/implem/trace_action.rs similarity index 94% rename from src/output/rendering/colored_text/trace_action.rs rename to src/io/output/draw_traces/implem/trace_action.rs index 20f514a..921f3ea 100644 --- a/src/output/rendering/colored_text/trace_action.rs +++ b/src/io/output/draw_traces/implem/trace_action.rs @@ -21,9 +21,9 @@ use itertools::Itertools; use crate::core::general_context::GeneralContext; use crate::core::execution::trace::trace::{TraceAction, TraceActionKind}; -use crate::output::rendering::colored_text::ttp::TextToPrint; -use crate::output::rendering::hibou_color_palette::*; -use crate::output::commons::textual_convention::*; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::*; +use crate::io::textual_convention::*; diff --git a/src/output/rendering/custom_draw/multitrace/draw_mu.rs b/src/io/output/draw_traces/interface.rs similarity index 63% rename from src/output/rendering/custom_draw/multitrace/draw_mu.rs rename to src/io/output/draw_traces/interface.rs index e18ef5d..3464730 100644 --- a/src/output/rendering/custom_draw/multitrace/draw_mu.rs +++ b/src/io/output/draw_traces/interface.rs @@ -16,26 +16,29 @@ limitations under the License. - -use std::path::Path; +use std::path::PathBuf; use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::MultiTrace; use crate::core::general_context::GeneralContext; -use crate::output::rendering::colored_text::ttp::TextToPrint; -use crate::output::rendering::custom_draw::multitrace::ext_mu::extract_texts_on_multi_trace; -use crate::output::rendering::custom_draw::utils::colored_text::{DrawnColoredTextAlignment, new_image_with_colored_text}; -use crate::output::rendering::sd_drawing_conf::{FONT_WIDTH, MARGIN, VERTICAL_SIZE}; +use crate::io::output::draw_commons::colored_text::draw_ttp::{DrawnColoredTextAlignment, new_image_with_colored_text}; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::sd_drawing_conf::{FONT_WIDTH, MARGIN, VERTICAL_SIZE}; +use crate::io::output::draw_traces::implem::ext_mu::extract_texts_on_multi_trace; use crate::process::ana_proc::logic::flags::MultiTraceAnalysisFlags; + pub fn draw_multitrace(gen_ctx : &GeneralContext, co_localizations : &CoLocalizations, - path_str : &String, - multi_trace : &MultiTrace, - flags : &MultiTraceAnalysisFlags, - is_simulation : bool, - sim_crit_loop : bool, - sim_crit_act : bool) { - let path = Path::new( path_str ); + multi_trace : &MultiTrace, + flags : &MultiTraceAnalysisFlags, + is_simulation : bool, + sim_crit_loop : bool, + sim_crit_act : bool, + parent_folder : &String, + output_file_name : &String) { + // *** + let output_file_name = format!("{:}.png", output_file_name); + let output_path : PathBuf = [parent_folder, &output_file_name].iter().collect(); // *** let mut text_lines : Vec> = extract_texts_on_multi_trace(gen_ctx, co_localizations, @@ -50,5 +53,5 @@ pub fn draw_multitrace(gen_ctx : &GeneralContext, let img_width : f32 = 2.0*MARGIN + (max_x_shift as f32)*FONT_WIDTH/2.0; let img_height : f32 = MARGIN + (text_lines.len() as f32)*(MARGIN + VERTICAL_SIZE); // *** - new_image_with_colored_text(path,&DrawnColoredTextAlignment::Left, img_width,img_height,text_lines) + new_image_with_colored_text(output_path.as_path(),&DrawnColoredTextAlignment::Left, img_width,img_height,text_lines) } \ No newline at end of file diff --git a/src/io/output/draw_traces/mod.rs b/src/io/output/draw_traces/mod.rs new file mode 100644 index 0000000..5fbd54c --- /dev/null +++ b/src/io/output/draw_traces/mod.rs @@ -0,0 +1,20 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +pub(in crate::io::output) mod implem; +pub mod interface; + diff --git a/src/output/rendering/custom_draw/transition/draw_firing.rs b/src/io/output/draw_transitions/draw_firing.rs similarity index 76% rename from src/output/rendering/custom_draw/transition/draw_firing.rs rename to src/io/output/draw_transitions/draw_firing.rs index 8d9c104..9f82b94 100644 --- a/src/output/rendering/custom_draw/transition/draw_firing.rs +++ b/src/io/output/draw_transitions/draw_firing.rs @@ -25,35 +25,34 @@ use crate::core::colocalizations::CoLocalizations; use crate::core::general_context::GeneralContext; use crate::core::execution::trace::trace::TraceAction; use crate::core::language::position::position::Position; -use crate::output::commons::textual_representation::position::position_to_text; -use crate::output::rendering::colored_text::trace_action::diagram_repr_trace_action; -use crate::output::rendering::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::colored_text::draw_ttp::{DrawnColoredTextAlignment, new_image_with_colored_text}; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; use crate::process::ana_proc::interface::step::SimulationStepKind; -use crate::output::rendering::custom_draw::utils::colored_text::{DrawnColoredTextAlignment, new_image_with_colored_text}; -use crate::output::rendering::hibou_color_palette::*; -use crate::output::rendering::sd_drawing_conf::*; +use crate::io::output::draw_commons::hibou_color_palette::*; +use crate::io::output::draw_commons::sd_drawing_conf::*; +use crate::io::output::draw_traces::implem::trace_action::diagram_repr_trace_action; // ********** -pub fn draw_firing_simple(path_str : &String, +pub fn draw_firing_simple(path : &Path, gen_ctx : &GeneralContext, action_position : &Position, executed_actions : &HashSet) { let mut text_lines : Vec> = Vec::new(); // *** - draw_firing_finalize(path_str,text_lines, gen_ctx, action_position, executed_actions); + draw_firing_finalize(path,text_lines, gen_ctx, action_position, executed_actions); } -pub fn draw_firing_analysis(path_str : &String, - gen_ctx : &GeneralContext, - co_localizations : &CoLocalizations, - action_position : &Position, - executed_actions : &HashSet, - consu_set : &HashSet, - sim_map : &HashMap) { +pub fn draw_firing_analysis(path : &Path, + gen_ctx : &GeneralContext, + action_position : &Position, + executed_actions : &HashSet, + co_localizations : &CoLocalizations, + consu_set : &HashSet, + sim_map : &HashMap) { // *** let mut text_lines : Vec> = Vec::new(); @@ -82,11 +81,11 @@ pub fn draw_firing_analysis(path_str : &String, text_lines.push( ttp ); } // *** - draw_firing_finalize(path_str,text_lines, gen_ctx, action_position, executed_actions); + draw_firing_finalize(path,text_lines, gen_ctx, action_position, executed_actions); } -fn draw_firing_finalize(path_str : &String, +fn draw_firing_finalize(path : &Path, text_lines : Vec>, gen_ctx : &GeneralContext, action_position : &Position, @@ -99,8 +98,8 @@ fn draw_firing_finalize(path_str : &String, ttp.push( TextToPrint{text:" ".to_string(),color:Rgb(HCP_Black)} ); } // *** - ttp.push( TextToPrint{text:"@p".to_string(),color:Rgb(HCP_StandardPurple)} ); - ttp.push( TextToPrint{text:position_to_text(action_position),color:Rgb(HCP_Black)} ); + ttp.push( TextToPrint{text:"@".to_string(),color:Rgb(HCP_StandardPurple)} ); + ttp.push( TextToPrint{text:action_position.to_string(),color:Rgb(HCP_Black)} ); text_lines.push( ttp ); } // *** @@ -110,7 +109,6 @@ fn draw_firing_finalize(path_str : &String, let img_width : f32 = 2.0*MARGIN + (max_x_shift as f32)*FONT_WIDTH/2.0; let img_height : f32 = MARGIN + (text_lines.len() as f32)*(MARGIN + VERTICAL_SIZE); // *** - let path = Path::new( path_str ); new_image_with_colored_text(path,&DrawnColoredTextAlignment::Center,img_width,img_height,text_lines) } diff --git a/src/output/rendering/custom_draw/transition/draw_hiding.rs b/src/io/output/draw_transitions/draw_hiding.rs similarity index 84% rename from src/output/rendering/custom_draw/transition/draw_hiding.rs rename to src/io/output/draw_transitions/draw_hiding.rs index 322fb27..2101c06 100644 --- a/src/output/rendering/custom_draw/transition/draw_hiding.rs +++ b/src/io/output/draw_transitions/draw_hiding.rs @@ -20,19 +20,18 @@ use std::path::Path; use image::Rgb; use crate::core::general_context::GeneralContext; -use crate::output::rendering::colored_text::ttp::TextToPrint; -use crate::output::rendering::custom_draw::utils::colored_text::{DrawnColoredTextAlignment, new_image_with_colored_text}; -use crate::output::rendering::hibou_color_palette::*; -use crate::output::rendering::sd_drawing_conf::*; +use crate::io::output::draw_commons::colored_text::draw_ttp::{DrawnColoredTextAlignment, new_image_with_colored_text}; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::*; +use crate::io::output::draw_commons::sd_drawing_conf::*; // ********** -pub fn draw_hiding(path_str : &String, +pub fn draw_hiding(path : &Path, gen_ctx : &GeneralContext, lfs_to_hide : &HashSet) { - let path = Path::new( path_str ); // *** let mut text_lines : Vec> = Vec::new(); // *** diff --git a/src/io/output/draw_transitions/draw_string_label.rs b/src/io/output/draw_transitions/draw_string_label.rs new file mode 100644 index 0000000..15dab6a --- /dev/null +++ b/src/io/output/draw_transitions/draw_string_label.rs @@ -0,0 +1,54 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use std::path::Path; + +use image::Rgb; +use crate::core::language::position::position::Position; +use crate::core::transformation::transfokind::InteractionTransformationKind; + +use crate::io::output::draw_commons::colored_text::draw_ttp::{DrawnColoredTextAlignment, new_image_with_colored_text}; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::*; +use crate::io::output::draw_commons::sd_drawing_conf::*; + + +// ********** + + + +pub fn draw_string_label(path : &Path,string_label : String) { + // *** + let mut text_lines : Vec> = Vec::new(); + // *** + { + let mut ttp = Vec::new(); + // *** + ttp.push( TextToPrint{text:string_label,color:Rgb(HCP_Black)} ); + text_lines.push( ttp ); + } + // *** + let line_lens : Vec = text_lines.iter().map(|x| TextToPrint::char_count(x) ).collect(); + let max_x_shift = *line_lens.iter().max().unwrap(); + // *** + let img_width : f32 = 2.0*MARGIN + (max_x_shift as f32)*FONT_WIDTH/2.0; + let img_height : f32 = 2.0*MARGIN + (text_lines.len() as f32)*FONT_HEIGHT/2.0; + // *** + new_image_with_colored_text(path,&DrawnColoredTextAlignment::Center,img_width,img_height,text_lines) +} + + diff --git a/src/io/output/draw_transitions/draw_transformation.rs b/src/io/output/draw_transitions/draw_transformation.rs new file mode 100644 index 0000000..bd3640e --- /dev/null +++ b/src/io/output/draw_transitions/draw_transformation.rs @@ -0,0 +1,58 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use std::path::Path; + +use image::Rgb; +use crate::core::language::position::position::Position; +use crate::core::transformation::transfokind::InteractionTransformationKind; + +use crate::io::output::draw_commons::colored_text::draw_ttp::{DrawnColoredTextAlignment, new_image_with_colored_text}; +use crate::io::output::draw_commons::colored_text::ttp::TextToPrint; +use crate::io::output::draw_commons::hibou_color_palette::*; +use crate::io::output::draw_commons::sd_drawing_conf::*; + + +// ********** + + + +pub fn draw_transformation(path : &Path, + transfo_kind : &InteractionTransformationKind, + position : &Position) { + // *** + let mut text_lines : Vec> = Vec::new(); + // *** + { + let mut ttp = Vec::new(); + // *** + ttp.push( TextToPrint{text:transfo_kind.to_string(),color:Rgb(HCP_Black)} ); + ttp.push( TextToPrint{text:"@".to_string(),color:Rgb(HCP_StandardPurple)} ); + ttp.push( TextToPrint{text:position.to_string(),color:Rgb(HCP_Black)} ); + text_lines.push( ttp ); + } + // *** + let line_lens : Vec = text_lines.iter().map(|x| TextToPrint::char_count(x) ).collect(); + let max_x_shift = *line_lens.iter().max().unwrap(); + // *** + let img_width : f32 = 2.0*MARGIN + (max_x_shift as f32)*FONT_WIDTH/2.0; + let img_height : f32 = 2.0*MARGIN + (text_lines.len() as f32)*FONT_HEIGHT/2.0; + // *** + new_image_with_colored_text(path,&DrawnColoredTextAlignment::Center,img_width,img_height,text_lines) +} + + diff --git a/src/io/output/draw_transitions/mod.rs b/src/io/output/draw_transitions/mod.rs new file mode 100644 index 0000000..37738a8 --- /dev/null +++ b/src/io/output/draw_transitions/mod.rs @@ -0,0 +1,23 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +pub mod draw_firing; +pub mod draw_hiding; +pub mod draw_transformation; +pub mod draw_string_label; + + diff --git a/src/io/output/graphviz/cluster/cluster.rs b/src/io/output/graphviz/cluster/cluster.rs new file mode 100644 index 0000000..7804cba --- /dev/null +++ b/src/io/output/graphviz/cluster/cluster.rs @@ -0,0 +1,64 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + +use crate::io::output::graphviz::colors::DotTranslatable; +use crate::io::output::graphviz::edge::edge::GraphVizEdge; +use crate::io::output::graphviz::node::node::GraphVizNode; +use crate::io::output::graphviz::node::style::GraphvizNodeStyle; + +pub struct GraphVizCluster { + pub id : String, + pub style : GraphvizNodeStyle, + pub nodes : Vec>, + pub edges : Vec +} + +impl GraphVizCluster { + pub fn new(id : String, + style : GraphvizNodeStyle, + nodes : Vec>, + edges : Vec) -> GraphVizCluster { + return GraphVizCluster{id,style,nodes,edges}; + } +} + +impl DotTranslatable for GraphVizCluster { + fn to_dot_string(&self) -> String { + let mut res = String::new(); + res.push_str(&format!("subgraph cluster_{:} {{\n",self.id)); + // *** + for item in &self.style { + res.push_str(&format!("{};\n",item.to_dot_string()) ); + } + // *** + for node in &self.nodes { + res.push_str("\t"); + res.push_str(& node.to_dot_string() ); + res.push_str("\n"); + } + for edge in &self.edges { + res.push_str("\t"); + res.push_str(& edge.to_dot_string() ); + res.push_str("\n"); + } + res.push_str("}"); + return res; + } +} + diff --git a/src/io/output/graphviz/cluster/mod.rs b/src/io/output/graphviz/cluster/mod.rs new file mode 100644 index 0000000..fab4533 --- /dev/null +++ b/src/io/output/graphviz/cluster/mod.rs @@ -0,0 +1,18 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +pub mod cluster; diff --git a/src/output/rendering/graphviz/common.rs b/src/io/output/graphviz/colors.rs similarity index 100% rename from src/output/rendering/graphviz/common.rs rename to src/io/output/graphviz/colors.rs diff --git a/src/io/output/graphviz/edge/edge.rs b/src/io/output/graphviz/edge/edge.rs new file mode 100644 index 0000000..92f4c74 --- /dev/null +++ b/src/io/output/graphviz/edge/edge.rs @@ -0,0 +1,48 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use crate::io::output::graphviz::colors::DotTranslatable; +use crate::io::output::graphviz::edge::style::GraphvizEdgeStyle; + +pub struct GraphVizEdge { + pub origin_id : String, + pub target_id : String, + pub style : GraphvizEdgeStyle +} + +impl GraphVizEdge { + pub fn new(origin_id : String, + target_id : String, + style : GraphvizEdgeStyle) -> GraphVizEdge { + return GraphVizEdge{origin_id,target_id,style}; + } +} + +impl DotTranslatable for GraphVizEdge { + fn to_dot_string(&self) -> String { + let mut res = String::new(); + res.push_str(&(self.origin_id)); + res.push_str("->"); + res.push_str(&(self.target_id)); + res.push_str(& self.style.to_dot_string() ); + res.push_str(";"); + return res; + } +} + + diff --git a/src/io/output/graphviz/edge/mod.rs b/src/io/output/graphviz/edge/mod.rs new file mode 100644 index 0000000..b49a8d9 --- /dev/null +++ b/src/io/output/graphviz/edge/mod.rs @@ -0,0 +1,19 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +pub mod style; +pub mod edge; + diff --git a/src/output/rendering/graphviz/edge_style.rs b/src/io/output/graphviz/edge/style.rs similarity index 98% rename from src/output/rendering/graphviz/edge_style.rs rename to src/io/output/graphviz/edge/style.rs index a135dbb..87210e2 100644 --- a/src/output/rendering/graphviz/edge_style.rs +++ b/src/io/output/graphviz/edge/style.rs @@ -15,7 +15,7 @@ limitations under the License. */ -use crate::output::rendering::graphviz::common::{DotTranslatable,GraphvizColor}; +use crate::io::output::graphviz::colors::{DotTranslatable, GraphvizColor}; pub enum GvArrowHeadFill { diff --git a/src/output/rendering/graphviz/graph.rs b/src/io/output/graphviz/graph.rs similarity index 52% rename from src/output/rendering/graphviz/graph.rs rename to src/io/output/graphviz/graph.rs index a57eac2..8f9a27c 100644 --- a/src/output/rendering/graphviz/graph.rs +++ b/src/io/output/graphviz/graph.rs @@ -15,56 +15,36 @@ limitations under the License. */ -use crate::output::rendering::graphviz::node_style::GraphvizNodeStyle; -use crate::output::rendering::graphviz::edge_style::GraphvizEdgeStyle; -use crate::output::rendering::graphviz::common::DotTranslatable; +use crate::io::output::graphviz::cluster::cluster::GraphVizCluster; +use crate::io::output::graphviz::colors::DotTranslatable; +use crate::io::output::graphviz::edge::edge::GraphVizEdge; -pub struct GraphVizNode { - pub id : String, - pub style : GraphvizNodeStyle +pub struct GraphVizDiGraph { + pub clusters : Vec, + pub nodes : Vec>, + pub edges : Vec } - -impl DotTranslatable for GraphVizNode { - fn to_dot_string(&self) -> String { - let mut res = String::new(); - res.push_str(&(self.id)); - res.push_str(&(self.style.to_dot_string())); - res.push_str(";"); - return res; +impl GraphVizDiGraph { + pub fn new() -> GraphVizDiGraph { + return GraphVizDiGraph{clusters:vec![],nodes:vec![],edges:vec![]}; } -} - -pub struct GraphVizEdge { - pub origin_id : String, - pub target_id : String, - pub style : GraphvizEdgeStyle -} - -impl DotTranslatable for GraphVizEdge { - fn to_dot_string(&self) -> String { - let mut res = String::new(); - res.push_str(&(self.origin_id)); - res.push_str("->"); - res.push_str(&(self.target_id)); - res.push_str(& self.style.to_dot_string() ); - res.push_str(";"); - return res; + pub fn get_specific_cluster(&mut self, cluster_id : usize) -> Option<&mut GraphVizCluster> { + return self.clusters.get_mut(cluster_id); } } - -pub struct GraphVizDiGraph { - pub nodes : Vec, - pub edges : Vec -} - impl DotTranslatable for GraphVizDiGraph { fn to_dot_string(&self) -> String { let mut res = String::new(); res.push_str("digraph G {"); + res.push_str("\ncompound=true;" ); + for cluster in &self.clusters { + res.push_str("\n\t"); + res.push_str(& cluster.to_dot_string() ); + } for node in &self.nodes { res.push_str("\n\t"); res.push_str(& node.to_dot_string() ); @@ -76,4 +56,5 @@ impl DotTranslatable for GraphVizDiGraph { res.push_str("\n}"); return res; } -} \ No newline at end of file +} + diff --git a/src/io/output/graphviz/mod.rs b/src/io/output/graphviz/mod.rs new file mode 100644 index 0000000..3a0cdbd --- /dev/null +++ b/src/io/output/graphviz/mod.rs @@ -0,0 +1,22 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +pub mod colors; +pub mod node; +pub mod edge; +pub mod cluster; +pub mod graph; \ No newline at end of file diff --git a/src/io/output/graphviz/node/mod.rs b/src/io/output/graphviz/node/mod.rs new file mode 100644 index 0000000..ee2cf23 --- /dev/null +++ b/src/io/output/graphviz/node/mod.rs @@ -0,0 +1,19 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +pub mod style; +pub mod node; \ No newline at end of file diff --git a/src/io/output/graphviz/node/node.rs b/src/io/output/graphviz/node/node.rs new file mode 100644 index 0000000..5274357 --- /dev/null +++ b/src/io/output/graphviz/node/node.rs @@ -0,0 +1,40 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use crate::io::output::graphviz::colors::DotTranslatable; +use crate::io::output::graphviz::node::style::GraphvizNodeStyle; + + + +pub struct GraphVizNode { + pub id : String, + pub style : GraphvizNodeStyle +} + + +impl DotTranslatable for GraphVizNode { + fn to_dot_string(&self) -> String { + let mut res = String::new(); + res.push_str(&(self.id)); + res.push_str(&(self.style.to_dot_string())); + res.push_str(";"); + return res; + } +} + + diff --git a/src/output/rendering/graphviz/node_style.rs b/src/io/output/graphviz/node/style.rs similarity index 84% rename from src/output/rendering/graphviz/node_style.rs rename to src/io/output/graphviz/node/style.rs index 1ec9c0a..b765109 100644 --- a/src/output/rendering/graphviz/node_style.rs +++ b/src/io/output/graphviz/node/style.rs @@ -17,10 +17,7 @@ limitations under the License. use strum_macros::IntoStaticStr; - -use crate::output::rendering::graphviz::common::{DotTranslatable,GraphvizColor}; - - +use crate::io::output::graphviz::colors::{DotTranslatable, GraphvizColor}; #[derive(IntoStaticStr)] @@ -33,7 +30,8 @@ pub enum GvNodeStyleKind { Diagonals, Filled, Striped, - Wedged + Wedged, + Invis } impl DotTranslatable for GvNodeStyleKind { @@ -81,7 +79,8 @@ pub enum GvNodeShape { InvTrapezium, InvHouse, Star, - PlainText + PlainText, + Point } impl DotTranslatable for GvNodeShape { @@ -104,13 +103,29 @@ pub enum GraphvizNodeStyleItem { FillColor(GraphvizColor), FontColor(GraphvizColor), FontSize(u32), - FontName(String) + FontName(String), + Height(u32), + Width(u32), + Peripheries(u32), + PenWidth(u32) } impl DotTranslatable for GraphvizNodeStyleItem { fn to_dot_string(&self) -> String { let mut res = String::new(); match self { + GraphvizNodeStyleItem::PenWidth(pw) => { + res.push_str(&format!("penwidth={:}",pw)); + }, + GraphvizNodeStyleItem::Height(height) => { + res.push_str(&format!("height={:}",height)); + }, + GraphvizNodeStyleItem::Width(width) => { + res.push_str(&format!("width={:}",width)); + }, + GraphvizNodeStyleItem::Peripheries(per) => { + res.push_str(&format!("peripheries={:}",per)); + }, GraphvizNodeStyleItem::Style(node_style) => { res.push_str("style="); res.push_str(&(node_style.to_dot_string())); @@ -123,7 +138,7 @@ impl DotTranslatable for GraphvizNodeStyleItem { res.push_str(&format!("label=\"{}\"",label)); }, GraphvizNodeStyleItem::Image(imgpath) => { - res.push_str(&format!("image=\"{}\"",imgpath)); + res.push_str(&format!("imagescale=true;image=\"{}\"",imgpath)); }, GraphvizNodeStyleItem::Color(graphviz_color) => { res.push_str("color="); diff --git a/src/output/rendering/custom_draw/multitrace/mod.rs b/src/io/output/graphviz/translatable.rs similarity index 95% rename from src/output/rendering/custom_draw/multitrace/mod.rs rename to src/io/output/graphviz/translatable.rs index 2a3f606..78d8b37 100644 --- a/src/output/rendering/custom_draw/multitrace/mod.rs +++ b/src/io/output/graphviz/translatable.rs @@ -15,6 +15,4 @@ limitations under the License. */ -pub mod draw_mu; -mod ext_mu; diff --git a/src/output/mod.rs b/src/io/output/mod.rs similarity index 84% rename from src/output/mod.rs rename to src/io/output/mod.rs index 50395cc..00d8fee 100644 --- a/src/output/mod.rs +++ b/src/io/output/mod.rs @@ -14,7 +14,13 @@ See the License for the specific language governing permissions and limitations under the License. */ -pub mod commons; +pub mod graphviz; +mod draw_commons; + +pub mod draw_interactions; +pub mod draw_traces; +pub mod draw_transitions; + pub mod to_hfiles; -pub mod rendering; + diff --git a/src/output/commons/textual_representation/model/interaction.rs b/src/io/output/to_hfiles/interaction/interaction.rs similarity index 54% rename from src/output/commons/textual_representation/model/interaction.rs rename to src/io/output/to_hfiles/interaction/interaction.rs index 7d7a9e2..7594164 100644 --- a/src/output/commons/textual_representation/model/interaction.rs +++ b/src/io/output/to_hfiles/interaction/interaction.rs @@ -17,22 +17,22 @@ limitations under the License. use crate::core::general_context::GeneralContext; use crate::core::language::syntax::interaction::{Interaction, LoopKind}; -use crate::output::commons::textual_convention::{SYNTAX_ALT, SYNTAX_EMPTY, SYNTAX_LOOP_H, SYNTAX_LOOP_P, SYNTAX_LOOP_S, SYNTAX_LOOP_W, SYNTAX_PAR, SYNTAX_SEQ, SYNTAX_STRICT}; -use crate::output::commons::textual_representation::model::model_action::{emission_as_text, reception_as_text}; +use crate::core::language::syntax::util::get_recursive_frag::{get_recursive_alt_frags, get_recursive_par_frags, get_recursive_seq_frags, get_recursive_strict_frags}; +use crate::io::output::to_hfiles::interaction::model_action::{emission_as_hif_encoding, reception_as_hif_encoding}; +use crate::io::textual_convention::{SYNTAX_ALT, SYNTAX_EMPTY, SYNTAX_LOOP_H, SYNTAX_LOOP_P, SYNTAX_LOOP_S, SYNTAX_LOOP_W, SYNTAX_PAR, SYNTAX_SEQ, SYNTAX_STRICT}; -pub fn interaction_as_text(gen_ctx : &GeneralContext, + +pub fn interaction_as_hif_encoding(gen_ctx : &GeneralContext, interaction : &Interaction) -> String { - return interaction_as_text_inner(gen_ctx,0,interaction); + return interaction_as_hif_encoding_inner(gen_ctx,0, interaction); } -fn binary_op_as_text(gen_ctx : &GeneralContext, +fn op_as_hif_encoding(gen_ctx : &GeneralContext, depth : usize, op_text : &'static str, - i1 : &Interaction, - i2:&Interaction) -> String { - let i1_string = interaction_as_text_inner(gen_ctx,depth+1,i1); - let i2_string = interaction_as_text_inner(gen_ctx,depth+1,i2); - return format!("{0}{1}(\n{2},\n{3}\n{0})", "\t".repeat(depth), op_text, i1_string, i2_string); + sub_ints : Vec<&Interaction>) -> String { + let ints_strs : Vec = sub_ints.iter().map(|i| interaction_as_hif_encoding_inner(gen_ctx,depth+1,i)).collect(); + return format!("{0}{1}(\n{2}\n{0})", "\t".repeat(depth), op_text, ints_strs.join(",\n")); } fn loop_kind_as_text(lk : &LoopKind) -> &'static str { @@ -52,7 +52,7 @@ fn loop_kind_as_text(lk : &LoopKind) -> &'static str { } } -fn interaction_as_text_inner(gen_ctx : &GeneralContext, +fn interaction_as_hif_encoding_inner(gen_ctx : &GeneralContext, depth : usize, interaction : &Interaction) -> String { match interaction { @@ -60,28 +60,36 @@ fn interaction_as_text_inner(gen_ctx : &GeneralContext, return format!("{}{}", "\t".repeat(depth), SYNTAX_EMPTY); }, &Interaction::Emission(ref em_act) => { - return format!("{}{}", "\t".repeat(depth), emission_as_text(em_act)); + return format!("{}{}", "\t".repeat(depth), emission_as_hif_encoding(gen_ctx,em_act)); }, &Interaction::Reception(ref rc_act) => { - return format!("{}{}", "\t".repeat(depth), reception_as_text(rc_act)); + return format!("{}{}", "\t".repeat(depth), reception_as_hif_encoding(gen_ctx,rc_act)); }, &Interaction::Strict(ref i1, ref i2) => { - return binary_op_as_text(gen_ctx,depth,SYNTAX_STRICT,i1,i2); + let mut strict_frags = get_recursive_strict_frags(i1); + strict_frags.extend_from_slice(&mut get_recursive_strict_frags(i2)); + return op_as_hif_encoding(gen_ctx,depth,SYNTAX_STRICT,strict_frags); }, &Interaction::Seq(ref i1, ref i2) => { - return binary_op_as_text(gen_ctx,depth,SYNTAX_SEQ,i1,i2); + let mut seq_frags = get_recursive_seq_frags(i1); + seq_frags.extend_from_slice(&mut get_recursive_seq_frags(i2)); + return op_as_hif_encoding(gen_ctx,depth,SYNTAX_SEQ,seq_frags); }, &Interaction::CoReg(_, ref i1, ref i2) => { panic!("todo"); }, &Interaction::Par(ref i1, ref i2) => { - return binary_op_as_text(gen_ctx,depth,SYNTAX_PAR,i1,i2); + let mut par_frags = get_recursive_par_frags(i1); + par_frags.extend_from_slice(&mut get_recursive_par_frags(i2)); + return op_as_hif_encoding(gen_ctx,depth,SYNTAX_PAR,par_frags); }, &Interaction::Alt(ref i1, ref i2) => { - return binary_op_as_text(gen_ctx,depth,SYNTAX_ALT,i1,i2); + let mut alt_frags = get_recursive_alt_frags(i1); + alt_frags.extend_from_slice(&mut get_recursive_alt_frags(i2)); + return op_as_hif_encoding(gen_ctx,depth,SYNTAX_ALT,alt_frags); }, &Interaction::Loop(ref lk, ref i1) => { - let i1_string = interaction_as_text_inner(gen_ctx,depth+1,i1); + let i1_string = interaction_as_hif_encoding_inner(gen_ctx,depth+1,i1); return format!("{0}{1}(\n{2}\n{0})", "\t".repeat(depth), loop_kind_as_text(lk), i1_string); }, _ => { diff --git a/src/io/output/to_hfiles/interaction/mod.rs b/src/io/output/to_hfiles/interaction/mod.rs new file mode 100644 index 0000000..91cadfb --- /dev/null +++ b/src/io/output/to_hfiles/interaction/mod.rs @@ -0,0 +1,21 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +mod model_action; +mod interaction; +pub mod to_hif; + + diff --git a/src/io/output/to_hfiles/interaction/model_action.rs b/src/io/output/to_hfiles/interaction/model_action.rs new file mode 100644 index 0000000..b381ba7 --- /dev/null +++ b/src/io/output/to_hfiles/interaction/model_action.rs @@ -0,0 +1,96 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::action::{CommunicationSynchronicity, EmissionAction, EmissionTargetRef, ReceptionAction}; + + +pub fn emission_as_hif_encoding(gen_ctx : &GeneralContext, + em_act : &EmissionAction) -> String { + let mut targ_names : Vec = Vec::new(); + for targ_ref in &em_act.targets { + match targ_ref { + EmissionTargetRef::Lifeline(tar_lf_id) => { + targ_names.push( gen_ctx.get_lf_name(*tar_lf_id).unwrap() ); + }, + EmissionTargetRef::Gate(tar_gt_id) => { + targ_names.push( gen_ctx.get_gt_name(*tar_gt_id).unwrap() ); + } + } + } + // *** + let synch_key : String; + match em_act.synchronicity { + CommunicationSynchronicity::Asynchronous => { + synch_key = "".to_string(); + }, + CommunicationSynchronicity::Synchronous => { + synch_key = "".to_string(); + } + } + // *** + let lf_name = gen_ctx.get_lf_name(em_act.origin_lf_id).unwrap(); + let ms_name = gen_ctx.get_ms_name(em_act.ms_id).unwrap(); + let rcp_num = targ_names.len(); + if rcp_num == 0 { + return format!("{} -- {}{} ->|", &lf_name, synch_key, &ms_name); + } else if rcp_num == 1 { + return format!("{} -- {}{} -> {}", &lf_name, synch_key, &ms_name, targ_names.get(0).unwrap()); + } else { + return format!("{} -- {}{} -> ({})", &lf_name, synch_key, &ms_name, &targ_names.join(",")); + } +} + + +pub fn reception_as_hif_encoding(gen_ctx : &GeneralContext, + rc_act : &ReceptionAction) -> String { + let mut targ_names : Vec = Vec::new(); + for rcp_lf_id in &rc_act.recipients { + targ_names.push( gen_ctx.get_lf_name(*rcp_lf_id).unwrap() ); + } + // *** + let synch_key : String; + match rc_act.synchronicity { + CommunicationSynchronicity::Asynchronous => { + synch_key = "".to_string(); + }, + CommunicationSynchronicity::Synchronous => { + synch_key = "".to_string(); + } + } + // *** + let gate_str : String; + match rc_act.origin_gt_id { + None => { + gate_str = "".to_string(); + }, + Some(orig_gt_id) => { + gate_str = format!("{} -- ",gen_ctx.get_gt_name(orig_gt_id).unwrap()); + } + } + // *** + let ms_name = gen_ctx.get_ms_name(rc_act.ms_id).unwrap(); + let rcp_num = targ_names.len(); + if rcp_num == 1 { + return format!("{}{}{} -> {}", gate_str, synch_key, &ms_name, targ_names.get(0).unwrap()); + } else if rcp_num > 1 { + return format!("{}{}{} -> ({})", gate_str, synch_key, &ms_name, &targ_names.join(",")); + } else { + panic!(); + } +} \ No newline at end of file diff --git a/src/output/to_hfiles/interaction_to_hsf.rs b/src/io/output/to_hfiles/interaction/to_hif.rs similarity index 63% rename from src/output/to_hfiles/interaction_to_hsf.rs rename to src/io/output/to_hfiles/interaction/to_hif.rs index 84cb785..a3422f1 100644 --- a/src/output/to_hfiles/interaction_to_hsf.rs +++ b/src/io/output/to_hfiles/interaction/to_hif.rs @@ -16,24 +16,23 @@ limitations under the License. -use std::fs; -use std::collections::HashMap; -use std::collections::btree_map::BTreeMap; +use std::fs::File; +use std::io::Write; use std::path::Path; -use pest::iterators::Pair; - -use crate::pest::Parser; - use crate::core::language::syntax::interaction::Interaction; -use crate::core::language::syntax::action::*; + use crate::core::general_context::GeneralContext; -use crate::input::error::HibouParsingError; -use crate::process::log::ProcessLogger; + +use crate::io::output::to_hfiles::interaction::interaction::interaction_as_hif_encoding; + -pub fn interaction_to_hsf(interaction : &Interaction, gen_ctx : &GeneralContext, file_name : &String) { - //TODO +pub fn interaction_to_hif(file_path : &Path, + gen_ctx : &GeneralContext, + interaction : &Interaction) { + let mut file = File::create(file_path).unwrap(); + file.write(interaction_as_hif_encoding(gen_ctx,&interaction).as_bytes() ); } \ No newline at end of file diff --git a/src/output/commons/textual_representation/model/mod.rs b/src/io/output/to_hfiles/mod.rs similarity index 96% rename from src/output/commons/textual_representation/model/mod.rs rename to src/io/output/to_hfiles/mod.rs index 88aa248..617b111 100644 --- a/src/output/commons/textual_representation/model/mod.rs +++ b/src/io/output/to_hfiles/mod.rs @@ -15,6 +15,5 @@ limitations under the License. */ -pub mod model_action; +pub mod trace; pub mod interaction; - diff --git a/src/io/output/to_hfiles/trace/mod.rs b/src/io/output/to_hfiles/trace/mod.rs new file mode 100644 index 0000000..1723a8c --- /dev/null +++ b/src/io/output/to_hfiles/trace/mod.rs @@ -0,0 +1,21 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +mod trace_action; +mod multi_trace; +pub mod to_htf; + diff --git a/src/output/commons/textual_representation/trace/multi_trace.rs b/src/io/output/to_hfiles/trace/multi_trace.rs similarity index 84% rename from src/output/commons/textual_representation/trace/multi_trace.rs rename to src/io/output/to_hfiles/trace/multi_trace.rs index f784099..964e746 100644 --- a/src/output/commons/textual_representation/trace/multi_trace.rs +++ b/src/io/output/to_hfiles/trace/multi_trace.rs @@ -21,10 +21,10 @@ use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::{MultiTrace, Trace}; use crate::core::general_context::GeneralContext; -use crate::output::commons::textual_representation::trace::trace_action::trace_actions_as_text; +use crate::io::output::to_hfiles::trace::trace_action::trace_actions_as_htf_encoding; -pub fn multi_trace_as_text(gen_ctx : &GeneralContext, +pub fn multi_trace_as_htf_encoding(gen_ctx : &GeneralContext, co_localizations : &CoLocalizations, multi_trace : &MultiTrace) -> String { let mut canals_strings : Vec = vec![]; @@ -37,11 +37,11 @@ pub fn multi_trace_as_text(gen_ctx : &GeneralContext, for lf_id in coloc_lfs.iter().sorted() { lf_names.push( gen_ctx.get_lf_name(*lf_id).unwrap() ); } - canal_string.push_str( &format!( "[{:}]", lf_names.join(",")) ); + canal_string.push_str( &format!( "[{:}] ", lf_names.join(",")) ); // *** let mut trace_text_elements = vec![]; for actions in canal_trace { - trace_text_elements.push( trace_actions_as_text(gen_ctx, actions) ); + trace_text_elements.push( trace_actions_as_htf_encoding(gen_ctx, actions) ); } canal_string.push_str(&trace_text_elements.join(".") ); // *** diff --git a/src/output/to_hfiles/multitrace_to_htf.rs b/src/io/output/to_hfiles/trace/to_htf.rs similarity index 70% rename from src/output/to_hfiles/multitrace_to_htf.rs rename to src/io/output/to_hfiles/trace/to_htf.rs index 04158cb..2b1c112 100644 --- a/src/output/to_hfiles/multitrace_to_htf.rs +++ b/src/io/output/to_hfiles/trace/to_htf.rs @@ -17,6 +17,7 @@ limitations under the License. use std::fs::File; use std::io::Write; +use std::path::Path; use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::MultiTrace; @@ -24,16 +25,15 @@ use crate::core::execution::trace::multitrace::MultiTrace; use crate::core::general_context::GeneralContext; -use crate::output::commons::file_extensions::HIBOU_TRACE_FILE_EXTENSION; -use crate::output::commons::textual_representation::trace::multi_trace::multi_trace_as_text; +use crate::io::output::to_hfiles::trace::multi_trace::multi_trace_as_htf_encoding; -pub fn write_multi_trace_into_file(file_name : &str, +pub fn write_multi_trace_into_file(file_path : &Path, gen_ctx : &GeneralContext, co_localizations : &CoLocalizations, multi_trace : &MultiTrace) { - let mut file = File::create(&format!("{:}.{:}",file_name, HIBOU_TRACE_FILE_EXTENSION)).unwrap(); - file.write(multi_trace_as_text(gen_ctx,co_localizations,multi_trace).as_bytes() ); + let mut file = File::create(file_path).unwrap(); + file.write(multi_trace_as_htf_encoding(gen_ctx,co_localizations,multi_trace).as_bytes() ); } diff --git a/src/output/commons/textual_representation/trace/trace_action.rs b/src/io/output/to_hfiles/trace/trace_action.rs similarity index 76% rename from src/output/commons/textual_representation/trace/trace_action.rs rename to src/io/output/to_hfiles/trace/trace_action.rs index 71511ae..8a1e522 100644 --- a/src/output/commons/textual_representation/trace/trace_action.rs +++ b/src/io/output/to_hfiles/trace/trace_action.rs @@ -21,22 +21,22 @@ use itertools::Itertools; use crate::core::general_context::GeneralContext; use crate::core::execution::trace::trace::{TraceAction, TraceActionKind}; -use crate::output::commons::textual_convention::{SYNTAX_EMISSION, SYNTAX_RECEPTION}; +use crate::io::textual_convention::{SYNTAX_EMISSION, SYNTAX_RECEPTION}; -pub fn trace_actions_as_text(gen_ctx : &GeneralContext, actions : &HashSet) -> String { +pub fn trace_actions_as_htf_encoding(gen_ctx : &GeneralContext, actions : &HashSet) -> String { if actions.len() == 1 { - return trace_action_as_text(gen_ctx,actions.iter().next().unwrap()); + return trace_action_as_htf_encoding(gen_ctx,actions.iter().next().unwrap()); } else { let mut actions_as_text= vec![]; for action in actions.iter().sorted() { - actions_as_text.push( trace_action_as_text(gen_ctx,action) ); + actions_as_text.push( trace_action_as_htf_encoding(gen_ctx,action) ); } return format!( "{{{:}}}", actions_as_text.join(",") ); } } -fn trace_action_as_text(gen_ctx : &GeneralContext, action : &TraceAction) -> String { +fn trace_action_as_htf_encoding(gen_ctx : &GeneralContext, action : &TraceAction) -> String { let lf_name = gen_ctx.get_lf_name(action.lf_id).unwrap(); let ms_name = gen_ctx.get_ms_name(action.ms_id).unwrap(); // *** diff --git a/src/output/commons/textual_convention.rs b/src/io/textual_convention.rs similarity index 91% rename from src/output/commons/textual_convention.rs rename to src/io/textual_convention.rs index ed528bb..d3ab452 100644 --- a/src/output/commons/textual_convention.rs +++ b/src/io/textual_convention.rs @@ -26,7 +26,9 @@ pub static SYNTAX_LOOP_W: &'static str = "loopW"; pub static SYNTAX_LOOP_P: &'static str = "loopP"; pub static SYNTAX_EMISSION: &'static str = "!"; +pub static SYNTAX_EMISSION_SYNCHRONOUS: &'static str = "|!|"; pub static SYNTAX_RECEPTION: &'static str = "?"; +pub static SYNTAX_RECEPTION_SYNCHRONOUS: &'static str = "|?|"; pub static SYNTAX_POSITION_LEFT: &'static str = "1"; pub static SYNTAX_POSITION_RIGHT: &'static str = "2"; diff --git a/src/loggers/graphic/conf.rs b/src/loggers/graphic/conf.rs index 937bd37..197ffe8 100644 --- a/src/loggers/graphic/conf.rs +++ b/src/loggers/graphic/conf.rs @@ -14,13 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ -/** - cut up representation in node - inner node for interaction/term - other inner node for multi-trace -**/ -pub enum GraphicProcessLoggerOutputKind { +pub enum GraphicProcessLoggerOutputFormat { svg, png } @@ -30,8 +25,4 @@ pub enum GraphicProcessLoggerLayout { vertical } -pub enum GraphicProcessLoggerInteractionRepresentation { - diagram, - term -} diff --git a/src/loggers/graphic/get_graph/filter.rs b/src/loggers/graphic/get_graph/filter.rs new file mode 100644 index 0000000..eca91e5 --- /dev/null +++ b/src/loggers/graphic/get_graph/filter.rs @@ -0,0 +1,56 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::io::output::graphviz::colors::GraphvizColor; +use crate::io::output::graphviz::edge::edge::GraphVizEdge; +use crate::io::output::graphviz::edge::style::{GraphvizEdgeStyle, GraphvizEdgeStyleItem, GvArrowHeadSide, GvArrowHeadStyle}; +use crate::io::output::graphviz::node::node::GraphVizNode; +use crate::io::output::graphviz::node::style::{GraphvizNodeStyle, GraphvizNodeStyleItem, GvNodeShape, GvNodeStyleKind}; +use crate::process::abstract_proc::common::FilterEliminationKind; + + +pub fn make_graphic_logger_filter(parent_state_id : u32, + new_state_id : u32, + elim_kind : &FilterEliminationKind) -> (GraphVizNode,GraphVizEdge) { + // *** + let elim_node : GraphVizNode; + { + let mut node_gv_options : GraphvizNodeStyle = Vec::new(); + // *** + node_gv_options.push( GraphvizNodeStyleItem::Label( elim_kind.to_string() ) ); + node_gv_options.push( GraphvizNodeStyleItem::Color( GraphvizColor::burlywood4 ) ); + node_gv_options.push( GraphvizNodeStyleItem::FontColor( GraphvizColor::beige ) ); + node_gv_options.push( GraphvizNodeStyleItem::FontSize( 16 ) ); + node_gv_options.push( GraphvizNodeStyleItem::FontName( "times-bold".to_string() ) ); + node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Pentagon) ); + node_gv_options.push( GraphvizNodeStyleItem::Style(vec![GvNodeStyleKind::Filled]) ); + // *** + elim_node = GraphVizNode{id:format!("e{:}", new_state_id),style:node_gv_options}; + } + // *** + let elim_edge : GraphVizEdge; + { + let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); + // *** + tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); + tran_gv_options.push( GraphvizEdgeStyleItem::Color( GraphvizColor::burlywood4 ) ); + tran_gv_options.push( GraphvizEdgeStyleItem::LTail( format!("cluster_n{}",parent_state_id) ) ); + // *** + elim_edge = GraphVizEdge::new(format!("a{:}", parent_state_id),elim_node.id.clone(),tran_gv_options); + } + return (elim_node,elim_edge); +} \ No newline at end of file diff --git a/src/loggers/graphic/get_graph/legend.rs b/src/loggers/graphic/get_graph/legend.rs new file mode 100644 index 0000000..1b1baef --- /dev/null +++ b/src/loggers/graphic/get_graph/legend.rs @@ -0,0 +1,37 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::io::output::graphviz::node::node::GraphVizNode; +use crate::io::output::graphviz::node::style::{GraphvizNodeStyle, GraphvizNodeStyleItem, GvNodeShape, GvNodeStyleKind}; + + +pub fn make_graphic_logger_legend(options_as_strs : &Vec) -> GraphVizNode { + let mut legend_str = String::new(); + for opt_str in options_as_strs { + legend_str.push_str(opt_str); + legend_str.push_str("\\l"); + } + // *** + let mut legend_node_gv_options : GraphvizNodeStyle = Vec::new(); + legend_node_gv_options.push( GraphvizNodeStyleItem::Label( legend_str ) ); + legend_node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); + legend_node_gv_options.push( GraphvizNodeStyleItem::Style(vec![GvNodeStyleKind::Bold,GvNodeStyleKind::Rounded]) ); + legend_node_gv_options.push( GraphvizNodeStyleItem::FontSize( 18 ) ); + // *** + return GraphVizNode{id:"legend".to_string(), style:legend_node_gv_options}; +} + diff --git a/src/output/rendering/custom_draw/mod.rs b/src/loggers/graphic/get_graph/mod.rs similarity index 90% rename from src/output/rendering/custom_draw/mod.rs rename to src/loggers/graphic/get_graph/mod.rs index e618881..95d198d 100644 --- a/src/output/rendering/custom_draw/mod.rs +++ b/src/loggers/graphic/get_graph/mod.rs @@ -15,8 +15,9 @@ limitations under the License. */ -mod utils; -pub mod multitrace; -pub mod seqdiag; +pub mod legend; +pub mod state; pub mod transition; -pub mod term; \ No newline at end of file +pub mod filter; +pub mod verdict; + diff --git a/src/loggers/graphic/get_graph/state.rs b/src/loggers/graphic/get_graph/state.rs new file mode 100644 index 0000000..abb250e --- /dev/null +++ b/src/loggers/graphic/get_graph/state.rs @@ -0,0 +1,172 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + +use std::path::PathBuf; +use crate::core::colocalizations::CoLocalizations; +use crate::core::execution::trace::multitrace::MultiTrace; +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::interaction::Interaction; +use crate::io::output::draw_interactions::interface::{draw_interaction, InteractionGraphicalRepresentation}; +use crate::io::output::draw_traces::interface::draw_multitrace; +use crate::io::output::graphviz::cluster::cluster::GraphVizCluster; +use crate::io::output::graphviz::colors::{DotTranslatable, GraphvizColor}; +use crate::io::output::graphviz::node::node::GraphVizNode; +use crate::io::output::graphviz::node::style::{GraphvizNodeStyle, GraphvizNodeStyleItem, GvNodeShape, GvNodeStyle, GvNodeStyleKind}; +use crate::process::ana_proc::logic::flags::MultiTraceAnalysisFlags; + + +fn make_anchor_node(state_id : u32) -> GraphVizNode { + return GraphVizNode{id:format!("a{:}", state_id), + style:vec![GraphvizNodeStyleItem::Label("".to_string()), + GraphvizNodeStyleItem::Style(vec![GvNodeStyleKind::Invis]), + GraphvizNodeStyleItem::Peripheries(0), + GraphvizNodeStyleItem::Height(0),GraphvizNodeStyleItem::Width(0) + ]}; +} + +pub fn make_graphic_logger_state(temp_folder : &String, + gen_ctx : &GeneralContext, + state_id : u32, + interaction : &Interaction, + as_sd : bool, + as_term : bool, + with_mu : Option<(&CoLocalizations,&MultiTrace,&MultiTraceAnalysisFlags,bool,bool,bool)>) -> GraphVizCluster { + let mut nodes : Vec> = vec![]; + // *** + let mut anchored = false; + let mut got = 0; + if let Some((coloc,mu,flags,is_sim,crit_loop,crit_act)) = with_mu { + got += 1; + let node = make_graphic_logger_mu(temp_folder,gen_ctx,state_id,coloc,mu,flags,is_sim,crit_loop,crit_act); + nodes.push(Box::new(node)); + } + if got > 0 { + let node = make_anchor_node(state_id); + nodes.push(Box::new(node)); + anchored = true; + } + // *** + if as_sd { + got += 1; + let node = make_graphic_logger_sd(temp_folder,gen_ctx,state_id,interaction); + nodes.push(Box::new(node)); + } + if !anchored && got > 0 { + let node = make_anchor_node(state_id); + nodes.push(Box::new(node)); + anchored = true; + } + if as_term { + let node = make_graphic_logger_tt(temp_folder,gen_ctx,state_id,interaction); + nodes.push(Box::new(node)); + } + if !anchored { + let node = make_anchor_node(state_id); + nodes.push(Box::new(node)); + } + // *** + let node_id = format!("n{:}", state_id); + // *** + let mut cluster_gv_options : GraphvizNodeStyle = Vec::new(); + cluster_gv_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::lightgrey )); + cluster_gv_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + // *** + return GraphVizCluster::new(node_id,cluster_gv_options,nodes,vec![]); +} + + + +fn make_graphic_logger_sd(temp_folder : &String, + gen_ctx : &GeneralContext, + state_id : u32, + interaction : &Interaction) -> GraphVizNode { + let mut node_gv_options : GraphvizNodeStyle = Vec::new(); + let int_image_file_name = format!("isd{}", state_id); + if interaction != &Interaction::Empty { + draw_interaction(gen_ctx, + interaction, + &InteractionGraphicalRepresentation::AsSequenceDiagram, + &"temp".to_string() , + temp_folder, + &int_image_file_name); + // *** + let int_image_file_path : PathBuf = [temp_folder, &format!("{}.png",int_image_file_name)].iter().collect(); + // *** + node_gv_options.push( GraphvizNodeStyleItem::Image( int_image_file_path.into_os_string().to_str().unwrap().to_string() ) ); + node_gv_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + } else { + node_gv_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + node_gv_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::white )); + } + node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); + // *** + return GraphVizNode{id : int_image_file_name, style:node_gv_options}; +} + + + +fn make_graphic_logger_tt(temp_folder : &String, + gen_ctx : &GeneralContext, + state_id : u32, + interaction : &Interaction) -> GraphVizNode { + let mut node_gv_options : GraphvizNodeStyle = Vec::new(); + let int_image_file_name = format!("itt{}", state_id); + if interaction != &Interaction::Empty { + draw_interaction(gen_ctx, + interaction, + &InteractionGraphicalRepresentation::AsTerm, + &"temp".to_string() , + temp_folder, + &int_image_file_name); + // *** + let int_image_file_path : PathBuf = [temp_folder, &format!("{}.png",int_image_file_name)].iter().collect(); + // *** + node_gv_options.push( GraphvizNodeStyleItem::Image( int_image_file_path.into_os_string().to_str().unwrap().to_string() ) ); + node_gv_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + } else { + node_gv_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + node_gv_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::white )); + } + node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); + // *** + return GraphVizNode{id : int_image_file_name, style:node_gv_options}; +} + + +fn make_graphic_logger_mu(temp_folder : &String, + gen_ctx : &GeneralContext, + state_id : u32, + co_localizations : &CoLocalizations, + multi_trace : &MultiTrace, + flags : &MultiTraceAnalysisFlags, + is_simulation : bool, + sim_crit_loop : bool, + sim_crit_act : bool) -> GraphVizNode { + let mu_image_file_name = format!("mu{}.png", state_id); + // *** + draw_multitrace(gen_ctx,co_localizations,multi_trace,flags,is_simulation,sim_crit_loop,sim_crit_act,temp_folder,&mu_image_file_name); + // *** + let mut node_gv_options : GraphvizNodeStyle = Vec::new(); + let mu_image_file_path : PathBuf = [temp_folder, &mu_image_file_name].iter().collect(); + node_gv_options.push( GraphvizNodeStyleItem::Image( mu_image_file_path.into_os_string().to_str().unwrap().to_string() ) ); + node_gv_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); + // *** + return GraphVizNode{id : format!("mu{:}", state_id), style:node_gv_options}; +} \ No newline at end of file diff --git a/src/loggers/graphic/get_graph/transition.rs b/src/loggers/graphic/get_graph/transition.rs new file mode 100644 index 0000000..3631a6d --- /dev/null +++ b/src/loggers/graphic/get_graph/transition.rs @@ -0,0 +1,136 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + + +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; +use crate::core::colocalizations::CoLocalizations; +use crate::core::execution::trace::trace::TraceAction; +use crate::core::general_context::GeneralContext; +use crate::core::language::position::position::Position; +use crate::core::transformation::transfokind::InteractionTransformationKind; +use crate::io::output::draw_transitions::draw_firing::{draw_firing_analysis, draw_firing_simple}; +use crate::io::output::draw_transitions::draw_hiding::draw_hiding; +use crate::io::output::draw_transitions::draw_string_label::draw_string_label; +use crate::io::output::draw_transitions::draw_transformation::draw_transformation; +use crate::io::output::graphviz::colors::GraphvizColor; +use crate::io::output::graphviz::node::node::GraphVizNode; +use crate::io::output::graphviz::node::style::{GraphvizNodeStyle, GraphvizNodeStyleItem, GvNodeShape}; +use crate::process::ana_proc::interface::step::SimulationStepKind; + + + +pub fn make_graphic_logger_string_label(temp_folder : &String, + state_id : u32, + string_label : String) -> GraphVizNode { + let sl_image_file_name = format!("sl{}.png", state_id); + let sl_image_file_path : PathBuf = [temp_folder, &sl_image_file_name].iter().collect(); + // *** + draw_string_label(sl_image_file_path.as_path(),string_label); + // *** + let mut gv_node_options : GraphvizNodeStyle = Vec::new(); + gv_node_options.push( GraphvizNodeStyleItem::Image( sl_image_file_path.into_os_string().to_str().unwrap().to_string() ) ); + gv_node_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + gv_node_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::white )); + gv_node_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); + // *** + return GraphVizNode{id:format!("sl{:}", state_id),style:gv_node_options}; +} + + + + + +pub fn make_graphic_logger_transformation(temp_folder : &String, + state_id : u32, + transfo_kind : &InteractionTransformationKind, + position : &Position) -> GraphVizNode { + let tr_image_file_name = format!("t{}.png", state_id); + let tr_image_file_path : PathBuf = [temp_folder, &tr_image_file_name].iter().collect(); + // *** + draw_transformation(tr_image_file_path.as_path(),transfo_kind,position); + // *** + let mut gv_node_options : GraphvizNodeStyle = Vec::new(); + gv_node_options.push( GraphvizNodeStyleItem::Image( tr_image_file_path.into_os_string().to_str().unwrap().to_string() ) ); + gv_node_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + gv_node_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::white )); + gv_node_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); + // *** + return GraphVizNode{id:format!("t{:}", state_id),style:gv_node_options}; +} + + + + +pub fn make_graphic_logger_hiding(temp_folder : &String, + gen_ctx : &GeneralContext, + state_id : u32, + lfs_to_hide: &HashSet) -> GraphVizNode { + let hid_image_file_name = format!("h{}.png", state_id); + let hid_image_file_path : PathBuf = [temp_folder, &hid_image_file_name].iter().collect(); + // *** + draw_hiding(hid_image_file_path.as_path(),gen_ctx,lfs_to_hide); + // *** + let mut gv_node_options : GraphvizNodeStyle = Vec::new(); + gv_node_options.push( GraphvizNodeStyleItem::Image( hid_image_file_path.into_os_string().to_str().unwrap().to_string() ) ); + gv_node_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + gv_node_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::white )); + gv_node_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); + // *** + return GraphVizNode{id:format!("h{:}", state_id),style:gv_node_options}; +} + + + +pub fn make_graphic_logger_firing(temp_folder : &String, + gen_ctx : &GeneralContext, + state_id : u32, + action_position : &Position, + executed_actions : &HashSet, + ana : Option<(&CoLocalizations, &HashSet, &HashMap)>) -> GraphVizNode { + let fir_image_file_name = format!("f{}.png", state_id); + let fir_image_file_path : PathBuf = [temp_folder, &fir_image_file_name].iter().collect(); + // *** + match ana { + None => { + draw_firing_simple(fir_image_file_path.as_path(), + gen_ctx, + action_position, + executed_actions); + }, + Some((colocs, consu_set,sim_map)) => { + draw_firing_analysis(fir_image_file_path.as_path(), + gen_ctx, + action_position, + executed_actions, + colocs, + consu_set, + sim_map); + } + } + // *** + let mut gv_node_options : GraphvizNodeStyle = Vec::new(); + gv_node_options.push( GraphvizNodeStyleItem::Image( fir_image_file_path.into_os_string().to_str().unwrap().to_string() ) ); + gv_node_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); + gv_node_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::white )); + gv_node_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); + // *** + return GraphVizNode{id:format!("f{:}", state_id),style:gv_node_options}; +} + diff --git a/src/loggers/graphic/get_graph/verdict.rs b/src/loggers/graphic/get_graph/verdict.rs new file mode 100644 index 0000000..50ecd3b --- /dev/null +++ b/src/loggers/graphic/get_graph/verdict.rs @@ -0,0 +1,57 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::io::output::graphviz::colors::GraphvizColor; +use crate::io::output::graphviz::edge::edge::GraphVizEdge; +use crate::io::output::graphviz::edge::style::{GraphvizEdgeStyle, GraphvizEdgeStyleItem, GvArrowHeadSide, GvArrowHeadStyle}; +use crate::io::output::graphviz::node::node::GraphVizNode; +use crate::io::output::graphviz::node::style::{GraphvizNodeStyle, GraphvizNodeStyleItem, GvNodeShape, GvNodeStyleKind}; +use crate::process::ana_proc::logic::verdicts::CoverageVerdict; + + +pub fn make_graphic_logger_verdict(parent_state_id: u32, + verdict: &CoverageVerdict) -> (GraphVizNode,GraphVizEdge) { + let verdict_color = verdict.get_verdict_color(); + // *** + let verd_node : GraphVizNode; + { + let mut node_gv_options : GraphvizNodeStyle = Vec::new(); + // *** + node_gv_options.push( GraphvizNodeStyleItem::Label( verdict.to_string() ) ); + node_gv_options.push( GraphvizNodeStyleItem::Color( verdict_color.clone() ) ); + node_gv_options.push( GraphvizNodeStyleItem::FontColor( GraphvizColor::beige ) ); + node_gv_options.push( GraphvizNodeStyleItem::FontSize( 16 ) ); + node_gv_options.push( GraphvizNodeStyleItem::FontName( "times-bold".to_string() ) ); + node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Diamond) ); + node_gv_options.push( GraphvizNodeStyleItem::Style(vec![GvNodeStyleKind::Filled]) ); + // *** + verd_node = GraphVizNode{id:format!("v{:}", parent_state_id),style:node_gv_options}; + } + // *** + let verd_edge : GraphVizEdge; + { + let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); + // *** + tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); + tran_gv_options.push( GraphvizEdgeStyleItem::Color( verdict_color ) ); + tran_gv_options.push( GraphvizEdgeStyleItem::LHead( format!("cluster_n{}",parent_state_id) ) ); + // *** + verd_edge = GraphVizEdge::new(format!("a{:}", parent_state_id),verd_node.id.clone(),tran_gv_options); + } + return (verd_node,verd_edge); +} + diff --git a/src/loggers/graphic/glog_ana.rs b/src/loggers/graphic/glog_ana.rs index cb06675..c84cb7b 100644 --- a/src/loggers/graphic/glog_ana.rs +++ b/src/loggers/graphic/glog_ana.rs @@ -18,19 +18,22 @@ limitations under the License. use std::collections::{HashMap, HashSet}; use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::MultiTrace; +use crate::core::execution::trace::trace::TraceAction; use crate::core::general_context::GeneralContext; -use crate::core::language::syntax::interaction::Interaction; use crate::core::language::position::position::Position; -use crate::core::execution::trace::trace::TraceAction; +use crate::core::language::syntax::interaction::Interaction; +use crate::io::output::graphviz::edge::edge::GraphVizEdge; +use crate::io::output::graphviz::edge::style::{GraphvizEdgeStyle, GraphvizEdgeStyleItem, GvArrowHeadSide, GvArrowHeadStyle, GvEdgeLineStyle}; +use crate::loggers::graphic::get_graph::filter::make_graphic_logger_filter; +use crate::loggers::graphic::get_graph::state::make_graphic_logger_state; +use crate::loggers::graphic::get_graph::transition::{make_graphic_logger_firing, make_graphic_logger_hiding}; +use crate::loggers::graphic::get_graph::verdict::make_graphic_logger_verdict; +use crate::loggers::graphic::graphic_logger::GraphicProcessLogger; use crate::process::abstract_proc::common::FilterEliminationKind; use crate::process::ana_proc::interface::logger::AnalysisLogger; use crate::process::ana_proc::interface::step::SimulationStepKind; -use crate::process::ana_proc::logic::verdicts::CoverageVerdict; -use crate::output::rendering::graphviz::common::GraphvizColor; -use crate::output::rendering::graphviz::edge_style::{GraphvizEdgeStyle, GraphvizEdgeStyleItem, GvArrowHeadSide, GvArrowHeadStyle, GvEdgeLineStyle}; -use crate::output::rendering::graphviz::node_style::{GraphvizNodeStyle, GraphvizNodeStyleItem, GvNodeShape, GvNodeStyleKind}; -use crate::loggers::graphic::graphic_logger::GraphicProcessLogger; use crate::process::ana_proc::logic::flags::MultiTraceAnalysisFlags; +use crate::process::ana_proc::logic::verdicts::CoverageVerdict; impl AnalysisLogger for GraphicProcessLogger { @@ -44,15 +47,14 @@ impl AnalysisLogger for GraphicProcessLogger { is_simulation : bool, sim_crit_loop : bool, sim_crit_act : bool) { - self.initiate(); - self.write_analysis_node(gen_ctx,co_localizations, - 1, - interaction, - multi_trace, - flags, - is_simulation, - sim_crit_loop, - sim_crit_act); + let init_node = make_graphic_logger_state(&self.temp_folder, + gen_ctx, + 1, + interaction, + self.int_repr_sd, + self.int_repr_tt, + Some((co_localizations,multi_trace,flags,is_simulation,sim_crit_loop,sim_crit_act))); + self.graph.nodes.push(Box::new(init_node)); } fn log_term(&mut self, @@ -76,29 +78,41 @@ impl AnalysisLogger for GraphicProcessLogger { sim_crit_loop : bool, sim_crit_act : bool) { // *** - self.write_firing_analysis(gen_ctx, - co_localizations, - new_state_id, - action_position, - executed_actions, - consu_set, - sim_map); + let state_firing = make_graphic_logger_firing(&self.temp_folder, + gen_ctx, + new_state_id, + action_position, + executed_actions, + Some((co_localizations,consu_set,sim_map))); // *** Transition To Firing + let tran_to_firing : GraphVizEdge; { let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); - tran_gv_options.push( GraphvizEdgeStyleItem::LTail( format!("cluster_i{}",parent_state_id) ) ); - self.write_edge(format!("i{:}", parent_state_id), format!("f{:}", new_state_id), tran_gv_options); + tran_gv_options.push( GraphvizEdgeStyleItem::LTail( format!("cluster_n{}",parent_state_id) ) ); + tran_to_firing = GraphVizEdge::new(format!("a{:}", parent_state_id),state_firing.id.clone(),tran_gv_options); } - // *** Resulting Interaction Node - self.write_analysis_node(gen_ctx, co_localizations,new_state_id, new_interaction, &multi_trace,new_flags,is_simulation,sim_crit_loop,sim_crit_act); - // *** Transition To Interaction Node + // *** Resulting New Node + let new_node = make_graphic_logger_state(&self.temp_folder, + gen_ctx, + new_state_id, + new_interaction, + self.int_repr_sd, + self.int_repr_tt, + Some((co_localizations,multi_trace,new_flags,is_simulation,sim_crit_loop,sim_crit_act))); + // *** Transition To New Node + let tran_to_new : GraphVizEdge; { let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); - tran_gv_options.push( GraphvizEdgeStyleItem::LHead( format!("cluster_i{}",new_state_id) ) ); - self.write_edge(format!("f{:}", new_state_id), format!("i{:}", new_state_id), tran_gv_options); + tran_gv_options.push( GraphvizEdgeStyleItem::LHead( format!("cluster_n{}",new_state_id) ) ); + tran_to_new = GraphVizEdge::new(state_firing.id.clone(),format!("a{:}", new_state_id),tran_gv_options); } + // *** + self.graph.nodes.push(Box::new(state_firing)); + self.graph.edges.push(tran_to_firing); + self.graph.nodes.push(Box::new(new_node)); + self.graph.edges.push(tran_to_new); } fn log_hide(&mut self, @@ -109,62 +123,58 @@ impl AnalysisLogger for GraphicProcessLogger { new_state_id : u32, lfs_to_hide : &HashSet, hidden_interaction : &Interaction, - new_flags : &MultiTraceAnalysisFlags) { - // *** Parent Interaction Node - let parent_interaction_node_name = format!("i{:}", parent_state_id); - // *** Hiding Node - self.write_hiding(gen_ctx,new_state_id,lfs_to_hide); + new_flags : &MultiTraceAnalysisFlags, + is_simulation : bool, + sim_crit_loop : bool, + sim_crit_act : bool) { + let state_hiding = make_graphic_logger_hiding(&self.temp_folder,gen_ctx,new_state_id,lfs_to_hide); // *** Transition To Hiding + let tran_to_hiding : GraphVizEdge; { let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); tran_gv_options.push( GraphvizEdgeStyleItem::LineStyle( GvEdgeLineStyle::Dashed ) ); - tran_gv_options.push( GraphvizEdgeStyleItem::LTail( format!("cluster_i{}",parent_state_id) ) ); - self.write_edge(parent_interaction_node_name, format!("h{:}", new_state_id), tran_gv_options); + tran_gv_options.push( GraphvizEdgeStyleItem::LTail( format!("cluster_n{}",parent_state_id) ) ); + tran_to_hiding = GraphVizEdge::new(format!("a{:}", parent_state_id),state_hiding.id.clone(),tran_gv_options); } - // *** Resulting Interaction Node - self.write_analysis_node(gen_ctx, co_localizations,new_state_id, hidden_interaction, multi_trace, new_flags,false,false,false ); - // *** Transition To Interaction Node + // *** Resulting New Node + let new_node = make_graphic_logger_state(&self.temp_folder, + gen_ctx, + new_state_id, + hidden_interaction, + self.int_repr_sd, + self.int_repr_tt, + Some((co_localizations,multi_trace,new_flags,is_simulation,sim_crit_loop,sim_crit_act))); + // *** Transition To New Node + let tran_to_new : GraphVizEdge; { let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); tran_gv_options.push( GraphvizEdgeStyleItem::LineStyle( GvEdgeLineStyle::Dashed ) ); - tran_gv_options.push( GraphvizEdgeStyleItem::LHead( format!("cluster_i{}",new_state_id) ) ); - self.write_edge( format!("h{:}", new_state_id), format!("i{:}", new_state_id), tran_gv_options); + tran_gv_options.push( GraphvizEdgeStyleItem::LHead( format!("cluster_n{}",new_state_id) ) ); + tran_to_new = GraphVizEdge::new(state_hiding.id.clone(),format!("a{:}", new_state_id),tran_gv_options); } + // *** + self.graph.nodes.push(Box::new(state_hiding)); + self.graph.edges.push(tran_to_hiding); + self.graph.nodes.push(Box::new(new_node)); + self.graph.edges.push(tran_to_new); } fn log_filtered(&mut self, parent_state_id: u32, new_state_id: u32, elim_kind: &FilterEliminationKind) { - self.write_filtered(parent_state_id,new_state_id,elim_kind); + let (elim_node,elim_edge) = make_graphic_logger_filter(parent_state_id,new_state_id,elim_kind); + self.graph.nodes.push(Box::new(elim_node)); + self.graph.edges.push(elim_edge); } fn log_verdict(&mut self, parent_state_id: u32, verdict: &CoverageVerdict) { - // *** - let parent_interaction_node_name = format!("i{:}", parent_state_id); - // *** - let verdict_node_name = format!("v{:}", parent_state_id); - // ***** - let verdict_color = verdict.get_verdict_color(); - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Label( verdict.to_string() ) ); - node_gv_options.push( GraphvizNodeStyleItem::Color( verdict_color.clone() ) ); - node_gv_options.push( GraphvizNodeStyleItem::FontColor( GraphvizColor::beige ) ); - node_gv_options.push( GraphvizNodeStyleItem::FontSize( 16 ) ); - node_gv_options.push( GraphvizNodeStyleItem::FontName( "times-bold".to_string() ) ); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Diamond) ); - node_gv_options.push( GraphvizNodeStyleItem::Style(vec![GvNodeStyleKind::Filled]) ); - // *** - let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); - tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); - tran_gv_options.push( GraphvizEdgeStyleItem::LTail( format!("cluster_i{}",parent_state_id) ) ); - tran_gv_options.push( GraphvizEdgeStyleItem::Color( verdict_color ) ); - // ***** - self.write_node(verdict_node_name.clone(), node_gv_options); - self.write_edge( parent_interaction_node_name, verdict_node_name, tran_gv_options); + let (verd_node,verd_edge) = make_graphic_logger_verdict(parent_state_id,verdict); + self.graph.nodes.push(Box::new(verd_node)); + self.graph.edges.push(verd_edge); } } \ No newline at end of file diff --git a/src/loggers/graphic/glog_canon.rs b/src/loggers/graphic/glog_canon.rs new file mode 100644 index 0000000..c2f657d --- /dev/null +++ b/src/loggers/graphic/glog_canon.rs @@ -0,0 +1,189 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +use std::collections::HashSet; +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::position::position::Position; +use crate::core::execution::trace::trace::TraceAction; +use crate::core::transformation::transfokind::InteractionTransformationKind; +use crate::io::output::graphviz::cluster::cluster::GraphVizCluster; +use crate::io::output::graphviz::colors::GraphvizColor; +use crate::io::output::graphviz::edge::edge::GraphVizEdge; +use crate::io::output::graphviz::edge::style::{GraphvizEdgeStyle, GraphvizEdgeStyleItem, GvArrowHeadSide, GvArrowHeadStyle}; +use crate::io::output::graphviz::node::style::{GraphvizNodeStyle, GraphvizNodeStyleItem}; +use crate::loggers::graphic::get_graph::filter::make_graphic_logger_filter; +use crate::process::abstract_proc::common::FilterEliminationKind; +use crate::loggers::graphic::get_graph::state::make_graphic_logger_state; +use crate::loggers::graphic::get_graph::transition::{make_graphic_logger_firing, make_graphic_logger_string_label, make_graphic_logger_transformation}; +use crate::loggers::graphic::graphic_logger::GraphicProcessLogger; +use crate::process::canon_proc::interface::logger::CanonizationLogger; +use crate::process::canon_proc::manager::IntRefOrOldIdRef; +use crate::process::canon_proc::transformations::phases::CanonizationPhase; + + +impl CanonizationLogger for GraphicProcessLogger { + + fn log_init(&mut self, interaction: &Interaction, gen_ctx: &GeneralContext) { + { + let mut cluster_gv_options : GraphvizNodeStyle = Vec::new(); + cluster_gv_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::lightblue1 )); + cluster_gv_options.push(GraphvizNodeStyleItem::Label("phase 1".to_string())); + let cluster_phase_1 = GraphVizCluster::new("phase1".to_string(),cluster_gv_options,vec![],vec![]); + self.graph.clusters.push(cluster_phase_1); + } + { + let mut cluster_gv_options : GraphvizNodeStyle = Vec::new(); + cluster_gv_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::palegreen )); + cluster_gv_options.push(GraphvizNodeStyleItem::Label("phase 2".to_string())); + let cluster_phase_2 = GraphVizCluster::new("phase2".to_string(),cluster_gv_options,vec![],vec![]); + self.graph.clusters.push(cluster_phase_2); + } + let init_node = make_graphic_logger_state(&self.temp_folder,gen_ctx,1,interaction,self.int_repr_sd,self.int_repr_tt,None); + let phase_cluster = self.graph.get_specific_cluster(0).unwrap(); + phase_cluster.nodes.push(Box::new(init_node)); + } + + fn log_term(&mut self, options_as_str: &Vec) { + self.terminate(options_as_str); + } + + fn log_phase_change(&mut self, + gen_ctx : &GeneralContext, + parent_state_id: u32, + new_state_id: u32, + target_interaction : &IntRefOrOldIdRef) { + // *** + let state_transfo = make_graphic_logger_string_label(&self.temp_folder,new_state_id,"Phase Change".to_string()); + // *** Transition To Transformation + let tran_to_transfo : GraphVizEdge; + { + let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); + tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); + tran_gv_options.push( GraphvizEdgeStyleItem::LTail( format!("cluster_n{}",parent_state_id) ) ); + tran_to_transfo = GraphVizEdge::new(format!("a{:}", parent_state_id),state_transfo.id.clone(),tran_gv_options); + } + // *** Resulting New Node + let target_int_id : u32; + match target_interaction { + IntRefOrOldIdRef::OldIDRef(old_target_id) => { + target_int_id = *old_target_id; + }, + IntRefOrOldIdRef::IntRef(interaction) => { + target_int_id = new_state_id; + let new_node = make_graphic_logger_state(&self.temp_folder,gen_ctx,new_state_id,interaction,self.int_repr_sd,self.int_repr_tt,None); + let phase_cluster = self.graph.get_specific_cluster(1).unwrap(); + phase_cluster.nodes.push(Box::new(new_node)); + } + } + // *** Transition To New Node + let tran_to_new : GraphVizEdge; + { + let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); + tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); + tran_gv_options.push( GraphvizEdgeStyleItem::LHead( format!("cluster_n{}",target_int_id) ) ); + tran_to_new = GraphVizEdge::new(state_transfo.id.clone(),format!("a{:}", target_int_id),tran_gv_options); + } + // *** + self.graph.nodes.push(Box::new(state_transfo)); + self.graph.edges.push(tran_to_transfo); + self.graph.edges.push(tran_to_new); + } + + fn log_transformation(&mut self, + gen_ctx : &GeneralContext, + phase : &CanonizationPhase, + parent_state_id : u32, + new_state_id : u32, + transfo_kind : &InteractionTransformationKind, + position : &Position, + target_interaction : &IntRefOrOldIdRef) { + // *** + let state_transfo = make_graphic_logger_transformation(&self.temp_folder,new_state_id,transfo_kind,position); + // *** Transition To Transformation + let tran_to_transfo : GraphVizEdge; + { + let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); + tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); + tran_gv_options.push( GraphvizEdgeStyleItem::LTail( format!("cluster_n{}",parent_state_id) ) ); + tran_to_transfo = GraphVizEdge::new(format!("a{:}", parent_state_id),state_transfo.id.clone(),tran_gv_options); + } + // *** Resulting New Node + let target_int_id : u32; + match target_interaction { + IntRefOrOldIdRef::OldIDRef(old_target_id) => { + target_int_id = *old_target_id; + match phase { + CanonizationPhase::FirstDefactorize => { + let phase_cluster = self.graph.get_specific_cluster(0).unwrap(); + phase_cluster.nodes.push(Box::new(state_transfo)); + }, + CanonizationPhase::SecondFactorize => { + let phase_cluster = self.graph.get_specific_cluster(1).unwrap(); + phase_cluster.nodes.push(Box::new(state_transfo)); + } + } + }, + IntRefOrOldIdRef::IntRef(interaction) => { + target_int_id = new_state_id; + let new_node = make_graphic_logger_state(&self.temp_folder,gen_ctx,new_state_id,interaction,self.int_repr_sd,self.int_repr_tt,None); + match phase { + CanonizationPhase::FirstDefactorize => { + let phase_cluster = self.graph.get_specific_cluster(0).unwrap(); + phase_cluster.nodes.push(Box::new(state_transfo)); + phase_cluster.nodes.push(Box::new(new_node)); + }, + CanonizationPhase::SecondFactorize => { + let phase_cluster = self.graph.get_specific_cluster(1).unwrap(); + phase_cluster.nodes.push(Box::new(state_transfo)); + phase_cluster.nodes.push(Box::new(new_node)); + } + } + } + } + // *** Transition To New Node + let tran_to_new : GraphVizEdge; + { + let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); + tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); + tran_gv_options.push( GraphvizEdgeStyleItem::LHead( format!("cluster_n{}",target_int_id) ) ); + tran_to_new = GraphVizEdge::new(format!("t{:}", new_state_id),format!("a{:}", target_int_id),tran_gv_options); + } + // *** + self.graph.edges.push(tran_to_transfo); + self.graph.edges.push(tran_to_new); + } + + fn log_filtered(&mut self, + phase : &CanonizationPhase, + parent_state_id: u32, + new_state_id: u32, + elim_kind: &FilterEliminationKind) { + let (elim_node,elim_edge) = make_graphic_logger_filter(parent_state_id,new_state_id,elim_kind); + match phase { + CanonizationPhase::FirstDefactorize => { + let phase_cluater = self.graph.get_specific_cluster(0).unwrap(); + phase_cluater.nodes.push(Box::new(elim_node)); + }, + CanonizationPhase::SecondFactorize => { + let phase_cluater = self.graph.get_specific_cluster(1).unwrap(); + phase_cluater.nodes.push(Box::new(elim_node)); + } + } + self.graph.edges.push(elim_edge); + } + +} \ No newline at end of file diff --git a/src/loggers/graphic/glog_explo.rs b/src/loggers/graphic/glog_explo.rs index 389aca1..b12e797 100644 --- a/src/loggers/graphic/glog_explo.rs +++ b/src/loggers/graphic/glog_explo.rs @@ -14,21 +14,27 @@ See the License for the specific language governing permissions and limitations under the License. */ -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use crate::core::general_context::GeneralContext; use crate::core::language::syntax::interaction::Interaction; use crate::core::language::position::position::Position; use crate::core::execution::trace::trace::TraceAction; +use crate::io::output::graphviz::edge::edge::GraphVizEdge; +use crate::io::output::graphviz::edge::style::{GraphvizEdgeStyle, GraphvizEdgeStyleItem, GvArrowHeadSide, GvArrowHeadStyle}; +use crate::loggers::graphic::get_graph::filter::make_graphic_logger_filter; use crate::process::abstract_proc::common::FilterEliminationKind; use crate::process::explo_proc::interface::logger::ExplorationLogger; -use crate::output::rendering::graphviz::edge_style::{GraphvizEdgeStyle, GraphvizEdgeStyleItem, GvArrowHeadSide, GvArrowHeadStyle}; +use crate::loggers::graphic::get_graph::state::make_graphic_logger_state; +use crate::loggers::graphic::get_graph::transition::make_graphic_logger_firing; use crate::loggers::graphic::graphic_logger::GraphicProcessLogger; + + impl ExplorationLogger for GraphicProcessLogger { fn log_init(&mut self, interaction: &Interaction, gen_ctx: &GeneralContext) { - self.initiate(); - self.write_interaction(gen_ctx,1, interaction); + let init_node = make_graphic_logger_state(&self.temp_folder,gen_ctx,1,interaction,self.int_repr_sd,self.int_repr_tt,None); + self.graph.nodes.push(Box::new(init_node)); } fn log_term(&mut self, options_as_str: &Vec) { @@ -43,25 +49,36 @@ impl ExplorationLogger for GraphicProcessLogger { executed_actions: &HashSet, new_interaction: &Interaction) { // *** - self.write_firing_simple(gen_ctx,new_state_id,action_position,executed_actions); + let state_firing = make_graphic_logger_firing(&self.temp_folder,gen_ctx,new_state_id,action_position,executed_actions,None); // *** Transition To Firing + let tran_to_firing : GraphVizEdge; { let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); - self.write_edge(format!("i{:}", parent_state_id), format!("f{:}", new_state_id), tran_gv_options); + tran_gv_options.push( GraphvizEdgeStyleItem::LTail( format!("cluster_n{}",parent_state_id) ) ); + tran_to_firing = GraphVizEdge::new(format!("a{:}", parent_state_id),state_firing.id.clone(),tran_gv_options); } - // *** Resulting Interaction Node - self.write_interaction(gen_ctx, new_state_id, new_interaction); - // *** Transition To Interaction Node + // *** Resulting New Node + let new_node = make_graphic_logger_state(&self.temp_folder,gen_ctx,new_state_id,new_interaction,self.int_repr_sd,self.int_repr_tt,None); + // *** Transition To New Node + let tran_to_new : GraphVizEdge; { let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); - self.write_edge(format!("f{:}", new_state_id), format!("i{:}", new_state_id), tran_gv_options); + tran_gv_options.push( GraphvizEdgeStyleItem::LHead( format!("cluster_n{}",new_state_id) ) ); + tran_to_new = GraphVizEdge::new(state_firing.id.clone(),format!("a{:}", new_state_id),tran_gv_options); } + // *** + self.graph.nodes.push(Box::new(state_firing)); + self.graph.edges.push(tran_to_firing); + self.graph.nodes.push(Box::new(new_node)); + self.graph.edges.push(tran_to_new); } fn log_filtered(&mut self, parent_state_id: u32, new_state_id: u32, elim_kind: &FilterEliminationKind) { - self.write_filtered(parent_state_id,new_state_id,elim_kind); + let (elim_node,elim_edge) = make_graphic_logger_filter(parent_state_id,new_state_id,elim_kind); + self.graph.nodes.push(Box::new(elim_node)); + self.graph.edges.push(elim_edge); } fn log_notified_lastchild_explored(&mut self, gen_ctx : &GeneralContext, parent_id: u32) { diff --git a/src/loggers/graphic/graphic_logger.rs b/src/loggers/graphic/graphic_logger.rs index aa41382..3b6cd69 100644 --- a/src/loggers/graphic/graphic_logger.rs +++ b/src/loggers/graphic/graphic_logger.rs @@ -15,61 +15,49 @@ limitations under the License. */ -use std::collections::{HashMap, HashSet}; use std::fs; use std::fs::File; use std::io::Write; +use std::path::{Path, PathBuf}; use std::process::Command; -use crate::core::colocalizations::CoLocalizations; -use crate::core::execution::trace::multitrace::MultiTrace; -use crate::core::execution::trace::trace::TraceAction; -use crate::core::general_context::GeneralContext; -use crate::core::language::position::position::Position; -use crate::core::language::syntax::interaction::Interaction; +use crate::io::output::graphviz::colors::DotTranslatable; +use crate::io::output::graphviz::graph::GraphVizDiGraph; +use crate::loggers::graphic::conf::{GraphicProcessLoggerLayout, GraphicProcessLoggerOutputFormat}; -use crate::loggers::graphic::conf::{GraphicProcessLoggerInteractionRepresentation, GraphicProcessLoggerLayout, GraphicProcessLoggerOutputKind}; -use crate::output::rendering::custom_draw::multitrace::draw_mu::draw_multitrace; -use crate::output::rendering::custom_draw::seqdiag::interaction::draw_interaction; -use crate::output::rendering::custom_draw::transition::draw_firing::{draw_firing_simple,draw_firing_analysis}; -use crate::output::rendering::custom_draw::transition::draw_hiding::draw_hiding; -use crate::output::rendering::graphviz::common::*; -use crate::output::rendering::graphviz::edge_style::*; -use crate::output::rendering::graphviz::graph::*; -use crate::output::rendering::graphviz::node_style::*; +use crate::loggers::graphic::get_graph::filter::make_graphic_logger_filter; +use crate::loggers::graphic::get_graph::legend::make_graphic_logger_legend; use crate::process::abstract_proc::common::FilterEliminationKind; -use crate::process::ana_proc::interface::step::SimulationStepKind; -use crate::process::ana_proc::logic::flags::MultiTraceAnalysisFlags; // *** pub struct GraphicProcessLogger { - log_name : String, - file : File, - output_kind : GraphicProcessLoggerOutputKind, + output_format : GraphicProcessLoggerOutputFormat, layout : GraphicProcessLoggerLayout, - interaction_repr : GraphicProcessLoggerInteractionRepresentation + // *** + pub int_repr_sd : bool, + pub int_repr_tt : bool, + // *** + pub temp_folder : String, + // *** + parent_folder : String, + output_file_name : String, + // *** + pub graph : GraphVizDiGraph } impl GraphicProcessLogger { - pub fn new(log_name : String, - output_kind : GraphicProcessLoggerOutputKind, + pub fn new(output_format : GraphicProcessLoggerOutputFormat, layout : GraphicProcessLoggerLayout, - interaction_repr : GraphicProcessLoggerInteractionRepresentation) -> GraphicProcessLogger { - let file = File::create(&format!("{:}.dot",log_name)).unwrap(); + int_repr_sd : bool, + int_repr_tt : bool, + temp_folder : String, + parent_folder : String, + output_file_name : String) -> GraphicProcessLogger { // *** - return GraphicProcessLogger{ - log_name, - file, - output_kind, - layout, - interaction_repr} - } - - pub fn initiate(&mut self) { // empties temp directory if exists - match fs::remove_dir_all("./temp") { + match fs::remove_dir_all(&temp_folder) { Ok(_) => { // do nothing }, @@ -77,248 +65,64 @@ impl GraphicProcessLogger { // do nothing } } - // creates temp directory - fs::create_dir_all("./temp").unwrap(); - // *** - self.file.write("digraph G {\n".as_bytes() ); - self.file.write("compound=true;\n".as_bytes() ); - // *** - match self.layout { - GraphicProcessLoggerLayout::horizontal => { - self.file.write("rankdir=LR;\n".as_bytes() ); - }, - GraphicProcessLoggerLayout::vertical => { - self.file.write("rankdir=TB;\n".as_bytes() ); - } + // creates temp directory if not exist + fs::create_dir_all(&temp_folder).unwrap(); + // creates parent directory if not exist + if parent_folder != "".to_string() { + fs::create_dir_all(&parent_folder).unwrap(); } // *** - } - - pub fn write_node(&mut self, - node_name : String, - style : GraphvizNodeStyle) { - let gv_node = GraphVizNode{id : node_name, style : style}; - self.file.write( gv_node.to_dot_string().as_bytes() ); - self.file.write("\n".as_bytes() ); - } - - pub fn write_edge(&mut self, - origin_id : String, - target_id : String, - style : GraphvizEdgeStyle) { - let gv_edge = GraphVizEdge{origin_id, target_id, style}; - self.file.write( gv_edge.to_dot_string().as_bytes() ); - self.file.write("\n".as_bytes() ); + return GraphicProcessLogger{output_format, + layout, + int_repr_sd, + int_repr_tt, + temp_folder:temp_folder, + parent_folder:parent_folder, + output_file_name:output_file_name.clone(), + graph:GraphVizDiGraph::new()}; } pub fn terminate(&mut self, options_as_strs : &Vec) { - // *** LEGEND + self.graph.nodes.push(Box::new(make_graphic_logger_legend(options_as_strs))); + // *** + let dot_file_name = format!("{:}.dot", self.output_file_name); + let dot_file_path : PathBuf = [&self.temp_folder, &dot_file_name].iter().collect(); { - let mut legend_str = String::new(); - for opt_str in options_as_strs { - legend_str.push_str(opt_str); - legend_str.push_str("\\l"); - } // *** - let mut legend_node_gv_options : GraphvizNodeStyle = Vec::new(); - legend_node_gv_options.push( GraphvizNodeStyleItem::Label( legend_str ) ); - legend_node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - legend_node_gv_options.push( GraphvizNodeStyleItem::Style(vec![GvNodeStyleKind::Bold,GvNodeStyleKind::Rounded]) ); - legend_node_gv_options.push( GraphvizNodeStyleItem::FontSize( 18 ) ); - // *** - self.write_node( "legend".to_string(), legend_node_gv_options ); + let mut dot_file = File::create(dot_file_path.as_path()).unwrap(); + dot_file.write(self.graph.to_dot_string().as_bytes()); } // *** - self.file.write( "}".as_bytes() ); - // *** - match self.output_kind { - GraphicProcessLoggerOutputKind::png => { + match self.output_format { + GraphicProcessLoggerOutputFormat::png => { + let output_file_name = format!("{:}.png", self.output_file_name); + let output_file_path : PathBuf = [&self.parent_folder, &output_file_name].iter().collect(); + // *** let status = Command::new("dot") .arg("-Tpng") - .arg(&format!("{:}.dot",self.log_name)) + .arg(dot_file_path.as_path()) .arg("-o") - .arg(&format!("{:}.png",self.log_name)) + .arg(output_file_path.as_path()) .output(); + println!("{:?}",status); }, - GraphicProcessLoggerOutputKind::svg => { + GraphicProcessLoggerOutputFormat::svg => { + let output_file_name = format!("{:}.svg", self.output_file_name); + let output_file_path : PathBuf = [&self.parent_folder, &output_file_name].iter().collect(); + // *** let status = Command::new("dot") .arg("-Tsvg:cairo") - .arg(&format!("{:}.dot",self.log_name)) + .arg(dot_file_path.as_path()) .arg("-o") - .arg(&format!("{:}.svg",self.log_name)) + .arg(output_file_path.as_path()) .output(); + println!("{:?}",status); } } } - pub fn write_multitrace(&mut self, - gen_ctx : &GeneralContext, - co_localizations : &CoLocalizations, - new_state_id : u32, - multi_trace : &MultiTrace, - flags : &MultiTraceAnalysisFlags, - is_simulation : bool, - sim_crit_loop : bool, - sim_crit_act : bool) { - - // *** - let mu_img_path : String = format!("./temp/{:}_m{}.png", self.log_name ,new_state_id); - draw_multitrace(gen_ctx, - co_localizations, - &mu_img_path, - multi_trace, - flags, - is_simulation, - sim_crit_loop, - sim_crit_act); - // *** - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Image( mu_img_path ) ); - node_gv_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - // *** - let current_node_name = format!("m{:}", new_state_id); - self.write_node(current_node_name, node_gv_options); - } - - pub fn write_interaction(&mut self, - gen_ctx : &GeneralContext, - new_state_id : u32, - new_interaction : &Interaction) { - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - if new_interaction != &Interaction::Empty { - let int_img_path : String = format!("./temp/{:}_i{}.png", self.log_name ,new_state_id); - draw_interaction(gen_ctx,&int_img_path, new_interaction); - node_gv_options.push( GraphvizNodeStyleItem::Image( int_img_path ) ); - node_gv_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); - } else { - node_gv_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); - node_gv_options.push(GraphvizNodeStyleItem::FillColor( GraphvizColor::white )); - } - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - // *** - let current_node_name = format!("i{:}", new_state_id); - self.write_node(current_node_name, node_gv_options); - } - - pub fn write_firing_simple(&mut self, - gen_ctx : &GeneralContext, - new_state_id : u32, - action_position : &Position, - executed_actions : &HashSet,) { - let firing_node_path : String = format!("./temp/{:}_f{}.png", self.log_name ,new_state_id); - draw_firing_simple(&firing_node_path, - gen_ctx, - action_position, - executed_actions); - // *** - let mut firing_gv_node_options : GraphvizNodeStyle = Vec::new(); - firing_gv_node_options.push( GraphvizNodeStyleItem::Image( firing_node_path ) ); - firing_gv_node_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); - firing_gv_node_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - // *** - let firing_node_name = format!("f{:}", new_state_id); - self.write_node( firing_node_name.clone(), firing_gv_node_options); - } - - pub fn write_firing_analysis(&mut self, - gen_ctx : &GeneralContext, - co_localizations : &CoLocalizations, - new_state_id : u32, - action_position : &Position, - executed_actions : &HashSet, - consu_set : &HashSet, - sim_map : &HashMap) { - let firing_node_path : String = format!("./temp/{:}_f{}.png", self.log_name ,new_state_id); - draw_firing_analysis(&firing_node_path, - gen_ctx, - co_localizations, - action_position, - executed_actions, - consu_set, - sim_map); - // *** - let mut firing_gv_node_options : GraphvizNodeStyle = Vec::new(); - firing_gv_node_options.push( GraphvizNodeStyleItem::Image( firing_node_path ) ); - firing_gv_node_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); - firing_gv_node_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - // *** - let firing_node_name = format!("f{:}", new_state_id); - self.write_node( firing_node_name.clone(), firing_gv_node_options); - } - - pub fn write_hiding(&mut self, - gen_ctx : &GeneralContext, - new_state_id : u32, - lfs_to_hide: &HashSet) { - let hiding_node_path : String = format!("./temp/{:}_h{}.png", self.log_name ,new_state_id); - draw_hiding(&hiding_node_path,gen_ctx,lfs_to_hide); - // *** - let mut hiding_gv_node_options : GraphvizNodeStyle = Vec::new(); - hiding_gv_node_options.push( GraphvizNodeStyleItem::Image( hiding_node_path ) ); - hiding_gv_node_options.push(GraphvizNodeStyleItem::Label( "".to_string() )); - hiding_gv_node_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Rectangle) ); - // *** - let hiding_node_name = format!("h{:}", new_state_id); - self.write_node(hiding_node_name, hiding_gv_node_options); - } - - pub fn write_filtered(&mut self, - parent_state_id : u32, - new_state_id : u32, - elim_kind : &FilterEliminationKind) { - // *** Node names - let parent_interaction_node_name = format!("i{:}", parent_state_id); - let elim_node_name = format!("e{:}", new_state_id); - // *** - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - // ***** - node_gv_options.push( GraphvizNodeStyleItem::Label( elim_kind.to_string() ) ); - node_gv_options.push( GraphvizNodeStyleItem::Color( GraphvizColor::burlywood4 ) ); - node_gv_options.push( GraphvizNodeStyleItem::FontColor( GraphvizColor::beige ) ); - node_gv_options.push( GraphvizNodeStyleItem::FontSize( 16 ) ); - node_gv_options.push( GraphvizNodeStyleItem::FontName( "times-bold".to_string() ) ); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::Pentagon) ); - node_gv_options.push( GraphvizNodeStyleItem::Style(vec![GvNodeStyleKind::Filled]) ); - // *** - self.write_node( elim_node_name.clone(), node_gv_options); - // *** - let mut tran_gv_options : GraphvizEdgeStyle = Vec::new(); - tran_gv_options.push( GraphvizEdgeStyleItem::Head( GvArrowHeadStyle::Vee(GvArrowHeadSide::Both) ) ); - tran_gv_options.push( GraphvizEdgeStyleItem::Color( GraphvizColor::burlywood4 ) ); - // *** - self.write_edge( parent_interaction_node_name, elim_node_name, tran_gv_options); - } - - - pub fn write_analysis_node(&mut self, - gen_ctx : &GeneralContext, - co_localizations : &CoLocalizations, - new_state_id : u32, - new_interaction : &Interaction, - multi_trace : &MultiTrace, - flags : &MultiTraceAnalysisFlags, - is_simulation : bool, - sim_crit_loop : bool, - sim_crit_act : bool) { - self.file.write(format!("subgraph cluster_i{} {{\n",new_state_id).as_bytes() ); - self.file.write("style=filled;color=lightgrey;\n".as_bytes() ); - // first node - self.write_multitrace(gen_ctx, - co_localizations, - new_state_id, - multi_trace, - flags, - is_simulation, - sim_crit_loop, - sim_crit_act); - self.write_interaction(gen_ctx,new_state_id,new_interaction); - // - self.file.write("}\n".as_bytes() ); - } - } diff --git a/src/loggers/graphic/mod.rs b/src/loggers/graphic/mod.rs index 7d77ab0..a91cc81 100644 --- a/src/loggers/graphic/mod.rs +++ b/src/loggers/graphic/mod.rs @@ -15,8 +15,11 @@ limitations under the License. */ +mod get_graph; + pub mod verdict; pub mod graphic_logger; pub mod conf; pub mod glog_explo; -pub mod glog_ana; \ No newline at end of file +pub mod glog_ana; +pub mod glog_canon; \ No newline at end of file diff --git a/src/loggers/graphic/verdict.rs b/src/loggers/graphic/verdict.rs index 7d4d9b3..22d4bc0 100644 --- a/src/loggers/graphic/verdict.rs +++ b/src/loggers/graphic/verdict.rs @@ -16,7 +16,7 @@ limitations under the License. use crate::process::ana_proc::logic::verdicts::CoverageVerdict; -use crate::output::rendering::graphviz::common::GraphvizColor; +use crate::io::output::graphviz::colors::GraphvizColor; impl CoverageVerdict { diff --git a/src/loggers/tracegen/tracegen_logger.rs b/src/loggers/tracegen/tracegen_logger.rs index 686f9c8..83f9267 100644 --- a/src/loggers/tracegen/tracegen_logger.rs +++ b/src/loggers/tracegen/tracegen_logger.rs @@ -20,27 +20,33 @@ limitations under the License. use std::collections::{HashMap, HashSet}; use std::fs; +use std::path::PathBuf; use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::MultiTrace; use crate::core::general_context::GeneralContext; use crate::core::execution::trace::trace::TraceAction; use crate::loggers::tracegen::conf::TracegenProcessLoggerGeneration; -use crate::output::to_hfiles::multitrace_to_htf::write_multi_trace_into_file; +use crate::io::file_extensions::HIBOU_TRACE_FILE_EXTENSION; +use crate::io::output::to_hfiles::trace::to_htf::write_multi_trace_into_file; pub struct TraceGenProcessLogger { - int_name : String, pub generation : TracegenProcessLoggerGeneration, // *** pub trace_map : HashMap, - pub co_localizations : CoLocalizations + pub co_localizations : CoLocalizations, + // *** + pub parent_folder_name : String, + pub trace_prefix : String + // *** } impl TraceGenProcessLogger { - pub fn new(name: String, - generation: TracegenProcessLoggerGeneration, - co_localizations : CoLocalizations) -> TraceGenProcessLogger { + pub fn new(generation: TracegenProcessLoggerGeneration, + co_localizations : CoLocalizations, + parent_folder_name : String, + trace_prefix : String) -> TraceGenProcessLogger { // *** let mut empty_mutrace : MultiTrace = vec![]; for cl in &co_localizations.locs_lf_ids { @@ -50,17 +56,14 @@ impl TraceGenProcessLogger { trace_map.insert( 1, empty_mutrace); // *** return TraceGenProcessLogger { - int_name: name, generation, trace_map, - co_localizations + co_localizations, + parent_folder_name, + trace_prefix } } - fn proc_name(&self) -> String { - return format!("tracegen_{}", self.int_name); - } - fn get_lf_coloc_id(&self, lf_id : usize) -> Option { for (coloc_id,coloc) in self.co_localizations.locs_lf_ids.iter().enumerate() { if coloc.contains(&lf_id) { @@ -72,7 +75,7 @@ impl TraceGenProcessLogger { pub fn initiate(&mut self) { // empties temp directory if exists - match fs::remove_dir_all(format!("./{:}", self.proc_name())) { + match fs::remove_dir_all(format!("./{:}", self.parent_folder_name)) { Ok(_) => { // do nothing }, @@ -81,7 +84,7 @@ impl TraceGenProcessLogger { } } // creates temp directory - fs::create_dir_all(format!("./{:}", self.proc_name())).unwrap(); + fs::create_dir_all(format!("./{:}", self.parent_folder_name)).unwrap(); } pub fn add_actions(&mut self, parent_id : u32, new_id : u32, new_actions : &HashSet) { @@ -108,7 +111,8 @@ impl TraceGenProcessLogger { gen_ctx : &GeneralContext, state_id : u32) { let mutrace_as_vec = self.trace_map.get(&state_id).unwrap(); - let file_path = format!("./{:}/{:}_t{:}", self.proc_name(), self.int_name, state_id); - write_multi_trace_into_file(&file_path, gen_ctx, &self.co_localizations,mutrace_as_vec); + let file_name = format!("{:}t{:}.{:}", self.trace_prefix, state_id, HIBOU_TRACE_FILE_EXTENSION); + let path : PathBuf = [&self.parent_folder_name, &file_name].iter().collect(); + write_multi_trace_into_file(path.as_path(), gen_ctx, &self.co_localizations,mutrace_as_vec); } } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index c8c3cd6..fc7747d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,9 +41,8 @@ extern crate rand; // ********** pub mod core; -pub mod output; +pub mod io; pub mod ui; -pub mod input; pub mod plantuml; //pub mod canonize; //pub mod merge_gates; diff --git a/src/merge_gates/merge.rs b/src/merge_gates/merge.rs index 96e4c95..d686efc 100644 --- a/src/merge_gates/merge.rs +++ b/src/merge_gates/merge.rs @@ -24,105 +24,7 @@ use crate::core::general_context::GeneralContext; use crate::canonize::transformations::phases::InteractionTermTransformation; use crate::canonize::transformations::transfokind::TransformationKind; -pub fn get_all_merges_rec(interaction : &Interaction) -> Vec { - let mut results = get_possible_merges_from_root(interaction); - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - for left_transfo in get_all_merges_rec(i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Strict(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_merges_rec(i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Strict(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, - &Interaction::Seq(ref i1, ref i2) => { - for left_transfo in get_all_merges_rec(i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Seq(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_merges_rec(i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Seq(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, - &Interaction::CoReg(ref cr, ref i1, ref i2) => { - for left_transfo in get_all_merges_rec(i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::CoReg(cr.clone(), Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_merges_rec(i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::CoReg(cr.clone(), i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, - &Interaction::Par(ref i1, ref i2) => { - for left_transfo in get_all_merges_rec(i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Par(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_merges_rec(i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Par(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, - &Interaction::Alt(ref i1, ref i2) => { - for left_transfo in get_all_merges_rec(i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Alt(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_merges_rec(i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Alt(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, - &Interaction::Loop(ref lk, ref i1) => { - for left_transfo in get_all_merges_rec(i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Loop(lk.clone(), Box::new(left_transfo.result)) - ) ); - } - }, - /*&Interaction::And(ref i1, ref i2) => { - for left_transfo in get_possible_merges_from_root(i1) { - results.push( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::And(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_possible_merges_from_root(i2) { - results.push( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::And(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - },*/ - _ => {} - } - return results; -} + fn get_possible_merges_from_root(interaction : &Interaction) -> Vec { let mut merges : Vec = Vec::new(); @@ -154,229 +56,15 @@ fn get_possible_merges_from_root(interaction : &Interaction) -> Vec {} } }, - (Interaction::Strict(ref i11, ref i12),Interaction::Strict(ref i21, ref i22)) => { - let new_left = Interaction::And( i11.clone(), i21.clone() ); - let new_right = Interaction::And( i12.clone(), i22.clone() ); - let new_int = Interaction::Strict(Box::new(new_left), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeSkip, - Position::Epsilon, - new_int)); - }, - (Interaction::Seq(ref i11, ref i12),Interaction::Seq(ref i21, ref i22)) => { - let new_left = Interaction::And( i11.clone(), i21.clone() ); - let new_right = Interaction::And( i12.clone(), i22.clone() ); - let new_int = Interaction::Seq(Box::new(new_left), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeSkip, - Position::Epsilon, - new_int)); - }, - (Interaction::Par(ref i11, ref i12),Interaction::Par(ref i21, ref i22)) => { - let new_left = Interaction::And( i11.clone(), i21.clone() ); - let new_right = Interaction::And( i12.clone(), i22.clone() ); - let new_int = Interaction::Par(Box::new(new_left), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeSkip, - Position::Epsilon, - new_int)); - }, - (Interaction::Alt(ref i11, ref i12),Interaction::Alt(ref i21, ref i22)) => { - let new_left = Interaction::And( i11.clone(), i21.clone() ); - let new_right = Interaction::And( i12.clone(), i22.clone() ); - let new_int = Interaction::Alt(Box::new(new_left), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeSkip, - Position::Epsilon, - new_int)); - }, - _ => {} - } - // *** - match **i1 { - Interaction::Strict(ref i11, ref i12) => { - { - let new_left = Interaction::And( i11.clone(), i2.clone() ); - let new_int = Interaction::Strict(Box::new(new_left), i12.clone() ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft1, - Position::Epsilon, - new_int)); - } - { - let new_right = Interaction::And( i12.clone(), i2.clone() ); - let new_int = Interaction::Strict( i11.clone(), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndRight1, - Position::Epsilon, - new_int)); - } - }, - Interaction::Seq(ref i11, ref i12) => { - { - let new_left = Interaction::And( i11.clone(), i2.clone() ); - let new_int = Interaction::Seq(Box::new(new_left), i12.clone() ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft1, - Position::Epsilon, - new_int)); - } - { - let new_right = Interaction::And( i12.clone(), i2.clone() ); - let new_int = Interaction::Seq( i11.clone(), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndRight1, - Position::Epsilon, - new_int)); - } - }, - Interaction::Par(ref i11, ref i12) => { - { - let new_left = Interaction::And( i11.clone(), i2.clone() ); - let new_int = Interaction::Par(Box::new(new_left), i12.clone() ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft1, - Position::Epsilon, - new_int)); - } - { - let new_right = Interaction::And( i12.clone(), i2.clone() ); - let new_int = Interaction::Par( i11.clone(), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndRight1, - Position::Epsilon, - new_int)); - } - }, - Interaction::Alt(ref i11, ref i12) => { - { - let new_left = Interaction::And( i11.clone(), i2.clone() ); - let new_int = Interaction::Alt(Box::new(new_left), i12.clone() ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft1, - Position::Epsilon, - new_int)); - } - { - let new_right = Interaction::And( i12.clone(), i2.clone() ); - let new_int = Interaction::Alt( i11.clone(), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndRight1, - Position::Epsilon, - new_int)); - } - }, - Interaction::Loop(ref lk, ref i11) => { - let new_sub = Interaction::And( i11.clone(), i2.clone() ); - let new_int = Interaction::Loop(lk.clone(), Box::new(new_sub) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft1, - Position::Epsilon, - new_int)); - }, + _ => {} } // *** - match **i2 { - Interaction::Strict(ref i21, ref i22) => { - { - let new_left = Interaction::And( i1.clone(), i21.clone() ); - let new_int = Interaction::Strict(Box::new(new_left), i22.clone() ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft2, - Position::Epsilon, - new_int)); - } - { - let new_right = Interaction::And( i1.clone(), i22.clone() ); - let new_int = Interaction::Strict( i21.clone(), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndRight2, - Position::Epsilon, - new_int)); - } - }, - Interaction::Seq(ref i21, ref i22) => { - { - let new_left = Interaction::And( i1.clone(), i21.clone() ); - let new_int = Interaction::Seq(Box::new(new_left), i22.clone() ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft2, - Position::Epsilon, - new_int)); - } - { - let new_right = Interaction::And( i1.clone(), i22.clone() ); - let new_int = Interaction::Seq( i21.clone(), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndRight2, - Position::Epsilon, - new_int)); - } - }, - Interaction::Par(ref i21, ref i22) => { - { - let new_left = Interaction::And( i1.clone(), i21.clone() ); - let new_int = Interaction::Par(Box::new(new_left), i22.clone() ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft2, - Position::Epsilon, - new_int)); - } - { - let new_right = Interaction::And( i1.clone(), i22.clone() ); - let new_int = Interaction::Par( i21.clone(), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndRight2, - Position::Epsilon, - new_int)); - } - }, - Interaction::Alt(ref i21, ref i22) => { - { - let new_left = Interaction::And( i1.clone(), i21.clone() ); - let new_int = Interaction::Alt(Box::new(new_left), i22.clone() ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft2, - Position::Epsilon, - new_int)); - } - { - let new_right = Interaction::And( i1.clone(), i22.clone() ); - let new_int = Interaction::Alt( i21.clone(), Box::new(new_right) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndRight2, - Position::Epsilon, - new_int)); - } - }, - Interaction::Loop(ref lk, ref i21) => { - let new_sub = Interaction::And( i1.clone(), i21.clone() ); - let new_int = Interaction::Loop(lk.clone(), Box::new(new_sub) ); - merges.push(InteractionTermTransformation::new(TransformationKind::MergeAndLeft2, - Position::Epsilon, - new_int)); - }, - _ => {} - } - }, _ => {} } return merges; } -fn merge_actions(emission : (&usize,&Vec,&usize), - reception : (&usize,&Option,&usize)) -> Option { - let (src_lf_id,target_refs,src_ms_id) = emission; - let (tar_lf_id,tar_orig,tar_ms_id) = reception; - if src_ms_id == tar_ms_id { - match tar_orig { - None => {}, - Some( tar_gt_id_orig ) => { - let mut new_targets : Vec = Vec::new(); - let mut got_it = false; - for targ_ref in target_refs { - match targ_ref { - EmissionTargetRef::Lifeline(ref other_tar_lf_id) => { - new_targets.push( EmissionTargetRef::Lifeline(*other_tar_lf_id) ); - }, - EmissionTargetRef::Gate(ref gate_id) => { - if gate_id == tar_gt_id_orig && !got_it { - new_targets.push( EmissionTargetRef::Lifeline(*tar_lf_id) ); - got_it = true; - } else { - new_targets.push( EmissionTargetRef::Gate(*gate_id) ); - } - } - } - } - if got_it { - return Some( ObservableAction{lf_id:*src_lf_id,act_kind:ObservableActionKind::Emission(new_targets),ms_id:*src_ms_id} ); - } - } - } - } - return None; -} diff --git a/src/merge_gates/process.rs b/src/merge_gates/process.rs index f4d8e4d..bf61b37 100644 --- a/src/merge_gates/process.rs +++ b/src/merge_gates/process.rs @@ -22,10 +22,10 @@ use std::collections::{HashSet,HashMap}; use std::process::Command; -use crate::output::rendering::graphviz::graph::*; -use crate::output::rendering::graphviz::node_style::*; -use crate::output::rendering::graphviz::edge_style::*; -use crate::output::rendering::graphviz::common::*; +use crate::io::output::graphviz::graph::*; +use crate::io::output::graphviz::node_style::*; +use crate::io::output::graphviz::edge_style::*; +use crate::io::output::graphviz::common::*; use crate::core::language::syntax::interaction::{Interaction}; diff --git a/src/output/commons/textual_representation/model/model_action.rs b/src/output/commons/textual_representation/model/model_action.rs deleted file mode 100644 index f8014c8..0000000 --- a/src/output/commons/textual_representation/model/model_action.rs +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - - -use crate::core::language::syntax::action::{EmissionAction, ReceptionAction}; - -pub fn emission_as_text(em_act : &EmissionAction) -> String { - todo!() -} - - -pub fn reception_as_text(em_act : &ReceptionAction) -> String { - todo!() -} \ No newline at end of file diff --git a/src/output/commons/textual_representation/position.rs b/src/output/commons/textual_representation/position.rs deleted file mode 100644 index 7df55a1..0000000 --- a/src/output/commons/textual_representation/position.rs +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -use crate::core::language::position::position::Position; -use crate::output::commons::textual_convention::{SYNTAX_POSITION_EPSILON,SYNTAX_POSITION_LEFT,SYNTAX_POSITION_RIGHT}; - -pub fn position_to_text(position : &Position) -> String { - match position { - Position::Left(ref in_self) => { - let mut my_string = SYNTAX_POSITION_LEFT.to_string(); - let sub_pos = position_to_text( &(*in_self) ); - if sub_pos.starts_with(SYNTAX_POSITION_EPSILON) { - let text_vec = sub_pos.chars().collect::>(); - my_string.push_str( &text_vec[1..].iter().cloned().collect::() ); - } else { - my_string.push_str( &sub_pos ); - } - return my_string; - }, - Position::Right(ref in_self) => { - let mut my_string = SYNTAX_POSITION_RIGHT.to_string(); - let sub_pos = position_to_text( &(*in_self) ); - if sub_pos.starts_with(SYNTAX_POSITION_EPSILON) { - let text_vec = sub_pos.chars().collect::>(); - my_string.push_str( &text_vec[1..].iter().cloned().collect::() ); - } else { - my_string.push_str( &sub_pos ); - } - return my_string; - }, - Position::Epsilon(sub_pos) => { - match sub_pos { - None => { - return SYNTAX_POSITION_EPSILON.to_string(); - }, - Some( pos_idx ) => { - return format!("{:}({:})", SYNTAX_POSITION_EPSILON, pos_idx); - } - } - } - } -} \ No newline at end of file diff --git a/src/output/rendering/custom_draw/seqdiag/mod.rs b/src/output/rendering/custom_draw/seqdiag/mod.rs deleted file mode 100644 index cb6dfd8..0000000 --- a/src/output/rendering/custom_draw/seqdiag/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -mod dimensions_tools; -mod lf_coords; -mod action; -mod img_content; -mod img_frame; -pub mod interaction; diff --git a/src/output/rendering/custom_draw/term/action_repr.rs b/src/output/rendering/custom_draw/term/action_repr.rs deleted file mode 100644 index bbab48b..0000000 --- a/src/output/rendering/custom_draw/term/action_repr.rs +++ /dev/null @@ -1,87 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -use crate::core::general_context::GeneralContext; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::output::rendering::custom_draw::term::util::position_to_id; -use crate::output::rendering::graphviz::common::*; -use crate::output::rendering::graphviz::graph::*; -use crate::output::rendering::graphviz::node_style::*; - -pub fn emission_repr(to_write : &mut String, - em_act : &EmissionAction, - gen_ctx : &GeneralContext, - interaction_name : &String, - current_pos : Position) { - let ms_name = gen_ctx.get_ms_name(em_act.ms_id).unwrap(); - let lf_name = gen_ctx.get_lf_name(em_act.origin_lf_id).unwrap(); - // *** - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::PlainText) ); - // *** - let node_name = format!("{}p{}",interaction_name,position_to_id(¤t_pos)); - // *** - let mut targ_names : Vec = Vec::new(); - for targ_ref in &em_act.targets { - match targ_ref { - EmissionTargetRef::Lifeline(tar_lf_id) => { - targ_names.push( gen_ctx.get_lf_name(*tar_lf_id).unwrap() ); - }, - EmissionTargetRef::Gate(tar_gt_id) => { - targ_names.push( gen_ctx.get_gt_name(*tar_gt_id).unwrap() ); - } - } - } - // *** - node_gv_options.push( GraphvizNodeStyleItem::Label( format!("{}-{}>({})", &lf_name, &ms_name, &targ_names.join(",")) ) ); - // *** - let gv_node = GraphVizNode{id : node_name, style : node_gv_options}; - to_write.push_str( &gv_node.to_dot_string() ); - to_write.push_str("\n"); -} - - -pub fn reception_repr(to_write : &mut String, - rc_act : &ReceptionAction, - gen_ctx : &GeneralContext, - interaction_name : &String, - current_pos : Position) { - let ms_name = gen_ctx.get_ms_name(rc_act.ms_id).unwrap(); - // *** - let mut node_gv_options : GraphvizNodeStyle = Vec::new(); - node_gv_options.push( GraphvizNodeStyleItem::Shape(GvNodeShape::PlainText) ); - // *** - let node_name = format!("{}p{}",interaction_name,position_to_id(¤t_pos)); - // *** - let mut targ_names : Vec = Vec::new(); - for rcp_lf_id in &rc_act.recipients { - targ_names.push( gen_ctx.get_lf_name(*rcp_lf_id).unwrap() ); - } - // *** - match rc_act.origin_gt_id { - None => { - node_gv_options.push( GraphvizNodeStyleItem::Label( format!("|-{}>({})", &ms_name, &targ_names.join(",")) ) );}, - Some(orig_gt_id) => { - let gt_name = gen_ctx.get_gt_name(orig_gt_id).unwrap(); - node_gv_options.push( GraphvizNodeStyleItem::Label( format!("{}-{}>({})", >_name, &ms_name, &targ_names.join(",")) ) ); - } - } - // *** - let gv_node = GraphVizNode{id : node_name, style : node_gv_options}; - to_write.push_str( &gv_node.to_dot_string() ); - to_write.push_str("\n"); -} \ No newline at end of file diff --git a/src/output/rendering/custom_draw/term/term_repr_out.rs b/src/output/rendering/custom_draw/term/term_repr_out.rs deleted file mode 100644 index 3e5bd56..0000000 --- a/src/output/rendering/custom_draw/term/term_repr_out.rs +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -use std::fs::File; -use std::io::Write; -use std::process::Command; - -use crate::core::general_context::GeneralContext; -use crate::core::language::syntax::interaction::Interaction; -use crate::output::rendering::custom_draw::term::term_repr::interaction_repr; - -pub fn to_term_repr(name : &String, - interaction : &Interaction, - gen_ctx : &GeneralContext) { - let mut file = File::create(&format!("{:}.dot",name)).unwrap(); - file.write( interaction_repr(interaction,gen_ctx,name,false).as_bytes() ); - let status = Command::new("dot") - .arg("-Tsvg:cairo") - .arg(&format!("{:}.dot",name)) - .arg("-o") - .arg(&format!("{:}.svg",name)) - .output(); -} - -pub fn to_term_repr_temp(name : &String, - interaction : &Interaction, - gen_ctx : &GeneralContext) { - let mut file = File::create(&format!("temp/{:}.dot",name)).unwrap(); - file.write( interaction_repr(interaction,gen_ctx,name,false).as_bytes() ); - let status = Command::new("dot") - .arg("-Tpng") - .arg(&format!("temp/{:}.dot",name)) - .arg("-o") - .arg(&format!("temp/{:}.png",name)) - .output(); -} - - - - - - - - - - diff --git a/src/output/rendering/custom_draw/term/util.rs b/src/output/rendering/custom_draw/term/util.rs deleted file mode 100644 index d5b1c60..0000000 --- a/src/output/rendering/custom_draw/term/util.rs +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -use crate::core::language::position::position::Position; - -pub(crate) fn position_to_id(position : &Position) -> String { - match position { - Position::Left(ref in_self) => { - let mut my_string = "1".to_string(); - let sub_pos = position_to_id( &(*in_self) ); - if sub_pos != "0".to_string() { - my_string.push_str( &sub_pos ); - } - return my_string; - }, - Position::Right(ref in_self) => { - let mut my_string = "2".to_string(); - let sub_pos = position_to_id( &(*in_self) ); - if sub_pos != "0".to_string() { - my_string.push_str( &sub_pos ); - } - return my_string; - }, - Position::Epsilon(sub_pos) => { - match sub_pos { - None => { - return "0".to_string(); - }, - Some(sbp_idx) => { - return format!("s{:}",sbp_idx); - } - } - } - } -} diff --git a/src/output/rendering/graphviz/mod.rs b/src/output/rendering/graphviz/mod.rs deleted file mode 100644 index f43d3a9..0000000 --- a/src/output/rendering/graphviz/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -pub mod common; -pub mod edge_style; -pub mod graph; -pub mod node_style; \ No newline at end of file diff --git a/src/process/ana_proc/interface/logger.rs b/src/process/ana_proc/interface/logger.rs index 6692897..f70ffb7 100644 --- a/src/process/ana_proc/interface/logger.rs +++ b/src/process/ana_proc/interface/logger.rs @@ -67,7 +67,10 @@ pub trait AnalysisLogger { new_state_id : u32, lfs_to_hide : &HashSet, hidden_interaction : &Interaction, - new_flags : &MultiTraceAnalysisFlags); + new_flags : &MultiTraceAnalysisFlags, + is_simulation : bool, + sim_crit_loop : bool, + sim_crit_act : bool); fn log_filtered(&mut self, parent_state_id : u32, diff --git a/src/process/ana_proc/manager.rs b/src/process/ana_proc/manager.rs index 4afbc54..1ae8891 100644 --- a/src/process/ana_proc/manager.rs +++ b/src/process/ana_proc/manager.rs @@ -517,6 +517,7 @@ impl AnalysisProcessManager { new_flags : &MultiTraceAnalysisFlags, parent_state_id : u32, new_state_id :u32) { + let (is_simulation,sim_crit_loop,sim_crit_act) = self.ana_kind.get_sim_crits(); for logger in self.manager.loggers.iter_mut() { logger.log_hide(&self.manager.gen_ctx, &self.co_localizations, @@ -525,7 +526,10 @@ impl AnalysisProcessManager { new_state_id, lfs_to_hide, new_interaction, - new_flags); + new_flags, + is_simulation, + sim_crit_loop, + sim_crit_act); } } } diff --git a/src/process/canon_proc/conf.rs b/src/process/canon_proc/interface/conf.rs similarity index 60% rename from src/process/canon_proc/conf.rs rename to src/process/canon_proc/interface/conf.rs index 3f9b234..113d4cb 100644 --- a/src/process/canon_proc/conf.rs +++ b/src/process/canon_proc/interface/conf.rs @@ -17,18 +17,21 @@ limitations under the License. -use crate::proc_refactoring::abstract_proc::AbstractConfiguration; -use crate::proc_refactoring::canon_proc::filter::{ExplorationFilter, ExplorationFilterCriterion}; -use crate::proc_refactoring::canon_proc::node::CanonizationNodeKind; -use crate::proc_refactoring::canon_proc::priorities::CanonizationPriorities; -use crate::proc_refactoring::canon_proc::step::CanonizationStepKind; + +use crate::process::abstract_proc::generic::AbstractConfiguration; +use crate::process::canon_proc::interface::filter::{CanonizationFilter, CanonizationFilterCriterion}; +use crate::process::canon_proc::interface::logger::CanonizationLogger; +use crate::process::canon_proc::interface::node::CanonizationNodeKind; +use crate::process::canon_proc::interface::priorities::CanonizationPriorities; +use crate::process::canon_proc::interface::step::CanonizationStepKind; pub struct CanonizationConfig {} impl AbstractConfiguration for CanonizationConfig { type NodeKind = CanonizationNodeKind; type StepKind = CanonizationStepKind; - type PrioritiesConf = CanonizationPriorities; + type Priorities = CanonizationPriorities; type Filter = CanonizationFilter; type FilterCriterion = CanonizationFilterCriterion; + type Logger = Box; } \ No newline at end of file diff --git a/src/process/canon_proc/filter.rs b/src/process/canon_proc/interface/filter.rs similarity index 51% rename from src/process/canon_proc/filter.rs rename to src/process/canon_proc/interface/filter.rs index e28230a..44a7f68 100644 --- a/src/process/canon_proc/filter.rs +++ b/src/process/canon_proc/interface/filter.rs @@ -16,53 +16,46 @@ limitations under the License. -use crate::proc_refactoring::abstract_proc::AbstractFilter; -use crate::proc_refactoring::explo_proc::conf::ExplorationConfig; -use crate::process::hibou_process::{FilterEliminationKind}; -pub struct ExplorationFilterCriterion { - pub loop_depth : u32 -} +use crate::process::abstract_proc::common::FilterEliminationKind; +use crate::process::abstract_proc::generic::AbstractFilter; +use crate::process::canon_proc::interface::conf::CanonizationConfig; + +pub struct CanonizationFilterCriterion; + -pub enum ExplorationFilter { - MaxLoopInstanciation(u32), +pub enum CanonizationFilter { MaxProcessDepth(u32), MaxNodeNumber(u32) } -impl std::string::ToString for ExplorationFilter { +impl std::string::ToString for CanonizationFilter { fn to_string(&self) -> String { match self { - ExplorationFilter::MaxLoopInstanciation(num) => { - return format!("MaxLoop={}",num); - }, - ExplorationFilter::MaxProcessDepth(num) => { + CanonizationFilter::MaxProcessDepth(num) => { return format!("MaxDepth={}",num); }, - ExplorationFilter::MaxNodeNumber(num) => { + CanonizationFilter::MaxNodeNumber(num) => { return format!("MaxNum={}",num); } } } } -impl AbstractFilter for ExplorationFilter { +impl AbstractFilter for CanonizationFilter { - fn apply_filter(&self, depth: u32, node_counter: u32, criterion: &ExplorationFilterCriterion) -> Option { + fn apply_filter(&self, depth: u32, + node_counter: u32, + criterion: &CanonizationFilterCriterion) -> Option { match self { - ExplorationFilter::MaxProcessDepth( max_depth ) => { + CanonizationFilter::MaxProcessDepth( max_depth ) => { if depth > *max_depth { return Some( FilterEliminationKind::MaxProcessDepth ); } }, - ExplorationFilter::MaxLoopInstanciation( loop_num ) => { - if criterion.loop_depth > *loop_num { - return Some( FilterEliminationKind::MaxLoopInstanciation ); - } - }, - ExplorationFilter::MaxNodeNumber( max_node_number ) => { + CanonizationFilter::MaxNodeNumber( max_node_number ) => { if node_counter >= *max_node_number { return Some( FilterEliminationKind::MaxNodeNumber ); } diff --git a/src/process/canon_proc/interface/logger.rs b/src/process/canon_proc/interface/logger.rs new file mode 100644 index 0000000..ffdb62f --- /dev/null +++ b/src/process/canon_proc/interface/logger.rs @@ -0,0 +1,60 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::position::position::Position; +use crate::core::transformation::transfokind::InteractionTransformationKind; +use crate::process::abstract_proc::common::FilterEliminationKind; +use crate::process::canon_proc::manager::IntRefOrOldIdRef; +use crate::process::canon_proc::transformations::phases::CanonizationPhase; + + +pub trait CanonizationLogger { + + fn log_init(&mut self, + interaction : &Interaction, + gen_ctx : &GeneralContext); + + fn log_term(&mut self, + options_as_str : &Vec); + + fn log_phase_change(&mut self, + gen_ctx : &GeneralContext, + parent_state_id : u32, + new_state_id : u32, + target_interaction : &IntRefOrOldIdRef); + + fn log_transformation(&mut self, + gen_ctx : &GeneralContext, + phase : &CanonizationPhase, + parent_state_id : u32, + new_state_id : u32, + transfo_kind : &InteractionTransformationKind, + position : &Position, + target_interaction : &IntRefOrOldIdRef); + + fn log_filtered(&mut self, + phase : &CanonizationPhase, + parent_state_id : u32, + new_state_id : u32, + elim_kind : &FilterEliminationKind); + +} + + diff --git a/src/process/canon_proc/interface/mod.rs b/src/process/canon_proc/interface/mod.rs new file mode 100644 index 0000000..c82de0f --- /dev/null +++ b/src/process/canon_proc/interface/mod.rs @@ -0,0 +1,26 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + +pub mod step; +pub mod filter; +pub mod conf; +pub mod priorities; +pub mod node; + +pub mod logger; + diff --git a/src/process/canon_proc/interface/node.rs b/src/process/canon_proc/interface/node.rs new file mode 100644 index 0000000..797a82b --- /dev/null +++ b/src/process/canon_proc/interface/node.rs @@ -0,0 +1,31 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + + + + +use crate::core::language::syntax::interaction::Interaction; +use crate::process::abstract_proc::generic::AbstractNodeKind; +use crate::process::canon_proc::transformations::phases::CanonizationPhase; + +pub struct CanonizationNodeKind { + pub interaction : Interaction, + pub phase : CanonizationPhase +} + +impl AbstractNodeKind for CanonizationNodeKind {} + diff --git a/src/process/canon_proc/priorities.rs b/src/process/canon_proc/interface/priorities.rs similarity index 72% rename from src/process/canon_proc/priorities.rs rename to src/process/canon_proc/interface/priorities.rs index 2a168ed..f80a10f 100644 --- a/src/process/canon_proc/priorities.rs +++ b/src/process/canon_proc/interface/priorities.rs @@ -14,9 +14,10 @@ See the License for the specific language governing permissions and limitations under the License. */ -use crate::proc_refactoring::abstract_proc::AbstractPrioritiesConf; +use crate::process::abstract_proc::generic::AbstractPriorities; + pub struct CanonizationPriorities { pub simpl : i32, pub flush : i32, @@ -36,17 +37,22 @@ impl CanonizationPriorities { defactorize : i32) -> CanonizationPriorities { return CanonizationPriorities{simpl,flush,invert,deduplicate,factorize,defactorize}; } + + pub fn default() -> CanonizationPriorities { + return CanonizationPriorities::new(0,0,0,0,0,0); + } } -impl AbstractPrioritiesConf for CanonizationPriorities { +impl AbstractPriorities for CanonizationPriorities { fn print_as_string(&self) -> String { let mut my_str = String::new(); - my_str.push_str( &format!("simpl={:},",self.simpl) ); + my_str.push_str( &format!("[simpl={:},",self.simpl) ); my_str.push_str( &format!("flush={:},",self.flush) ); my_str.push_str( &format!("invert={:},",self.invert) ); - my_str.push_str( &format!("deduplicate={:}",self.deduplicate) ); - my_str.push_str( &format!("factorize={:}",self.factorize) ); + my_str.push_str( &format!("deduplicate={:},",self.deduplicate) ); + my_str.push_str( &format!("factorize={:},",self.factorize) ); + my_str.push_str( &format!("defactorize={:}]",self.defactorize) ); return my_str; } diff --git a/src/process/canon_proc/step.rs b/src/process/canon_proc/interface/step.rs similarity index 50% rename from src/process/canon_proc/step.rs rename to src/process/canon_proc/interface/step.rs index 42f4110..2f366bd 100644 --- a/src/process/canon_proc/step.rs +++ b/src/process/canon_proc/interface/step.rs @@ -14,87 +14,104 @@ See the License for the specific language governing permissions and limitations under the License. */ -use crate::proc_refactoring::abstract_proc::AbstractStepKind; -use crate::proc_refactoring::canon_proc::conf::CanonizationConfig; -use crate::proc_refactoring::canon_proc::priorities::CanonizationPriorities; -use crate::proc_refactoring::canon_proc::transformations::phases::CanonizationTransformation; -use crate::proc_refactoring::canon_proc::transformations::transfokind::CanonizationTransformationKind; + +use crate::core::transformation::transfodef::InteractionTransformation; +use crate::core::transformation::transfokind::InteractionTransformationKind; +use crate::process::abstract_proc::generic::AbstractStepKind; +use crate::process::canon_proc::interface::conf::CanonizationConfig; +use crate::process::canon_proc::interface::priorities::CanonizationPriorities; + + + pub enum CanonizationStepKind { - Transform(CanonizationTransformation) + Transform(InteractionTransformation), + ChangePhase } - impl AbstractStepKind for CanonizationStepKind { fn get_priority(&self, process_priorities: &CanonizationPriorities) -> i32 { match self { + CanonizationStepKind::ChangePhase => { + return 0; + }, CanonizationStepKind::Transform( transfo ) => { let mut priority : i32 = 0; match transfo.kind { - CanonizationTransformationKind::SimplLeft => { - priority += process_priorities.simpl; - }, - CanonizationTransformationKind::SimplRight => { + InteractionTransformationKind::Simpl => { priority += process_priorities.simpl; }, - CanonizationTransformationKind::FlushLeft => { + InteractionTransformationKind::FlushLeft => { priority += process_priorities.flush; }, - CanonizationTransformationKind::FlushRight => { + InteractionTransformationKind::FlushRight => { priority += process_priorities.flush; }, - CanonizationTransformationKind::InvertAlt => { - priority += process_priorities.invert; - }, - CanonizationTransformationKind::InvertPar => { + InteractionTransformationKind::InvertAlt => { priority += process_priorities.invert; }, - CanonizationTransformationKind::TriInvertAltRF => { + InteractionTransformationKind::InvertPar => { priority += process_priorities.invert; }, - CanonizationTransformationKind::TriInvertParRF => { - priority += process_priorities.invert; - }, - CanonizationTransformationKind::Deduplicate => { - priority += process_priorities.deduplicate; - }, - CanonizationTransformationKind::TriDeduplicateRF => { + InteractionTransformationKind::Deduplicate => { priority += process_priorities.deduplicate; }, - CanonizationTransformationKind::FactorizePrefixStrict => { - priority += process_priorities.factorize; - }, - CanonizationTransformationKind::FactorizePrefixSeq => { + InteractionTransformationKind::FactorizePrefixStrict => { priority += process_priorities.factorize; }, - CanonizationTransformationKind::FactorizePrefixPar => { + InteractionTransformationKind::FactorizePrefixSeq => { priority += process_priorities.factorize; }, - CanonizationTransformationKind::FactorizeSuffixStrict => { + InteractionTransformationKind::FactorizeSuffixStrict => { priority += process_priorities.factorize; }, - CanonizationTransformationKind::FactorizeSuffixSeq => { + InteractionTransformationKind::FactorizeSuffixSeq => { priority += process_priorities.factorize; }, - CanonizationTransformationKind::FactorizeSuffixPar => { + InteractionTransformationKind::FactorizeCommutativePar => { priority += process_priorities.factorize; }, - CanonizationTransformationKind::DeFactorizeLeft => { + InteractionTransformationKind::DeFactorizeLeft => { priority += process_priorities.defactorize; }, - CanonizationTransformationKind::DeFactorizeRight => { + InteractionTransformationKind::DeFactorizeRight => { priority += process_priorities.defactorize; }, - CanonizationTransformationKind::LoopSimpl => { + InteractionTransformationKind::LoopSimpl => { priority += process_priorities.simpl; }, - CanonizationTransformationKind::LoopUnNest => { + InteractionTransformationKind::LoopAltSimpl => { priority += process_priorities.simpl; }, - CanonizationTransformationKind::SortEmissionTargets => { + InteractionTransformationKind::LoopUnNest => { priority += process_priorities.simpl; + }, + InteractionTransformationKind::SortActionContent => { + priority += process_priorities.simpl; + }, + // *** + InteractionTransformationKind::MergeShiftLeft1 => { + // nothing + }, + InteractionTransformationKind::MergeShiftLeft2 => { + // nothing + }, + InteractionTransformationKind::MergeShiftRight1 => { + // nothing + }, + InteractionTransformationKind::MergeShiftRight2 => { + // nothing + }, + InteractionTransformationKind::MergeSkip => { + // nothing + }, + InteractionTransformationKind::MergeSkipInvert => { + // nothing + }, + InteractionTransformationKind::MergeAction => { + // nothing } } // *** diff --git a/src/process/canon_proc/manager.rs b/src/process/canon_proc/manager.rs new file mode 100644 index 0000000..b356f61 --- /dev/null +++ b/src/process/canon_proc/manager.rs @@ -0,0 +1,310 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +use std::collections::{HashMap, HashSet}; +use std::iter::FromIterator; + +use crate::core::general_context::GeneralContext; +use crate::core::language::syntax::interaction::Interaction; +use crate::core::language::position::position::Position; +use crate::core::transformation::transfodef::InteractionTransformation; +use crate::core::transformation::transfokind::InteractionTransformationKind; +use crate::process::abstract_proc::common::{FilterEliminationKind, HibouSearchStrategy}; +use crate::process::abstract_proc::generic::{GenericNode, GenericStep}; +use crate::process::abstract_proc::manager::{GenericProcessManager, GenericProcessPriorities}; +use crate::process::canon_proc::interface::conf::CanonizationConfig; +use crate::process::canon_proc::interface::filter::{CanonizationFilter, CanonizationFilterCriterion}; +use crate::process::canon_proc::interface::logger::CanonizationLogger; +use crate::process::canon_proc::interface::node::CanonizationNodeKind; +use crate::process::canon_proc::interface::step::CanonizationStepKind; +use crate::process::canon_proc::transformations::get_transfos::get_canonize_transfos; +use crate::process::canon_proc::transformations::phases::CanonizationPhase; + + + +pub enum IntRefOrOldIdRef<'l> { + IntRef(&'l Interaction), + OldIDRef(u32) +} + + +pub struct CanonizationProcessManager { + pub(crate) manager: GenericProcessManager, + pub(crate) get_all_transfos : bool, + pub(crate) node_has_child_interaction : HashSet, + phase1_known : HashMap, // interaction term and corresponding state id + phase2_known : HashMap // interaction term and corresponding state id +} + +impl CanonizationProcessManager { + + pub fn new(gen_ctx : GeneralContext, + strategy : HibouSearchStrategy, + filters : Vec, + priorities : GenericProcessPriorities, + loggers : Vec>, + get_all_transfos : bool) -> CanonizationProcessManager { + let manager = GenericProcessManager::new( + gen_ctx, + strategy, + filters, + priorities, + loggers + ); + return CanonizationProcessManager{manager, + get_all_transfos, + node_has_child_interaction:HashSet::new(), + phase1_known:HashMap::new(), + phase2_known:HashMap::new()}; + } + + pub fn canonize(&mut self, + interaction : Interaction) -> u32 { + self.init_loggers(&interaction); + // *** + let mut next_state_id : u32 = 1; + let mut node_counter : u32 = 0; + self.enqueue_next_node_in_canonization(next_state_id,interaction,CanonizationPhase::FirstDefactorize,0); + next_state_id = next_state_id + 1; + node_counter = node_counter +1; + // *** + // *** + while let Some(next_to_process) = self.manager.extract_from_queue() { + let new_state_id = next_state_id; + next_state_id = next_state_id + 1; + // *** + let mut parent_state = self.manager.pick_memorized_state(next_to_process.parent_id); + // *** + match self.process_step(&parent_state, + next_to_process.kind, + next_to_process.parent_id, + new_state_id, + node_counter) { + None => {}, + Some( (new_interaction,new_depth,new_phase) ) => { + self.node_has_child_interaction.insert(next_to_process.parent_id); + node_counter = node_counter + 1; + self.enqueue_next_node_in_canonization(new_state_id, + new_interaction, + new_phase, + new_depth); + } + } + // *** + parent_state.remaining_ids_to_process.remove(&next_to_process.id_as_child); + if parent_state.remaining_ids_to_process.len() > 0 { + self.manager.remember_state(next_to_process.parent_id,parent_state); + } else { + let parent_has_child_interaction = self.node_has_child_interaction.remove(&next_to_process.parent_id); + if !parent_has_child_interaction { + self.manager.queue_set_last_reached_has_no_child(); + } + } + // *** + } + // *** + self.term_loggers(); + // *** + return node_counter; + } + + fn enqueue_next_node_in_canonization(&mut self, + parent_id : u32, + interaction : Interaction, + phase : CanonizationPhase, + depth : u32) { + // *** + let transfos = get_canonize_transfos(&interaction,&phase,self.get_all_transfos); + // *** + let mut id_as_child : u32 = 0; + // *** + let mut to_enqueue : Vec> = Vec::new(); + for transfo in transfos { + id_as_child = id_as_child + 1; + let generic_step = GenericStep{parent_id,id_as_child,kind:CanonizationStepKind::Transform(transfo)}; + to_enqueue.push( generic_step ); + } + // *** + if id_as_child == 0 { + if phase == CanonizationPhase::FirstDefactorize { + id_as_child = id_as_child + 1; + let generic_step = GenericStep{parent_id,id_as_child,kind:CanonizationStepKind::ChangePhase}; + to_enqueue.push( generic_step ); + } + } + // *** + if id_as_child > 0 { + let remaining_ids_to_process : HashSet = HashSet::from_iter((1..(id_as_child+1)).collect::>().iter().cloned() ); + let generic_node = GenericNode{kind:CanonizationNodeKind{interaction,phase},remaining_ids_to_process,depth}; + self.manager.remember_state( parent_id, generic_node ); + self.manager.enqueue_new_steps( parent_id, to_enqueue, depth ); + } else { + self.manager.queue_set_last_reached_has_no_child(); + } + } + + fn process_step(&mut self, + parent_state : &GenericNode, + step_kind : CanonizationStepKind, + parent_id : u32, + new_state_id : u32, + node_counter : u32) -> Option<(Interaction,u32,CanonizationPhase)> { + match step_kind { + CanonizationStepKind::Transform( transfo ) => { + match &parent_state.kind.phase { + CanonizationPhase::FirstDefactorize => { + match self.phase1_known.get(&transfo.result) { + None => { + self.phase1_known.insert(transfo.result.clone(),new_state_id); + return self.process_new_transformation_step(parent_state,transfo,parent_id,new_state_id,node_counter); + }, + Some(old_state_id) => { + self.transformation_loggers(&parent_state.kind.phase, + &transfo.kind, + &transfo.position, + &IntRefOrOldIdRef::OldIDRef(*old_state_id), + parent_id, + new_state_id); + return None; + } + } + }, + CanonizationPhase::SecondFactorize => { + match self.phase2_known.get(&transfo.result) { + None => { + self.phase2_known.insert(transfo.result.clone(),new_state_id); + return self.process_new_transformation_step(parent_state,transfo,parent_id,new_state_id,node_counter); + }, + Some(old_state_id) => { + self.transformation_loggers(&parent_state.kind.phase, + &transfo.kind, + &transfo.position, + &IntRefOrOldIdRef::OldIDRef(*old_state_id), + parent_id, + new_state_id); + return None; + } + } + } + } + }, + CanonizationStepKind::ChangePhase => { + match self.phase2_known.get(&parent_state.kind.interaction) { + None => { + self.phase2_known.insert(parent_state.kind.interaction.clone(),new_state_id); + self.phase_change_loggers(&IntRefOrOldIdRef::IntRef(&parent_state.kind.interaction), + parent_id, + new_state_id); + let new_depth = parent_state.depth + 1; + return Some( (parent_state.kind.interaction.clone(),new_depth,CanonizationPhase::SecondFactorize) ); + }, + Some(old_state_id) => { + self.phase_change_loggers(&IntRefOrOldIdRef::OldIDRef(*old_state_id), + parent_id, + new_state_id); + return None; + } + } + } + } + } + + + + fn process_new_transformation_step(&mut self, + parent_state : &GenericNode, + transfo : InteractionTransformation, + parent_id : u32, + new_state_id : u32, + node_counter : u32) -> Option<(Interaction,u32,CanonizationPhase)> { + let new_depth = parent_state.depth + 1; + match self.manager.apply_filters(new_depth,node_counter,&CanonizationFilterCriterion) { + None => { + self.transformation_loggers(&parent_state.kind.phase, + &transfo.kind, + &transfo.position, + &IntRefOrOldIdRef::IntRef(&transfo.result), + parent_id, + new_state_id); + return Some( (transfo.result,new_depth,parent_state.kind.phase.clone()) ); + }, + Some( elim_kind ) => { + self.filtered_loggers(&parent_state.kind.phase, + parent_id, + new_state_id, + &elim_kind); + return None; + } + } + } + + fn init_loggers(&mut self, interaction : &Interaction) { + for logger in self.manager.loggers.iter_mut() { + (*logger).log_init(interaction, &self.manager.gen_ctx); + } + } + + fn term_loggers(&mut self) { + let mut options_as_strs = (&self).manager.get_basic_options_as_strings(); + options_as_strs.insert(0, "process=canonization".to_string()); + options_as_strs.push( format!("search_all={}", self.get_all_transfos.to_string()) ); + for logger in self.manager.loggers.iter_mut() { + (*logger).log_term(&options_as_strs); + } + } + + fn filtered_loggers(&mut self, + phase : &CanonizationPhase, + parent_state_id : u32, + new_state_id : u32, + elim_kind : &FilterEliminationKind) { + for logger in self.manager.loggers.iter_mut() { + logger.log_filtered(phase, + parent_state_id, + new_state_id, + elim_kind); + } + } + + fn transformation_loggers(&mut self, + current_phase : &CanonizationPhase, + transfo_kind : &InteractionTransformationKind, + position : &Position, + new_interaction : &IntRefOrOldIdRef, + parent_state_id : u32, + new_state_id : u32) { + for logger in self.manager.loggers.iter_mut() { + logger.log_transformation(&self.manager.gen_ctx, + current_phase, + parent_state_id, + new_state_id, + transfo_kind, + position, + new_interaction); + } + } + + fn phase_change_loggers(&mut self, + new_interaction : &IntRefOrOldIdRef, + parent_state_id : u32, + new_state_id : u32) { + for logger in self.manager.loggers.iter_mut() { + (*logger).log_phase_change(&self.manager.gen_ctx,parent_state_id,new_state_id,new_interaction); + } + } + +} + diff --git a/src/process/canon_proc/mod.rs b/src/process/canon_proc/mod.rs index 2ae20dc..5fa7cb7 100644 --- a/src/process/canon_proc/mod.rs +++ b/src/process/canon_proc/mod.rs @@ -15,15 +15,9 @@ limitations under the License. */ - - -pub(in crate::proc_refactoring::canon_proc) mod node; -pub(in crate::proc_refactoring::canon_proc) mod step; -pub(in crate::proc_refactoring::canon_proc) mod transformations; -pub(in crate::proc_refactoring::canon_proc) mod priorities; -pub(in crate::proc_refactoring::canon_proc) mod conf; -pub(in crate::proc_refactoring::canon_proc) mod filter; - +pub mod transformations; +pub mod interface; +pub mod manager; diff --git a/src/process/canon_proc/transformations/get_all_transfos.rs b/src/process/canon_proc/transformations/get_all_transfos.rs deleted file mode 100644 index 777a036..0000000 --- a/src/process/canon_proc/transformations/get_all_transfos.rs +++ /dev/null @@ -1,153 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::general_context::GeneralContext; - -use crate::output::rendering::textual::monochrome::position::position_to_text; - -use crate::proc_refactoring::canon_proc::transformations::transfokind::*; -use crate::proc_refactoring::canon_proc::transformations::transfofunc::*; - -use crate::proc_refactoring::canon_proc::transformations::phases::*; - - -pub fn phase_1_all_transfos(interaction : &Interaction) -> Vec { - return get_all_transformations_rec(&transfos_phase1(),interaction); -} - -pub fn phase_2_all_transfos(interaction : &Interaction) -> Vec { - return get_all_transformations_rec(&transfos_phase2(),interaction); -} - -fn get_all_transformations_inner(transfos : &Vec<(CanonizationTransformationKind, &dyn Fn(&Interaction) -> Option)>, - interaction : &Interaction) -> Vec { - - let mut results : Vec = Vec::new(); - for (transfo_kind, transfo_func) in transfos { - match transfo_func(interaction) { - None => {}, - Some(new_int) => { - results.push( CanonizationTransformation::new((*transfo_kind).clone(),Position::Epsilon(None),new_int) ); - } - } - } - return results; -} - -fn get_all_transformations_rec(transfos : &Vec<(CanonizationTransformationKind, &dyn Fn(&Interaction) -> Option)>, - interaction : &Interaction) -> Vec { - let mut results = get_all_transformations_inner(transfos,interaction); - match interaction { - &Interaction::Empty => { - // *** - }, &Interaction::Emission(_) => { - // *** - }, &Interaction::Reception(_) => { - // *** - }, &Interaction::Strict(ref i1, ref i2) => { - for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( CanonizationTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Strict(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( CanonizationTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Strict(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, &Interaction::Seq(ref i1, ref i2) => { - for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( CanonizationTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Seq(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( CanonizationTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Seq(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, &Interaction::CoReg(ref cr, ref i1, ref i2) => { - for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( CanonizationTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::CoReg(cr.clone(), Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( CanonizationTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::CoReg(cr.clone(), i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, &Interaction::Par(ref i1, ref i2) => { - for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( CanonizationTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Par(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( CanonizationTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Par(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, &Interaction::Alt(ref i1, ref i2) => { - for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( CanonizationTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Alt(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( CanonizationTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Alt(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - }, &Interaction::Loop(ref lk, ref i1) => { - for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( CanonizationTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Loop(lk.clone(), Box::new(left_transfo.result)) - ) ); - } - }, &Interaction::And(ref i1, ref i2) => { - for left_transfo in get_all_transformations_rec(transfos,i1) { - results.push( CanonizationTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Strict(Box::new(left_transfo.result),i2.clone()) - ) ); - } - for right_transfo in get_all_transformations_rec(transfos,i2) { - results.push( CanonizationTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Strict(i1.clone(), Box::new(right_transfo.result)) - ) ); - } - } - } - return results; -} - - diff --git a/src/process/canon_proc/transformations/get_one_transfo.rs b/src/process/canon_proc/transformations/get_one_transfo.rs deleted file mode 100644 index 2eacfc2..0000000 --- a/src/process/canon_proc/transformations/get_one_transfo.rs +++ /dev/null @@ -1,200 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - - - -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::general_context::GeneralContext; - -use crate::output::rendering::textual::monochrome::position::position_to_text; - -use crate::proc_refactoring::canon_proc::transformations::transfokind::*; -use crate::proc_refactoring::canon_proc::transformations::transfofunc::*; - -use crate::proc_refactoring::canon_proc::transformations::phases::*; - - -pub fn phase_1_one_transfo(interaction : &Interaction) -> Vec { - match get_one_transformation_rec(&transfos_phase1(),interaction) { - Some( got_transfo ) => { - return vec![got_transfo]; - }, - None => { - return Vec::new(); - } - } -} - -pub fn phase_2_one_transfo(interaction : &Interaction) -> Vec { - match get_one_transformation_rec(&transfos_phase2(),interaction) { - Some( got_transfo ) => { - return vec![got_transfo]; - }, - None => { - return Vec::new(); - } - } -} - -fn get_one_transformation_inner(transfos : &Vec<(TransformationKind, &dyn Fn(&Interaction) -> Option)>, - interaction : &Interaction) -> Option { - for (transfo_kind, transfo_func) in transfos { - match transfo_func(interaction) { - None => {}, - Some(new_int) => { - return Some( InteractionTermTransformation::new((*transfo_kind).clone(),Position::Epsilon(None),new_int) ); - } - } - } - return None; -} - -fn get_one_transformation_rec(transfos : &Vec<(TransformationKind, &dyn Fn(&Interaction) -> Option)>, - interaction : &Interaction) -> Option { - match get_one_transformation_inner(transfos,interaction) { - Some( got_transfo ) => { - return Some(got_transfo); - }, - None => { - match interaction { - &Interaction::Empty => { - // *** - }, &Interaction::Emission(_) => { - // *** - }, &Interaction::Reception(_) => { - // *** - }, &Interaction::Strict(ref i1, ref i2) => { - match get_one_transformation_rec(transfos,i1) { - Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Strict(Box::new(left_transfo.result),i2.clone())) ); - }, - None => {} - } - match get_one_transformation_rec(transfos,i2) { - Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Strict(i1.clone(), Box::new(right_transfo.result))) ); - }, - None => {} - } - }, &Interaction::Seq(ref i1, ref i2) => { - match get_one_transformation_rec(transfos,i1) { - Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Seq(Box::new(left_transfo.result),i2.clone())) ); - }, - None => {} - } - match get_one_transformation_rec(transfos,i2) { - Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Seq(i1.clone(), Box::new(right_transfo.result))) ); - }, - None => {} - } - }, &Interaction::CoReg(ref cr, ref i1, ref i2) => { - match get_one_transformation_rec(transfos,i1) { - Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::CoReg(cr.clone(), Box::new(left_transfo.result),i2.clone())) ); - }, - None => {} - } - match get_one_transformation_rec(transfos,i2) { - Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::CoReg(cr.clone(), i1.clone(), Box::new(right_transfo.result))) ); - }, - None => {} - } - }, &Interaction::Par(ref i1, ref i2) => { - match get_one_transformation_rec(transfos,i1) { - Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Par(Box::new(left_transfo.result),i2.clone())) ); - }, - None => {} - } - match get_one_transformation_rec(transfos,i2) { - Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Par(i1.clone(), Box::new(right_transfo.result))) ); - }, - None => {} - } - }, &Interaction::Alt(ref i1, ref i2) => { - match get_one_transformation_rec(transfos,i1) { - Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Alt(Box::new(left_transfo.result),i2.clone())) ); - }, - None => {} - } - match get_one_transformation_rec(transfos,i2) { - Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Alt(i1.clone(), Box::new(right_transfo.result))) ); - }, - None => {} - } - }, &Interaction::Loop(ref lk, ref i1) => { - match get_one_transformation_rec(transfos,i1) { - Some(sub_transfo) => { - return Some( InteractionTermTransformation::new(sub_transfo.kind, - Position::Left(Box::new(sub_transfo.position)), - Interaction::Loop(lk.clone(), Box::new(sub_transfo.result))) ); - }, - None => {} - } - }, &Interaction::And(ref i1, ref i2) => { - match get_one_transformation_rec(transfos,i1) { - Some(left_transfo) => { - return Some( InteractionTermTransformation::new(left_transfo.kind, - Position::Left(Box::new(left_transfo.position)), - Interaction::Strict(Box::new(left_transfo.result),i2.clone())) ); - }, - None => {} - } - match get_one_transformation_rec(transfos,i2) { - Some(right_transfo) => { - return Some( InteractionTermTransformation::new(right_transfo.kind, - Position::Right(Box::new(right_transfo.position)), - Interaction::Strict(i1.clone(), Box::new(right_transfo.result))) ); - }, - None => {} - } - } - } - } - } - return None; -} - - diff --git a/src/process/canon_proc/transformations/get_transfos.rs b/src/process/canon_proc/transformations/get_transfos.rs new file mode 100644 index 0000000..7ce6431 --- /dev/null +++ b/src/process/canon_proc/transformations/get_transfos.rs @@ -0,0 +1,34 @@ +/* +Copyright 2020 Erwan Mahe (github.com/erwanM974) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +use crate::core::language::syntax::interaction::Interaction; +use crate::core::transformation::get_transfos::get_transfos::get_transfos; +use crate::core::transformation::transfodef::InteractionTransformation; +use crate::process::canon_proc::transformations::phases::{CanonizationPhase, transfos_phase1, transfos_phase2}; + + +pub fn get_canonize_transfos(interaction : &Interaction, phase : &CanonizationPhase, get_all : bool) -> Vec { + match phase { + CanonizationPhase::FirstDefactorize => { + return get_transfos(interaction,get_all,&transfos_phase1()); + }, + CanonizationPhase::SecondFactorize => { + return get_transfos(interaction,get_all,&transfos_phase2()); + } + } +} + diff --git a/src/process/canon_proc/transformations/mod.rs b/src/process/canon_proc/transformations/mod.rs index 73e886f..9d42569 100644 --- a/src/process/canon_proc/transformations/mod.rs +++ b/src/process/canon_proc/transformations/mod.rs @@ -15,12 +15,9 @@ limitations under the License. */ -pub mod transfokind; -pub mod transfofunc; + pub mod phases; +pub mod get_transfos; -pub mod get_all_transfos; -//pub mod get_one_transfo; -pub mod total_order; diff --git a/src/process/canon_proc/transformations/phases.rs b/src/process/canon_proc/transformations/phases.rs index f90b88c..21ef7a7 100644 --- a/src/process/canon_proc/transformations/phases.rs +++ b/src/process/canon_proc/transformations/phases.rs @@ -15,62 +15,77 @@ limitations under the License. */ -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::general_context::GeneralContext; - -use crate::output::rendering::textual::monochrome::position::position_to_text; - -use crate::proc_refactoring::canon_proc::transformations::transfokind::*; -use crate::proc_refactoring::canon_proc::transformations::transfofunc::*; - +use crate::core::language::syntax::interaction::Interaction; +use crate::core::transformation::transfofunc::action::*; +use crate::core::transformation::transfofunc::dedupl::*; +use crate::core::transformation::transfofunc::defactorize::*; +use crate::core::transformation::transfofunc::factorize_par::factorize_par; +use crate::core::transformation::transfofunc::factorize_prefix::*; +use crate::core::transformation::transfofunc::factorize_suffix::*; +use crate::core::transformation::transfofunc::flush::*; +use crate::core::transformation::transfofunc::invert::*; +use crate::core::transformation::transfofunc::loop_alt_simpl::loop_alt_simpl; +use crate::core::transformation::transfofunc::loop_simpl::*; +use crate::core::transformation::transfofunc::simpl::*; +use crate::core::transformation::transfokind::InteractionTransformationKind; +#[derive(Clone, PartialEq, Debug, Eq, Hash)] +pub enum CanonizationPhase { + FirstDefactorize, + SecondFactorize +} +impl CanonizationPhase { + pub fn to_string(&self) -> String { + match self { + &CanonizationPhase::FirstDefactorize => { + return "1:Defactorize".to_string(); + }, + &CanonizationPhase::SecondFactorize => { + return "2:Factorize".to_string(); + } + } + } +} -pub fn transfos_phase1<'lifetime>() -> Vec<(CanonizationTransformationKind, &'lifetime dyn Fn(&Interaction) -> Option)> { +pub fn transfos_phase1<'lifetime>() -> Vec<(InteractionTransformationKind, &'lifetime dyn Fn(&Interaction) -> Vec)> { return vec![ - (CanonizationTransformationKind::Deduplicate,&deduplicate), - (CanonizationTransformationKind::TriDeduplicateRF,&tri_deduplicate_right_flushed), - (CanonizationTransformationKind::SimplLeft,&simpl_left), - (CanonizationTransformationKind::SimplRight,&simpl_right), - (CanonizationTransformationKind::FlushRight,&flush_right), - (CanonizationTransformationKind::InvertPar,&invert_par_conditional), - (CanonizationTransformationKind::TriInvertParRF,&tri_invert_par_conditional_right_flushed), - (CanonizationTransformationKind::InvertAlt,&invert_alt_conditional), - (CanonizationTransformationKind::TriInvertAltRF,&tri_invert_alt_conditional_right_flushed), - (CanonizationTransformationKind::LoopSimpl,&loop_simpl), - (CanonizationTransformationKind::LoopUnNest,&loop_unnest), - (CanonizationTransformationKind::DeFactorizeLeft,&defactorize_left), - (CanonizationTransformationKind::DeFactorizeRight,&defactorize_right), + (InteractionTransformationKind::Deduplicate,&deduplicate), + (InteractionTransformationKind::Simpl,&simpl), + (InteractionTransformationKind::FlushRight,&flush_right), + (InteractionTransformationKind::InvertPar,&invert_par_sorted), + (InteractionTransformationKind::InvertAlt,&invert_alt_sorted), + (InteractionTransformationKind::LoopSimpl,&loop_empty_simpl), + (InteractionTransformationKind::LoopUnNest,&loop_unnest), + (InteractionTransformationKind::LoopAltSimpl,&loop_alt_simpl), + // *** + (InteractionTransformationKind::DeFactorizeLeft,&defactorize_left), + (InteractionTransformationKind::DeFactorizeRight,&defactorize_right), // *** - (CanonizationTransformationKind::SortEmissionTargets,&sort_emission_targets) + (InteractionTransformationKind::SortActionContent,&sort_action_content) ]; } -pub fn transfos_phase2<'lifetime>() -> Vec<(CanonizationTransformationKind, &'lifetime dyn Fn(&Interaction) -> Option)> { +pub fn transfos_phase2<'lifetime>() -> Vec<(InteractionTransformationKind, &'lifetime dyn Fn(&Interaction) -> Vec)> { return vec![ - (CanonizationTransformationKind::Deduplicate,&deduplicate), - (CanonizationTransformationKind::TriDeduplicateRF,&tri_deduplicate_right_flushed), - (CanonizationTransformationKind::SimplLeft,&simpl_left), - (CanonizationTransformationKind::SimplRight,&simpl_right), - (CanonizationTransformationKind::FlushRight,&flush_right), - (CanonizationTransformationKind::InvertPar,&invert_par_conditional), - (CanonizationTransformationKind::TriInvertParRF,&tri_invert_par_conditional_right_flushed), - (CanonizationTransformationKind::InvertAlt,&invert_alt_conditional), - (CanonizationTransformationKind::TriInvertAltRF,&tri_invert_alt_conditional_right_flushed), - (CanonizationTransformationKind::LoopSimpl,&loop_simpl), - (CanonizationTransformationKind::LoopUnNest,&loop_unnest), - (CanonizationTransformationKind::FactorizePrefixStrict,&factorize_prefix_strict), - (CanonizationTransformationKind::FactorizePrefixSeq,&factorize_prefix_seq), - (CanonizationTransformationKind::FactorizePrefixPar,&factorize_prefix_par), - (CanonizationTransformationKind::FactorizeSuffixStrict,&factorize_suffix_strict), - (CanonizationTransformationKind::FactorizeSuffixSeq,&factorize_suffix_seq), - (CanonizationTransformationKind::FactorizeSuffixPar,&factorize_suffix_par), + (InteractionTransformationKind::Deduplicate,&deduplicate), + (InteractionTransformationKind::Simpl,&simpl), + (InteractionTransformationKind::FlushRight,&flush_right), + (InteractionTransformationKind::InvertPar,&invert_par_sorted), + (InteractionTransformationKind::InvertAlt,&invert_alt_sorted), + (InteractionTransformationKind::LoopSimpl,&loop_empty_simpl), + (InteractionTransformationKind::LoopUnNest,&loop_unnest), + (InteractionTransformationKind::LoopAltSimpl,&loop_alt_simpl), + // *** + (InteractionTransformationKind::FactorizePrefixStrict,&factorize_prefix_strict), + (InteractionTransformationKind::FactorizePrefixSeq,&factorize_prefix_seq), + (InteractionTransformationKind::FactorizeSuffixStrict,&factorize_suffix_strict), + (InteractionTransformationKind::FactorizeSuffixSeq,&factorize_suffix_seq), + (InteractionTransformationKind::FactorizeCommutativePar,&factorize_par), // *** - (CanonizationTransformationKind::SortEmissionTargets,&sort_emission_targets) + (InteractionTransformationKind::SortActionContent,&sort_action_content) ]; } diff --git a/src/process/canon_proc/transformations/total_order.rs b/src/process/canon_proc/transformations/total_order.rs deleted file mode 100644 index d60d2eb..0000000 --- a/src/process/canon_proc/transformations/total_order.rs +++ /dev/null @@ -1,286 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - - -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::general_context::GeneralContext; - -use crate::core::execution::trace::trace::TraceActionKind; - - - -fn emission_lower_than(em_act1 : &EmissionAction, em_act2 : &EmissionAction) -> bool { - if &em_act1.ms_id < &em_act2.ms_id { - return true; - } else if &em_act1.ms_id > &em_act2.ms_id{ - return false; - } - // *** - if &em_act1.origin_lf_id < &em_act2.origin_lf_id { - return true; - } else if &em_act1.origin_lf_id > &em_act2.origin_lf_id { - return false; - } - // *** - let max_tar_len = em_act1.targets.len().max(em_act2.targets.len()); - for i in 0..max_tar_len { - match (em_act1.targets.get(i) , em_act2.targets.get(i) ) { - ( Some( tar_ref1 ), Some(tar_ref2) ) => { - if tar_ref1 < tar_ref2 { - return true; - } - }, - (None,Some(_)) => { - return true; - }, - (Some(_),None) => {}, - (None,None) => {} - } - } - // *** - return em_act1.synchronicity < em_act2.synchronicity; -} - - -fn reception_lower_than(rc_act1 : &ReceptionAction, rc_act2 : &ReceptionAction) -> bool { - if &rc_act1.ms_id < &rc_act2.ms_id { - return true; - } else if &rc_act1.ms_id > &rc_act2.ms_id{ - return false; - } - // *** - match (rc_act1.origin_gt_id,rc_act2.origin_gt_id) { - (None,Some(_)) => { - return true; - }, - (Some(_),None) => {}, - (None,None) => {}, - (Some( gt_id1),Some(gt_id2)) => { - if gt_id1 < gt_id2 { - return true; - } - } - } - // *** - let max_tar_len = rc_act1.recipients.len().max(rc_act2.recipients.len()); - for i in 0..max_tar_len { - match (rc_act1.recipients.get(i) , rc_act2.recipients.get(i) ) { - ( Some( tar_lf_id1 ), Some(tar_lf_id2) ) => { - if tar_lf_id1 < tar_lf_id2 { - return true; - } - }, - (None,Some(_)) => { - return true; - }, - (Some(_),None) => {}, - (None,None) => {} - } - } - // *** - return rc_act1.synchronicity < rc_act2.synchronicity; -} - - -pub fn interaction_lower_than(i1 : &Interaction, i2 : &Interaction) -> bool { - match i1 { - &Interaction::Empty => { - match i2 { - &Interaction::Empty => { - return false; - }, - _ => { - return true; - } - } - }, - &Interaction::Emission(ref em_act1) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(ref em_act2) => { - return emission_lower_than(em_act1,em_act2); - }, - _ => { - return true; - } - } - }, - &Interaction::Reception(ref rc_act1) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(ref rc_act2) => { - return reception_lower_than(rc_act1,rc_act2); - }, - _ => { - return true; - } - } - } - &Interaction::Par(ref i11, ref i12) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(_) => { - return false; - }, - &Interaction::Par(ref i21, ref i22) => { - if interaction_lower_than(i11,i21) { - return true; - } else { - if i11 != i21 { - return false; - } else { - return interaction_lower_than(i12,i22); - } - } - }, - _ => { - return true; - } - } - }, - &Interaction::Seq(ref i11, ref i12) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(_) => { - return false; - }, - &Interaction::Par(_,_) => { - return false; - }, - &Interaction::Seq(ref i21, ref i22) => { - if interaction_lower_than(i11,i21) { - return true; - } else { - if i11 != i21 { - return false; - } else { - return interaction_lower_than(i12,i22); - } - } - }, - _ => { - return true; - } - } - }, - &Interaction::Strict(ref i11, ref i12) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(_) => { - return false; - }, - &Interaction::Par(_,_) => { - return false; - }, - &Interaction::Seq(_,_) => { - return false; - }, - &Interaction::Strict(ref i21, ref i22) => { - if interaction_lower_than(i11,i21) { - return true; - } else { - if i11 != i21 { - return false; - } else { - return interaction_lower_than(i12,i22); - } - } - }, - _ => { - return true; - } - } - }, - &Interaction::Alt(ref i11, ref i12) => { - match i2 { - &Interaction::Empty => { - return false; - }, - &Interaction::Emission(_) => { - return false; - }, - &Interaction::Reception(_) => { - return false; - }, - &Interaction::Par(_,_) => { - return false; - }, - &Interaction::Seq(_,_) => { - return false; - }, - &Interaction::Strict(_,_) => { - return false; - }, - &Interaction::Alt(ref i21, ref i22) => { - if interaction_lower_than(i11,i21) { - return true; - } else { - if i11 != i21 { - return false; - } else { - return interaction_lower_than(i12,i22); - } - } - }, - _ => { - return true; - } - } - }, - &Interaction::Loop(ref lk1, ref i11) => { - match i2 { - &Interaction::Loop(ref lk2, ref i21) => { - if lk1 < lk2 { - return true; - } else { - return interaction_lower_than(i11,i21); - } - }, - _ => { - return false; - } - } - }, - _ => { - panic!(); - } - } -} \ No newline at end of file diff --git a/src/process/canon_proc/transformations/transfofunc.rs b/src/process/canon_proc/transformations/transfofunc.rs deleted file mode 100644 index fae077d..0000000 --- a/src/process/canon_proc/transformations/transfofunc.rs +++ /dev/null @@ -1,558 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -use crate::core::language::syntax::interaction::{Interaction}; -use crate::core::language::syntax::action::*; -use crate::core::language::position::position::Position; -use crate::core::language::syntax::util::get_recursive_frag::*; -use crate::core::language::syntax::util::fold_recursive_frags::*; -use crate::core::general_context::GeneralContext; - -use crate::proc_refactoring::canon_proc::transformations::total_order::interaction_lower_than; - - -pub(in crate::proc_refactoring::canon_proc) fn simpl_left(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - if **i1 == Interaction::Empty { - return Some( *(i2.clone()) ); - } - }, - &Interaction::Seq(ref i1, ref i2) => { - if **i1 == Interaction::Empty { - return Some( *(i2.clone()) ); - } - }, - &Interaction::Par(ref i1, ref i2) => { - if **i1 == Interaction::Empty { - return Some( *(i2.clone()) ); - } - }, - &Interaction::CoReg(_, ref i1, ref i2) => { - if **i1 == Interaction::Empty { - return Some( *(i2.clone()) ); - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn simpl_right(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - if **i2 == Interaction::Empty { - return Some( *(i1.clone()) ); - } - }, - &Interaction::Seq(ref i1, ref i2) => { - if **i2 == Interaction::Empty { - return Some( *(i1.clone()) ); - } - }, - &Interaction::Par(ref i1, ref i2) => { - if **i2 == Interaction::Empty { - return Some( *(i1.clone()) ); - } - }, - &Interaction::CoReg(_, ref i1, ref i2) => { - if **i2 == Interaction::Empty { - return Some( *(i1.clone()) ); - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn flush_right(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11,ref i12) => { - return Some( Interaction::Alt( i11.clone(), Box::new(Interaction::Alt(i12.clone(), i2.clone())) ) ); - }, - _ => {} - } - }, - &Interaction::Strict(ref i1, ref i2) => { - match **i1 { - Interaction::Strict(ref i11,ref i12) => { - return Some( Interaction::Strict( i11.clone(), Box::new(Interaction::Strict(i12.clone(), i2.clone())) ) ); - }, - _ => {} - } - }, - &Interaction::Seq(ref i1, ref i2) => { - match **i1 { - Interaction::Seq(ref i11,ref i12) => { - return Some( Interaction::Seq( i11.clone(), Box::new(Interaction::Seq(i12.clone(), i2.clone())) ) ); - }, - _ => {} - } - }, - &Interaction::Par(ref i1, ref i2) => { - match **i1 { - Interaction::Par(ref i11,ref i12) => { - return Some( Interaction::Par( i11.clone(), Box::new(Interaction::Par(i12.clone(), i2.clone())) ) ); - }, - _ => {} - } - }, - &Interaction::CoReg(ref cr1, ref i1, ref i2) => { - match **i1 { - Interaction::CoReg(ref cr2, ref i11,ref i12) => { - if cr1 == cr2 { - return Some( Interaction::CoReg( cr1.clone(), i11.clone(), Box::new(Interaction::CoReg(cr1.clone(), i12.clone(), i2.clone())) ) ); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn flush_left(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21,ref i22) => { - return Some( Interaction::Alt( Box::new(Interaction::Alt(i1.clone(), i21.clone())), i22.clone() ) ); - }, - _ => {} - } - }, - &Interaction::Strict(ref i1, ref i2) => { - match **i2 { - Interaction::Strict(ref i21,ref i22) => { - return Some( Interaction::Strict( Box::new(Interaction::Strict(i1.clone(), i21.clone())), i22.clone() ) ); - }, - _ => {} - } - }, - &Interaction::Seq(ref i1, ref i2) => { - match **i2 { - Interaction::Seq(ref i21,ref i22) => { - return Some( Interaction::Seq( Box::new(Interaction::Seq(i1.clone(), i21.clone())), i22.clone() ) ); - }, - _ => {} - } - }, - &Interaction::Par(ref i1, ref i2) => { - match **i2 { - Interaction::Par(ref i21,ref i22) => { - return Some( Interaction::Par( Box::new(Interaction::Par(i1.clone(), i21.clone())), i22.clone() ) ); - }, - _ => {} - } - }, - &Interaction::CoReg(ref cr1, ref i1, ref i2) => { - match **i2 { - Interaction::CoReg(ref cr2, ref i21,ref i22) => { - if cr1 == cr2 { - return Some( Interaction::CoReg( cr1.clone(), Box::new(Interaction::CoReg(cr1.clone(), i1.clone(), i21.clone())), i22.clone() ) ); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - -pub(in crate::proc_refactoring::canon_proc) fn invert_alt_conditional(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - if interaction_lower_than(i2,i1) { - return Some( Interaction::Alt( i2.clone(), i1.clone() ) ); - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn invert_par_conditional(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Par(ref i1, ref i2) => { - if interaction_lower_than(i2,i1) { - return Some(Interaction::Par(i2.clone(), i1.clone())); - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn tri_invert_alt_conditional_right_flushed(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i_right) => { - match **i_right { - Interaction::Alt(ref i2,ref i3) => { - if interaction_lower_than(i2,i1) { - return Some( Interaction::Alt( i2.clone(), Box::new(Interaction::Alt(i1.clone(), i3.clone())) ) ); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn tri_invert_par_conditional_right_flushed(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Par(ref i1, ref i_right) => { - match **i_right { - Interaction::Par(ref i2,ref i3) => { - if interaction_lower_than(i2,i1) { - return Some(Interaction::Par(i2.clone(), Box::new(Interaction::Par(i1.clone(), i3.clone())))); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn deduplicate(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - if i1 == i2 { - return Some( *i1.clone() ); - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn tri_deduplicate_right_flushed(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i_right) => { - match **i_right { - Interaction::Alt(ref i2,ref i3) => { - if i1 == i2 { - return Some( Interaction::Alt(i1.clone(),i3.clone()) ); - } - }, - _ => {} - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn factorize_prefix_strict(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_strict_frags = get_recursive_strict_frags(i1); - let mut right_strict_frags = get_recursive_strict_frags(i2); - if left_strict_frags[0] == right_strict_frags[0] { - let first_frag = left_strict_frags.remove(0); - right_strict_frags.remove(0); - if first_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_strict_frags(&mut left_strict_frags)), - Box::new(fold_recursive_strict_frags(&mut right_strict_frags)) - ); - return Some( Interaction::Strict( Box::new(first_frag.clone()), Box::new(new_alt)) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn factorize_prefix_seq(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_seq_frags = get_recursive_seq_frags(i1); - let mut right_seq_frags = get_recursive_seq_frags(i2); - if left_seq_frags[0] == right_seq_frags[0] { - let first_frag = left_seq_frags.remove(0); - right_seq_frags.remove(0); - if first_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_seq_frags(&mut left_seq_frags)), - Box::new(fold_recursive_seq_frags(&mut right_seq_frags)) - ); - return Some( Interaction::Seq( Box::new(first_frag.clone()), Box::new(new_alt)) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn factorize_prefix_par(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_par_frags = get_recursive_par_frags(i1); - let mut right_par_frags = get_recursive_par_frags(i2); - if left_par_frags[0] == right_par_frags[0] { - let first_frag = left_par_frags.remove(0); - right_par_frags.remove(0); - if first_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_par_frags(&mut left_par_frags)), - Box::new(fold_recursive_par_frags(&mut right_par_frags)) - ); - return Some( Interaction::Par( Box::new(first_frag.clone()), Box::new(new_alt)) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn factorize_suffix_strict(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_strict_frags = get_recursive_strict_frags(i1); - let mut right_strict_frags = get_recursive_strict_frags(i2); - if left_strict_frags.last() == right_strict_frags.last() { - let last_frag : &Interaction = left_strict_frags.pop().unwrap(); - right_strict_frags.pop(); - if last_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_strict_frags(&mut left_strict_frags)), - Box::new(fold_recursive_strict_frags(&mut right_strict_frags)) - ); - return Some( Interaction::Strict( Box::new(new_alt), Box::new(last_frag.clone()) ) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn factorize_suffix_seq(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_seq_frags = get_recursive_seq_frags(i1); - let mut right_seq_frags = get_recursive_seq_frags(i2); - if left_seq_frags.last() == right_seq_frags.last() { - let last_frag : &Interaction = left_seq_frags.pop().unwrap(); - right_seq_frags.pop(); - if last_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_seq_frags(&mut left_seq_frags)), - Box::new(fold_recursive_seq_frags(&mut right_seq_frags)) - ); - return Some( Interaction::Seq( Box::new(new_alt), Box::new(last_frag.clone()) ) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn factorize_suffix_par(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Alt(ref i1, ref i2) => { - let mut left_par_frags = get_recursive_par_frags(i1); - let mut right_par_frags = get_recursive_par_frags(i2); - if left_par_frags.last() == right_par_frags.last() { - let last_frag : &Interaction = left_par_frags.pop().unwrap(); - right_par_frags.pop(); - if last_frag != &Interaction::Empty { - let new_alt = Interaction::Alt(Box::new(fold_recursive_par_frags(&mut left_par_frags)), - Box::new(fold_recursive_par_frags(&mut right_par_frags)) - ); - return Some( Interaction::Par( Box::new(new_alt), Box::new(last_frag.clone()) ) ); - } - } - }, - _ => {} - } - return None; -} - -pub(in crate::proc_refactoring::canon_proc) fn defactorize_left(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21, ref i22) => { - let new_iA = Interaction::Strict( i1.clone(), i21.clone() ); - let new_iB = Interaction::Strict( i1.clone(), i22.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::Seq(ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21, ref i22) => { - let new_iA = Interaction::Seq( i1.clone(), i21.clone() ); - let new_iB = Interaction::Seq( i1.clone(), i22.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::Par(ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21, ref i22) => { - let new_iA = Interaction::Par( i1.clone(), i21.clone() ); - let new_iB = Interaction::Par( i1.clone(), i22.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::CoReg(ref cr, ref i1, ref i2) => { - match **i2 { - Interaction::Alt(ref i21, ref i22) => { - let new_iA = Interaction::CoReg( cr.clone(), i1.clone(), i21.clone() ); - let new_iB = Interaction::CoReg( cr.clone(), i1.clone(), i22.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - - -pub(in crate::proc_refactoring::canon_proc) fn defactorize_right(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Strict(ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11, ref i12) => { - let new_iA = Interaction::Strict( i11.clone(), i2.clone() ); - let new_iB = Interaction::Strict( i12.clone(), i2.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::Seq(ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11, ref i12) => { - let new_iA = Interaction::Seq( i11.clone(), i2.clone() ); - let new_iB = Interaction::Seq( i12.clone(), i2.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::Par(ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11, ref i12) => { - let new_iA = Interaction::Par( i11.clone(), i2.clone() ); - let new_iB = Interaction::Par( i12.clone(), i2.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - &Interaction::CoReg(ref cr, ref i1, ref i2) => { - match **i1 { - Interaction::Alt(ref i11, ref i12) => { - let new_iA = Interaction::CoReg( cr.clone(), i11.clone(), i2.clone() ); - let new_iB = Interaction::CoReg( cr.clone(), i12.clone(), i2.clone() ); - return Some( Interaction::Alt(Box::new(new_iA), Box::new(new_iB) ) ); - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - - -pub(in crate::proc_refactoring::canon_proc) fn loop_simpl(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Loop(ref sk, ref i1) => { - match **i1 { - Interaction::Empty => { - return Some( Interaction::Empty ); - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - -pub(in crate::proc_refactoring::canon_proc) fn loop_unnest(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Loop(ref lkA, ref i1) => { - match **i1 { - Interaction::Loop(ref lkB, ref i11) => { - return Some( Interaction::Loop((lkA.min(lkB)).clone(), i11.clone()) ); - }, - _ => {} - } - }, - _ => {} - } - return None; -} - - - -pub(in crate::proc_refactoring::canon_proc) fn sort_emission_targets(interaction : &Interaction) -> Option { - match interaction { - &Interaction::Emission(ref em_act) => { - let mut new_targets = em_act.targets.clone(); - new_targets.sort(); - if new_targets != em_act.targets { - let new_emission = EmissionAction::new(em_act.origin_lf_id,em_act.ms_id,em_act.synchronicity.clone(),new_targets); - return Some( Interaction::Emission(new_emission) ); - } - }, - &Interaction::Reception(ref rc_act) => { - let mut new_targets = rc_act.recipients.clone(); - new_targets.sort(); - if new_targets != rc_act.recipients { - let new_reception = ReceptionAction::new(rc_act.origin_gt_id.clone(),rc_act.ms_id,rc_act.synchronicity.clone(),new_targets); - return Some( Interaction::Reception(new_reception) ); - } - }, - _ => {} - } - return None; -} - - - - - - - - - - - - diff --git a/src/process/canon_proc/transformations/transfokind.rs b/src/process/canon_proc/transformations/transfokind.rs deleted file mode 100644 index 0c85d0b..0000000 --- a/src/process/canon_proc/transformations/transfokind.rs +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - - -use crate::core::language::syntax::interaction::Interaction; -use crate::core::language::position::position::Position; -use crate::output::rendering::textual::monochrome::position::position_to_text; - -#[derive(Clone, PartialEq, Debug, Eq, Hash)] -pub enum CanonizationTransformationKind { - SimplLeft, - SimplRight, - FlushLeft, - FlushRight, - InvertAlt, - InvertPar, - TriInvertAltRF, - TriInvertParRF, - Deduplicate, - TriDeduplicateRF, - FactorizePrefixStrict, - FactorizePrefixSeq, - FactorizePrefixPar, - FactorizeSuffixStrict, - FactorizeSuffixSeq, - FactorizeSuffixPar, - DeFactorizeLeft, - DeFactorizeRight, - LoopSimpl, - LoopUnNest, - SortEmissionTargets -} - -impl CanonizationTransformationKind { - pub fn to_string(&self) -> String { - match self { - &CanonizationTransformationKind::SimplLeft => { - return "SimplLeft".to_string(); - }, - &CanonizationTransformationKind::SimplRight => { - return "SimplRight".to_string(); - }, - &CanonizationTransformationKind::FlushLeft => { - return "FlushLeft".to_string(); - }, - &CanonizationTransformationKind::FlushRight => { - return "FlushRight".to_string(); - }, - &CanonizationTransformationKind::InvertAlt => { - return "InvertAlt".to_string(); - }, - &CanonizationTransformationKind::InvertPar => { - return "InvertPar".to_string(); - }, - &CanonizationTransformationKind::TriInvertAltRF => { - return "TriInvertAltRF".to_string(); - }, - &CanonizationTransformationKind::TriInvertParRF => { - return "TriInvertParRF".to_string(); - }, - &CanonizationTransformationKind::Deduplicate => { - return "Deduplicate".to_string(); - }, - &CanonizationTransformationKind::TriDeduplicateRF => { - return "TriDeduplicateRF".to_string(); - }, - &CanonizationTransformationKind::FactorizePrefixStrict => { - return "FactorizePrefixStrict".to_string(); - }, - &CanonizationTransformationKind::FactorizePrefixSeq => { - return "FactorizePrefixSeq".to_string(); - }, - &CanonizationTransformationKind::FactorizePrefixPar => { - return "FactorizePrefixPar".to_string(); - }, - &CanonizationTransformationKind::FactorizeSuffixStrict => { - return "FactorizeSuffixStrict".to_string(); - }, - &CanonizationTransformationKind::FactorizeSuffixSeq => { - return "FactorizeSuffixSeq".to_string(); - }, - &CanonizationTransformationKind::FactorizeSuffixPar => { - return "FactorizeSuffixPar".to_string(); - }, - &CanonizationTransformationKind::DeFactorizeLeft => { - return "DeFactorizeLeft".to_string(); - }, - &CanonizationTransformationKind::DeFactorizeRight => { - return "DeFactorizeRight".to_string(); - }, - &CanonizationTransformationKind::LoopSimpl => { - return "LoopSimpl".to_string(); - }, - &CanonizationTransformationKind::LoopUnNest => { - return "LoopUnNest".to_string(); - }, - &CanonizationTransformationKind::SortEmissionTargets => { - return "SortEmissionTargets".to_string(); - } - } - } -} - -pub struct CanonizationTransformation { - pub kind : CanonizationTransformationKind, - pub position : Position, - pub result : Interaction -} - -impl CanonizationTransformation { - pub fn new(kind : CanonizationTransformationKind, - position : Position, - result : Interaction) -> CanonizationTransformation { - return CanonizationTransformation{kind,position,result}; - } - - pub fn transformation_str_description(&self) -> String { - return format!("{}@{}", self.kind.to_string(), position_to_text(&self.position)) - } -} \ No newline at end of file diff --git a/src/process/mod.rs b/src/process/mod.rs index 4509999..5200433 100644 --- a/src/process/mod.rs +++ b/src/process/mod.rs @@ -18,8 +18,7 @@ limitations under the License. pub mod abstract_proc; pub mod explo_proc; pub mod ana_proc; -//pub mod canon_proc; -//pub mod canon_proc; +pub mod canon_proc; //pub mod merge_proc; diff --git a/src/trace_manip/mutate/insert_noise.rs b/src/trace_manip/mutate/insert_noise.rs index 3434f8e..e10157d 100644 --- a/src/trace_manip/mutate/insert_noise.rs +++ b/src/trace_manip/mutate/insert_noise.rs @@ -16,6 +16,7 @@ limitations under the License. use std::collections::HashSet; +use std::path::PathBuf; use rand::Rng; use rand::rngs::ThreadRng; use rand::seq::SliceRandom; @@ -24,7 +25,8 @@ use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::{MultiTrace, Trace}; use crate::core::execution::trace::trace::{TraceAction, TraceActionKind}; use crate::core::general_context::GeneralContext; -use crate::output::to_hfiles::multitrace_to_htf::write_multi_trace_into_file; +use crate::io::file_extensions::HIBOU_TRACE_FILE_EXTENSION; +use crate::io::output::to_hfiles::trace::to_htf::write_multi_trace_into_file; pub fn generate_insert_noise_mutant(gen_ctx : &GeneralContext, @@ -35,22 +37,24 @@ pub fn generate_insert_noise_mutant(gen_ctx : &GeneralContext, max_num_inserts : u32, one_per_compo_max : bool, only_at_end : bool) -> String{ + let file_name = format!("{:}.{:}", mutant_name, HIBOU_TRACE_FILE_EXTENSION); + let path : PathBuf; let file_path : String; match parent_folder { None => { - file_path = format!("./{:}", mutant_name); + path = [&file_name].iter().collect(); }, Some( parent ) => { - file_path = format!("{:}/{:}", parent, mutant_name); + path = [parent, &file_name].iter().collect(); } } // *** let mutant_mt = mutate_by_inserting_noise(gen_ctx,co_localizations,multi_trace,max_num_inserts,one_per_compo_max,only_at_end); - write_multi_trace_into_file(&file_path, + write_multi_trace_into_file(path.as_path(), gen_ctx, co_localizations, &mutant_mt); - return file_path; + return path.into_os_string().to_str().unwrap().to_string(); } diff --git a/src/trace_manip/mutate/swap_actions.rs b/src/trace_manip/mutate/swap_actions.rs index 48685e8..5f1bdf7 100644 --- a/src/trace_manip/mutate/swap_actions.rs +++ b/src/trace_manip/mutate/swap_actions.rs @@ -17,6 +17,7 @@ limitations under the License. +use std::path::PathBuf; use std::ptr; use rand::rngs::ThreadRng; use rand::seq::SliceRandom; @@ -24,7 +25,8 @@ use rand::distributions::{Distribution, Uniform}; use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::{MultiTrace, Trace}; use crate::core::general_context::GeneralContext; -use crate::output::to_hfiles::multitrace_to_htf::write_multi_trace_into_file; +use crate::io::file_extensions::HIBOU_TRACE_FILE_EXTENSION; +use crate::io::output::to_hfiles::trace::to_htf::write_multi_trace_into_file; pub fn generate_swap_actions_mutant(gen_ctx : &GeneralContext, @@ -32,23 +34,25 @@ pub fn generate_swap_actions_mutant(gen_ctx : &GeneralContext, multi_trace : &MultiTrace, parent_folder : Option<&str>, mutant_name : &str, - max_num_swaps : u32) -> String{ + max_num_swaps : u32) -> String { + let file_name = format!("{:}.{:}", mutant_name, HIBOU_TRACE_FILE_EXTENSION); + let path : PathBuf; let file_path : String; match parent_folder { None => { - file_path = format!("./{:}", mutant_name); + path = [&file_name].iter().collect(); }, Some( parent ) => { - file_path = format!("{:}/{:}", parent, mutant_name); + path = [parent, &file_name].iter().collect(); } } // *** let mutant_mt = mutate_by_swapping_actions(multi_trace,max_num_swaps); - write_multi_trace_into_file(&file_path, + write_multi_trace_into_file(path.as_path(), gen_ctx, co_localizations, &mutant_mt); - return file_path; + return path.into_os_string().to_str().unwrap().to_string(); } diff --git a/src/trace_manip/mutate/swap_component.rs b/src/trace_manip/mutate/swap_component.rs index 20ea183..4299095 100644 --- a/src/trace_manip/mutate/swap_component.rs +++ b/src/trace_manip/mutate/swap_component.rs @@ -16,13 +16,15 @@ limitations under the License. +use std::path::PathBuf; use rand::rngs::ThreadRng; use rand::seq::SliceRandom; use rand::distributions::{Distribution, Uniform}; use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::{MultiTrace}; use crate::core::general_context::GeneralContext; -use crate::output::to_hfiles::multitrace_to_htf::write_multi_trace_into_file; +use crate::io::file_extensions::HIBOU_TRACE_FILE_EXTENSION; +use crate::io::output::to_hfiles::trace::to_htf::write_multi_trace_into_file; pub fn generate_swap_components_mutant(gen_ctx : &GeneralContext, @@ -32,22 +34,24 @@ pub fn generate_swap_components_mutant(gen_ctx : &GeneralContext, parent_folder : Option<&str>, mutant_name : &str, max_num_swaps : u32) -> String{ + let file_name = format!("{:}.{:}", mutant_name, HIBOU_TRACE_FILE_EXTENSION); + let path : PathBuf; let file_path : String; match parent_folder { None => { - file_path = format!("./{:}", mutant_name); + path = [&file_name].iter().collect(); }, Some( parent ) => { - file_path = format!("{:}/{:}", parent, mutant_name); + path = [parent, &file_name].iter().collect(); } } // *** let mutant_mt = mutate_by_swapping_components(mu1,mu2,max_num_swaps); - write_multi_trace_into_file(&file_path, + write_multi_trace_into_file(path.as_path(), gen_ctx, co_localizations, &mutant_mt); - return file_path; + return path.into_os_string().to_str().unwrap().to_string();; } diff --git a/src/trace_manip/slice/exhaustive.rs b/src/trace_manip/slice/exhaustive.rs index 5d0722d..afe5ba5 100644 --- a/src/trace_manip/slice/exhaustive.rs +++ b/src/trace_manip/slice/exhaustive.rs @@ -17,25 +17,29 @@ limitations under the License. use std::collections::HashSet; +use std::path::PathBuf; use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::Trace; use crate::core::general_context::GeneralContext; use crate::core::execution::trace::trace::TraceAction; -use crate::output::to_hfiles::multitrace_to_htf::write_multi_trace_into_file; +use crate::io::file_extensions::HIBOU_TRACE_FILE_EXTENSION; +use crate::io::output::to_hfiles::trace::to_htf::write_multi_trace_into_file; use crate::util::slicer::Slicer; pub fn get_all_slices_rec<'a>(gen_ctx : &GeneralContext, co_localizations : &CoLocalizations, dir_name : &str, + file_name_prefix : &str, id : &mut u32, ok_canals : &Vec, rem_canals : &mut (impl Iterator + Clone)) { match rem_canals.next() { None => { - let file_path = format!("{:}/s{:}", dir_name, id); + let file_name = format!("{:}s{:}.{:}", file_name_prefix, id, HIBOU_TRACE_FILE_EXTENSION); + let path : PathBuf = [dir_name, &file_name].iter().collect(); *id = *id + 1; - write_multi_trace_into_file(&file_path, gen_ctx, co_localizations,ok_canals); + write_multi_trace_into_file(path.as_path(), gen_ctx, co_localizations,ok_canals); }, Some(canal_trace) => { let mut slicer = Slicer::new(&canal_trace); @@ -46,6 +50,7 @@ pub fn get_all_slices_rec<'a>(gen_ctx : &GeneralContext, get_all_slices_rec(gen_ctx, co_localizations, dir_name, + file_name_prefix, id, &new_ok_canals, &mut rem_canals.clone()); @@ -57,14 +62,16 @@ pub fn get_all_slices_rec<'a>(gen_ctx : &GeneralContext, pub fn get_all_prefixes_rec<'a>(gen_ctx : &GeneralContext, co_localizations : &CoLocalizations, dir_name : &str, + file_name_prefix : &str, id : &mut u32, ok_canals : &Vec, rem_canals : &mut (impl Iterator + Clone)) { match rem_canals.next() { None => { - let file_path = format!("{:}/s{:}", dir_name, id); + let file_name = format!("{:}s{:}.{:}", file_name_prefix, id, HIBOU_TRACE_FILE_EXTENSION); + let path : PathBuf = [dir_name, &file_name].iter().collect(); *id = *id + 1; - write_multi_trace_into_file(&file_path, gen_ctx, co_localizations,ok_canals); + write_multi_trace_into_file(path.as_path(), gen_ctx, co_localizations,ok_canals); }, Some(canal_trace ) => { for i in 0..(canal_trace.len()+1) { @@ -74,6 +81,7 @@ pub fn get_all_prefixes_rec<'a>(gen_ctx : &GeneralContext, get_all_prefixes_rec(gen_ctx, co_localizations, dir_name, + file_name_prefix, id, &new_ok_canals, &mut rem_canals.clone()); @@ -85,14 +93,16 @@ pub fn get_all_prefixes_rec<'a>(gen_ctx : &GeneralContext, pub fn get_all_suffixes_rec<'a>(gen_ctx : &GeneralContext, co_localizations : &CoLocalizations, dir_name : &str, + file_name_prefix : &str, id : &mut u32, ok_canals : &Vec, rem_canals : &mut (impl Iterator + Clone)) { match rem_canals.next() { None => { - let file_path = format!("{:}/s{:}", dir_name, id); + let file_name = format!("{:}s{:}.{:}", file_name_prefix, id, HIBOU_TRACE_FILE_EXTENSION); + let path : PathBuf = [dir_name, &file_name].iter().collect(); *id = *id + 1; - write_multi_trace_into_file(&file_path, gen_ctx, co_localizations,ok_canals); + write_multi_trace_into_file(path.as_path(), gen_ctx, co_localizations,ok_canals); }, Some(canal_trace) => { for i in 0..(canal_trace.len()+1) { @@ -102,6 +112,7 @@ pub fn get_all_suffixes_rec<'a>(gen_ctx : &GeneralContext, get_all_suffixes_rec(gen_ctx, co_localizations, dir_name, + file_name_prefix, id, &new_ok_canals, &mut rem_canals.clone()); diff --git a/src/trace_manip/slice/generate.rs b/src/trace_manip/slice/generate.rs index de4799f..5794930 100644 --- a/src/trace_manip/slice/generate.rs +++ b/src/trace_manip/slice/generate.rs @@ -31,12 +31,13 @@ fn get_exhaustive_slicing<'a>(gen_ctx : &GeneralContext, co_localizations : &CoLocalizations, kind : &SliceKind, dir_name : &String, + file_name_prefix : &String, rem_canals : &mut (impl Iterator + Clone)) { match kind { &SliceKind::Prefix => { get_all_prefixes_rec(gen_ctx, co_localizations, - dir_name, + dir_name,file_name_prefix, &mut 1, &vec![], rem_canals); @@ -44,7 +45,7 @@ fn get_exhaustive_slicing<'a>(gen_ctx : &GeneralContext, &SliceKind::Suffix => { get_all_suffixes_rec(gen_ctx, co_localizations, - dir_name, + dir_name,file_name_prefix, &mut 1, &vec![], rem_canals); @@ -52,7 +53,7 @@ fn get_exhaustive_slicing<'a>(gen_ctx : &GeneralContext, &SliceKind::Slice => { get_all_slices_rec(gen_ctx, co_localizations, - dir_name, + dir_name,file_name_prefix, &mut 1, &vec![], rem_canals); @@ -65,6 +66,7 @@ pub fn generate_slices(gen_ctx : &GeneralContext, mu_name : &str, multi_trace : &MultiTrace, parent_folder : Option<&str>, + file_name_prefix_opt : Option<&str>, select : &SliceGenerationSelection, kind : &SliceKind) { let dir_name : String; @@ -73,9 +75,19 @@ pub fn generate_slices(gen_ctx : &GeneralContext, dir_name = format!("./{:}_slices", mu_name); }, Some( parent ) => { - dir_name = format!("{:}/{:}_slices", parent, mu_name); + dir_name = parent.to_string(); } } + let file_name_prefix : String; + match file_name_prefix_opt { + None => { + file_name_prefix = "".to_string(); + }, + Some( got_fnp ) => { + file_name_prefix = got_fnp.to_string(); + } + } + /* // empties directory if exists match fs::remove_dir_all(&dir_name) { Ok(_) => { @@ -85,6 +97,7 @@ pub fn generate_slices(gen_ctx : &GeneralContext, // do nothing } } + */ // creates directory fs::create_dir_all(&dir_name).unwrap(); // *** @@ -93,32 +106,18 @@ pub fn generate_slices(gen_ctx : &GeneralContext, get_exhaustive_slicing(gen_ctx, co_localizations, kind, - &dir_name, + &dir_name,&file_name_prefix, &mut multi_trace.iter()); }, &SliceGenerationSelection::Random( mut num_slices, wide ) => { get_random_slicing(gen_ctx, co_localizations, - &dir_name, + &dir_name,&file_name_prefix, &mut num_slices, - &multi_trace,kind, + &multi_trace, + kind, wide); } } } -/* -fn get_total_num_slices(multi_trace : &AnalysableMultiTrace) -> u32 { - let mut prod : u32 = 1; - for canal in &multi_trace.canals { - let canal_len = canal.trace.len(); - if canal_len > 1 { - let num_slices_of_canal : u32 = 1 + ( (1..canal_len as u32).sum::() ); - prod = prod * num_slices_of_canal; - } else if canal_len == 1 { - prod = prod * 2; - } - } - return prod; -} -*/ diff --git a/src/trace_manip/slice/random.rs b/src/trace_manip/slice/random.rs index a914944..1789f89 100644 --- a/src/trace_manip/slice/random.rs +++ b/src/trace_manip/slice/random.rs @@ -18,6 +18,7 @@ limitations under the License. use std::cmp::{max, min}; use std::collections::HashSet; +use std::path::PathBuf; use rand::distributions::{Distribution, Uniform}; use rand::rngs::ThreadRng; @@ -25,7 +26,8 @@ use crate::core::colocalizations::CoLocalizations; use crate::core::execution::trace::multitrace::{MultiTrace, Trace}; use crate::core::general_context::GeneralContext; -use crate::output::to_hfiles::multitrace_to_htf::write_multi_trace_into_file; +use crate::io::file_extensions::HIBOU_TRACE_FILE_EXTENSION; +use crate::io::output::to_hfiles::trace::to_htf::write_multi_trace_into_file; use crate::trace_manip::slice::conf::SliceKind; @@ -33,6 +35,7 @@ use crate::trace_manip::slice::conf::SliceKind; pub fn get_random_slicing(gen_ctx : &GeneralContext, co_localizations : &CoLocalizations, dir_name : &str, + file_name_prefix : &str, num_slices : &mut u32, multi_trace : &MultiTrace, kind : &SliceKind, @@ -52,12 +55,15 @@ pub fn get_random_slicing(gen_ctx : &GeneralContext, new_canals_ids.push( ids ); } // *** - let file_path = format!("{:}/s{:}", dir_name, num_slices); + let file_name = format!("{:}s{:}.{:}", file_name_prefix, num_slices, HIBOU_TRACE_FILE_EXTENSION); + let path : PathBuf = [dir_name, &file_name].iter().collect(); + //let file_path = format!("{:}/{:}s{:}", dir_name, file_name_prefix, num_slices); *num_slices = *num_slices - 1; // *** if !slices.contains( &new_canals_ids ) { - write_multi_trace_into_file(&file_path, - gen_ctx,co_localizations, + write_multi_trace_into_file(path.as_path(), + gen_ctx, + co_localizations, &new_multi_trace); slices.insert(new_canals_ids); } @@ -97,9 +103,11 @@ fn get_any_cut(rng : &mut ThreadRng, length : usize, kind : &SliceKind) -> (usiz } } // *** - let min_id = min(id1,id2); - let max_id = max(id1,id2); - return (min_id,max_id); + if id2 >= id1 { + return (id1,id2); + } else { + return (id2,id1); + } } fn get_wider_cut(rng : &mut ThreadRng, length : usize, kind : &SliceKind) -> (usize,usize) { diff --git a/src/ui/commands/cli_analyze.rs b/src/ui/commands/cli_analyze.rs index 3e5f3cf..1ddaea3 100644 --- a/src/ui/commands/cli_analyze.rs +++ b/src/ui/commands/cli_analyze.rs @@ -19,10 +19,10 @@ use std::time::Instant; use clap::ArgMatches; use crate::core::execution::trace::multitrace::multi_trace_length; -use crate::input::hsf::interface::parse_hsf_file; -use crate::input::hif::interface::parse_hif_file; -use crate::input::hcf::interface::{parse_hcf_file_for_ana,HibouAnalyzeOptions}; -use crate::input::htf::interface::parse_htf_file; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::io::input::hif::interface::parse_hif_file; +use crate::io::input::hcf::interface::{parse_hcf_file_for_ana,HibouAnalyzeOptions}; +use crate::io::input::htf::interface::parse_htf_file; use crate::process::ana_proc::logic::flags::MultiTraceAnalysisFlags; use crate::process::ana_proc::manager::AnalysisProcessManager; diff --git a/src/ui/commands/cli_canonize.rs b/src/ui/commands/cli_canonize.rs index be3633f..00de960 100644 --- a/src/ui/commands/cli_canonize.rs +++ b/src/ui/commands/cli_canonize.rs @@ -15,52 +15,65 @@ limitations under the License. */ -use std::collections::HashSet; -use std::fs::write; -use std::path::Path; + use std::time::Instant; -use clap::App; use clap::ArgMatches; +use crate::io::input::hcf::interface::{HibouCanonizeOptions, parse_hcf_file_for_canonize}; +use crate::io::input::hif::interface::parse_hif_file; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::process::canon_proc::manager::CanonizationProcessManager; + pub fn cli_canonize(matches : &ArgMatches) -> (Vec,u32) { let hsf_file_path = matches.value_of("hsf").unwrap(); match parse_hsf_file(hsf_file_path) { Err(e) => { - ret_print.push( e.to_string() ); - print_retval(ret_print); - return -1; + return (vec![e.to_string()],1); }, - Ok( (gen_ctx,my_int,_) ) => { - let file_name = Path::new(hsf_file_path).file_stem().unwrap().to_str().unwrap(); - let process_name : String; - let search_all : bool; - // *** - if matches.is_present("searchall") { - process_name = format!("{}_canon_all", file_name); - search_all = true; - } else { - process_name = format!("{}_canon_one", file_name); - search_all = false; - } - // *** - if my_int.has_coregions() || my_int.has_ands() { - ret_print.push( "Interaction term has coregions and/or ands -> Not Implemented".to_string() ); - print_retval(ret_print); - return -1; - } - // *** - canon_process_interaction_term(&my_int,&gen_ctx,&process_name,search_all); - // *** - ret_print.push( "".to_string()); - ret_print.push( "CANONIZING process for INTERACTION".to_string()); - ret_print.push( format!("from file '{}'",hsf_file_path) ); - ret_print.push( format!("on file : {}.svg",process_name) ); - ret_print.push( "".to_string()); - if search_all { - ret_print.push( "(searched all transformation sequences)".to_string()); - } else { - ret_print.push( "(searched one transformation sequence)".to_string()); + Ok( gen_ctx ) => { + let hif_file_path = matches.value_of("hif").unwrap(); + match parse_hif_file(&gen_ctx,hif_file_path) { + Err(e) => { + return (vec![e.to_string()],1); + }, + Ok( int) => { + let canon_opts : HibouCanonizeOptions; + if matches.is_present("hcf") { + let hcf_file_path = matches.value_of("hcf").unwrap(); + match parse_hcf_file_for_canonize(&gen_ctx,hcf_file_path) { + Err(e) => { + return (vec![e.to_string()],1); + }, + Ok( got_canon_opt) => { + canon_opts = got_canon_opt; + } + } + } else { + canon_opts = HibouCanonizeOptions::default(); + } + let mut ret_print = vec![]; + // *** + ret_print.push( "".to_string()); + ret_print.push( "CANONIZING process for INTERACTION".to_string()); + ret_print.push( format!("from file '{}'",hif_file_path) ); + ret_print.push( "".to_string()); + // *** + let mut manager = CanonizationProcessManager::new(gen_ctx, + canon_opts.strategy, + canon_opts.filters, + canon_opts.priorities, + canon_opts.loggers, + canon_opts.search_all); + // *** + let now = Instant::now(); + let node_count = manager.canonize(int); + let elapsed_time = now.elapsed(); + ret_print.push( format!("node count : {:?}", node_count ) ); + ret_print.push( format!("elapsed : {:?}", elapsed_time.as_secs_f64() ) ); + return (ret_print,0); + } } } } -} \ No newline at end of file +} + diff --git a/src/ui/commands/cli_draw.rs b/src/ui/commands/cli_draw.rs index e4c9737..772d036 100644 --- a/src/ui/commands/cli_draw.rs +++ b/src/ui/commands/cli_draw.rs @@ -19,9 +19,11 @@ use std::path::Path; use clap::ArgMatches; -use crate::input::hsf::interface::parse_hsf_file; -use crate::input::hif::interface::parse_hif_file; -use crate::output::rendering::custom_draw::seqdiag::interaction::draw_interaction; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::io::input::hif::interface::parse_hif_file; +use crate::io::output::draw_interactions::interface::{InteractionGraphicalRepresentation,draw_interaction}; + + pub fn cli_draw(matches : &ArgMatches) -> (Vec,u32) { let hsf_file_path = matches.value_of("hsf").unwrap(); @@ -36,21 +38,41 @@ pub fn cli_draw(matches : &ArgMatches) -> (Vec,u32) { return (vec![e.to_string()],1); }, Ok( int) => { - let mut ret_print = vec![]; - let spec_output_file : String; + let rep_kind : InteractionGraphicalRepresentation; + if matches.is_present("representation") { + let extracted = matches.value_of("representation").unwrap(); + match extracted { + "sd" => { + rep_kind = InteractionGraphicalRepresentation::AsSequenceDiagram; + }, + "tt" => { + rep_kind = InteractionGraphicalRepresentation::AsTerm; + }, + _ => { + return (vec![format!("unknown representation kind : {:}",extracted)], 1); + } + } + } else { + rep_kind = InteractionGraphicalRepresentation::AsSequenceDiagram; + } + // *** + let output_file_name : String; if matches.is_present("output") { let extracted = matches.value_of("output").unwrap(); - spec_output_file = format!("{}.png", extracted); + output_file_name = extracted.to_string(); } else { let file_name = Path::new(hif_file_path).file_stem().unwrap().to_str().unwrap(); - spec_output_file = format!("{}.png", file_name); + output_file_name = format!("{}_repr", file_name); } + // *** + draw_interaction(&gen_ctx, &int, &rep_kind, &"temp".to_string(), &"".to_string(), &output_file_name); + // *** + let mut ret_print = vec![]; ret_print.push( "".to_string()); ret_print.push( "DRAWING INTERACTION".to_string()); ret_print.push( format!("from file '{}'",hif_file_path) ); - ret_print.push( format!("on file : {}",spec_output_file) ); + ret_print.push( format!("on file : {}",output_file_name) ); ret_print.push( "".to_string()); - draw_interaction(&gen_ctx,&spec_output_file, &int); return (ret_print,0); } } diff --git a/src/ui/commands/cli_explore.rs b/src/ui/commands/cli_explore.rs index 9f96cf8..e9248fe 100644 --- a/src/ui/commands/cli_explore.rs +++ b/src/ui/commands/cli_explore.rs @@ -21,9 +21,9 @@ use std::time::Instant; use clap::ArgMatches; -use crate::input::hsf::interface::parse_hsf_file; -use crate::input::hif::interface::parse_hif_file; -use crate::input::hcf::interface::{parse_hcf_file_for_explore,HibouExploreOptions}; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::io::input::hif::interface::parse_hif_file; +use crate::io::input::hcf::interface::{parse_hcf_file_for_explore,HibouExploreOptions}; use crate::process::explo_proc::manager::ExplorationProcessManager; diff --git a/src/ui/commands/cli_mutate_insert_noise.rs b/src/ui/commands/cli_mutate_insert_noise.rs index fdb82e5..b1e9b4d 100644 --- a/src/ui/commands/cli_mutate_insert_noise.rs +++ b/src/ui/commands/cli_mutate_insert_noise.rs @@ -20,8 +20,8 @@ use std::path::Path; use clap::ArgMatches; -use crate::input::hsf::interface::parse_hsf_file; -use crate::input::htf::interface::parse_htf_file; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::io::input::htf::interface::parse_htf_file; use crate::trace_manip::mutate::insert_noise::generate_insert_noise_mutant; diff --git a/src/ui/commands/cli_mutate_swap_actions.rs b/src/ui/commands/cli_mutate_swap_actions.rs index 5017ef3..a5a933c 100644 --- a/src/ui/commands/cli_mutate_swap_actions.rs +++ b/src/ui/commands/cli_mutate_swap_actions.rs @@ -20,8 +20,8 @@ use std::path::Path; use clap::ArgMatches; use crate::core::general_context::GeneralContext; -use crate::input::hsf::interface::parse_hsf_file; -use crate::input::htf::interface::parse_htf_file; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::io::input::htf::interface::parse_htf_file; use crate::trace_manip::mutate::swap_actions::generate_swap_actions_mutant; diff --git a/src/ui/commands/cli_mutate_swap_components.rs b/src/ui/commands/cli_mutate_swap_components.rs index be5d550..2f3dfa0 100644 --- a/src/ui/commands/cli_mutate_swap_components.rs +++ b/src/ui/commands/cli_mutate_swap_components.rs @@ -19,8 +19,8 @@ use std::path::Path; use clap::ArgMatches; -use crate::input::hsf::interface::parse_hsf_file; -use crate::input::htf::interface::parse_htf_file; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::io::input::htf::interface::parse_htf_file; use crate::trace_manip::mutate::swap_component::generate_swap_components_mutant; diff --git a/src/ui/commands/cli_puml_ap.rs b/src/ui/commands/cli_puml_ap.rs index 15ae06e..b138eed 100644 --- a/src/ui/commands/cli_puml_ap.rs +++ b/src/ui/commands/cli_puml_ap.rs @@ -19,8 +19,8 @@ use std::path::Path; use clap::ArgMatches; -use crate::input::hsf::interface::parse_hsf_file; -use crate::input::hif::interface::parse_hif_file; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::io::input::hif::interface::parse_hif_file; use crate::plantuml::automata_product::to_plant_uml_ap; diff --git a/src/ui/commands/cli_puml_sd.rs b/src/ui/commands/cli_puml_sd.rs index f997a36..ae8e5a8 100644 --- a/src/ui/commands/cli_puml_sd.rs +++ b/src/ui/commands/cli_puml_sd.rs @@ -19,8 +19,8 @@ use std::path::Path; use clap::ArgMatches; -use crate::input::hsf::interface::parse_hsf_file; -use crate::input::hif::interface::parse_hif_file; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::io::input::hif::interface::parse_hif_file; use crate::plantuml::sequence::to_plant_uml_sd; diff --git a/src/ui/commands/cli_slice.rs b/src/ui/commands/cli_slice.rs index d94273c..78aa12a 100644 --- a/src/ui/commands/cli_slice.rs +++ b/src/ui/commands/cli_slice.rs @@ -18,9 +18,8 @@ use std::path::Path; use clap::ArgMatches; -use crate::core::general_context::GeneralContext; -use crate::input::hsf::interface::parse_hsf_file; -use crate::input::htf::interface::parse_htf_file; +use crate::io::input::hsf::interface::parse_hsf_file; +use crate::io::input::htf::interface::parse_htf_file; use crate::trace_manip::slice::conf::{SliceGenerationSelection, SliceKind}; use crate::trace_manip::slice::generate::generate_slices; @@ -55,6 +54,16 @@ pub fn cli_slice(matches : &ArgMatches) -> (Vec,u32) { } } // *** + let file_name_prefix_opt : Option<&str>; + match matches.value_of("name") { + None => { + file_name_prefix_opt = None; + }, + Some( got_name ) => { + file_name_prefix_opt = Some( got_name ); + } + } + // *** let generation_selection : SliceGenerationSelection; if matches.is_present("random") { let extracted = matches.value_of("random").unwrap(); @@ -96,7 +105,7 @@ pub fn cli_slice(matches : &ArgMatches) -> (Vec,u32) { generation_kind = SliceKind::Slice; } // *** - generate_slices(&gen_ctx,&co_localizations,mu_name,&multi_trace,parent_folder,&generation_selection,&generation_kind); + generate_slices(&gen_ctx,&co_localizations,mu_name,&multi_trace,parent_folder,file_name_prefix_opt,&generation_selection,&generation_kind); return (ret_print,0); } } diff --git a/src/ui/commands/cli_term_repr.rs b/src/ui/commands/cli_term_repr.rs deleted file mode 100644 index 81f2669..0000000 --- a/src/ui/commands/cli_term_repr.rs +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2020 Erwan Mahe (github.com/erwanM974) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -use std::collections::HashSet; -use std::fs::write; -use std::path::Path; -use std::time::Instant; -use clap::App; -use clap::ArgMatches; -use crate::input::hsf_file::parse_hsf_file; -use crate::output::rendering::custom_draw::term::term_repr_out::to_term_repr; - - -pub fn cli_term_repr(matches : &ArgMatches) -> (Vec,u32) { - let hsf_file_path = matches.value_of("hsf").unwrap(); - match parse_hsf_file(hsf_file_path) { - Err(e) => { - return (vec![e.to_string()],-1) - }, - Ok( (gen_ctx,my_int,_) ) => { - let file_name = Path::new(hsf_file_path).file_stem().unwrap().to_str().unwrap(); - let output_name = format!("{}_repr", file_name); - // *** - let mut ret_print = vec![]; - ret_print.push( "".to_string()); - ret_print.push( "DRAWING INTERACTION as syntax tree".to_string()); - ret_print.push( format!("from file '{}'",hsf_file_path) ); - ret_print.push( format!("on file : {}.svg",output_name) ); - ret_print.push( "".to_string()); - to_term_repr(&output_name, &my_int, &gen_ctx); - return (ret_print,0); - } - } -} \ No newline at end of file diff --git a/src/ui/commands/mod.rs b/src/ui/commands/mod.rs index 2086ee2..c552351 100644 --- a/src/ui/commands/mod.rs +++ b/src/ui/commands/mod.rs @@ -15,7 +15,7 @@ limitations under the License. */ pub mod cli_analyze; -//pub mod cli_canonize; +pub mod cli_canonize; pub mod cli_draw; pub mod cli_explore; //pub mod cli_merge; diff --git a/src/ui/hibou_cli.rs b/src/ui/hibou_cli.rs index 44f772a..3cb1b0b 100644 --- a/src/ui/hibou_cli.rs +++ b/src/ui/hibou_cli.rs @@ -18,6 +18,7 @@ limitations under the License. use clap::App; use crate::ui::commands::cli_analyze::cli_analyze; +use crate::ui::commands::cli_canonize::cli_canonize; use crate::ui::commands::cli_draw::cli_draw; use crate::ui::commands::cli_explore::cli_explore; use crate::ui::commands::cli_mutate_insert_noise::cli_mutate_insert_noise; @@ -58,6 +59,10 @@ pub fn hibou_cli() -> i32 { let mut got = cli_explore(matches); ret_print = got.0; ret_code = got.1; + } else if let Some(matches) = matches.subcommand_matches("canonize") { + let mut got = cli_canonize(matches); + ret_print = got.0; + ret_code = got.1; } else if let Some(matches) = matches.subcommand_matches("analyze") { let mut got = cli_analyze(matches); ret_print = got.0; diff --git a/src/ui/hibou_cli.yml b/src/ui/hibou_cli.yml index 8ec28ef..a25209f 100644 --- a/src/ui/hibou_cli.yml +++ b/src/ui/hibou_cli.yml @@ -16,13 +16,13 @@ name: hibou_label -version: "0.8.0" +version: "0.8.1" author: Erwan Mahe about: Holistic Interaction Behavioral Oracle Utility - hibou provides utilities for manipulating interaction models (sequence diagrams/sequence charts) subcommands: - draw: - about: utility to draw an interaction as a sequence diagram - version: "0.8.0" + about: utility to draw an interaction either as a sequence diagram or a term tree + version: "0.8.1" author: Erwan Mahe args: - hsf: @@ -38,9 +38,31 @@ subcommands: short: o takes_value: true help: target file for drawing (default is 'the name of the hsf'.png) + - representation: + required: false + short: r + takes_value : true + help: kind of representation (either sequence diagram 'sd' or term tree 'tt') + - canonize: + about: utility to compute the normal form of an interaction + version: "0.8.1" + author: Erwan Mahe + args: + - hsf: + required: true + index: 1 + help: input hibou signature file + - hif: + required: true + index: 2 + help: input hibou interaction file + - hcf: + required: false + index: 3 + help: input hibou configuration file - explore: about: utility to explore the semantics of an interaction - version: "0.8.0" + version: "0.8.1" author: Erwan Mahe args: - hsf: @@ -57,7 +79,7 @@ subcommands: help: input hibou configuration file - analyze: about: utility to analyze a (multi-)trace w.r.t. an interaction - version: "0.8.0" + version: "0.8.1" author: Erwan Mahe args: - hsf: @@ -78,7 +100,7 @@ subcommands: help: input hibou configuration file - slice: about: utility to generate slices of a (multi-)trace - version: "0.8.0" + version: "0.8.1" author: Erwan Mahe args: - hsf: @@ -109,9 +131,14 @@ subcommands: short: w takes_value: false help: keep only wider slices (each component length at least one third of the original) + - name: + required: false + short: n + takes_value: true + help: a name for prefixing generated files names - mutate_insert_noise: about: utility to generate generate a mutant from a multi-trace by inserting noise actions - version: "0.8.0" + version: "0.8.1" author: Erwan Mahe args: - hsf: @@ -149,7 +176,7 @@ subcommands: help: maximum number of inserts (default 1), actual number can be lower due other parameters - mutate_swap_actions: about: utility to generate generate a mutant from a multi-trace by swaping positions of actions within its component traces - version: "0.8.0" + version: "0.8.1" author: Erwan Mahe args: - hsf: @@ -177,7 +204,7 @@ subcommands: help: maximum number of swaps (default 1), actual number can be lower due to multi-trace size - mutate_swap_components: about: utility to generate generate a mutant from two multi-traces by swaping their respective component traces - version: "0.8.0" + version: "0.8.1" author: Erwan Mahe args: - hsf: @@ -209,7 +236,7 @@ subcommands: help: maximum number of swaps (default 1), actual number can be lower due to multi-trace size - puml_sd: about: utility to translate an interaction into a .puml informal sequence diagram spec (.puml) - version: "0.8.0" + version: "0.8.1" author: Erwan Mahe args: - hsf: @@ -222,7 +249,7 @@ subcommands: help: input hibou interaction file - puml_ap: about: utility to translate an interaction into a .puml informal automata product spec (.puml) - version: "0.8.0" + version: "0.8.1" author: Erwan Mahe args: - hsf: diff --git a/src/ui/util/printing.rs b/src/ui/util/printing.rs index 48c35da..565ed38 100644 --- a/src/ui/util/printing.rs +++ b/src/ui/util/printing.rs @@ -30,7 +30,7 @@ fn get_ascii_left() -> Vec<&'static str> { my_vec.push(r#"-"-"- Oracle "#); my_vec.push(r#" \_/ Utility "#); my_vec.push(r#" "#); - my_vec.push(r#" V-label-0.8.0 "#); + my_vec.push(r#" V-label-0.8.1 "#); return my_vec; }