Skip to content

Commit

Permalink
upd data_reader
Browse files Browse the repository at this point in the history
  • Loading branch information
t-lohse committed Feb 12, 2024
1 parent fce42b0 commit 4925fbf
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 79 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ itertools = "0.10.5"
regex = "1"
rayon = "1.6.1"
lazy_static = "1.4.0"
num = "0.4.1"

# Enable optimizations for EDBM in debug mode, but not for our code:
[profile.dev.package.edbm]
Expand Down
10 changes: 1 addition & 9 deletions src/data_reader/json_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,7 @@ pub fn read_json_component<P: AsRef<Path>>(
.join("Components")
.join(format!("{}.json", component_name));

let component: Result<Component, SyntaxResult> = match read_json(&component_path) {
Ok(json) => Ok(json),
Err(error) => Err(SyntaxFailure::unparsable(
error.to_string(),
component_path.display().to_string(),
)),
};

component
read_json(&component_path).map_err(|e| SyntaxFailure::unparseable(e, component_path.display()))
}

/// Opens a file and reads it.
Expand Down
10 changes: 3 additions & 7 deletions src/data_reader/parse_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,8 @@ pub fn parse_system(pair: pest::iterators::Pair<Rule>) -> SystemExpression {

SystemExpression::Component(comp_name, special_id)
}
Rule::variable_name => {
let comp_name = pair.as_str().to_string();
SystemExpression::Component(comp_name, None)
}
Rule::variable_name => SystemExpression::Component(pair.as_str().to_string(), None),

_ => unreachable!("Unexpected rule: {:?}", pair.as_rule()),
})
.map_infix(|left, op, right| {
Expand Down Expand Up @@ -201,9 +199,7 @@ fn parse_query(pair: pest::iterators::Pair<Rule>) -> QueryExpression {
QueryExpression::BisimMinim(SaveExpression { system, name })
}
Rule::syntax => {
let mut pairs = pair.into_inner();
let system = parse_system(pairs.next().unwrap());
QueryExpression::Syntax(system)
QueryExpression::Syntax(parse_system(pair.into_inner().next().unwrap()))
}
_ => unreachable!("Unexpected rule: {:?}", pair.as_rule()),
};
Expand Down
2 changes: 1 addition & 1 deletion src/data_reader/proto_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ fn proto_location_tree_to_location_tree(
) -> Rc<LocationTree> {
let target: SpecificLocation = location_tree.into();

system.construct_location_tree(target).unwrap()
system.construct_location_tree(target).unwrap() // TODO maybe handle `Err` better
}

fn proto_constraint_to_constraint(
Expand Down
93 changes: 38 additions & 55 deletions src/data_reader/serialization.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::data_reader::parse_edge;
use crate::model_objects::expressions;
use crate::data_reader::parse_edge::{parse_guard, parse_updates, Update};
use crate::model_objects::expressions::{ArithExpression, BoolExpression};
use crate::model_objects::{Component, Declarations, Edge, Location, LocationType, SyncType};
use crate::simulation::graph_layout::layout_dummy_component;
use edbm::util::constraints::ClockIndex;
use itertools::Itertools;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::ops::Add;
Expand Down Expand Up @@ -45,12 +46,12 @@ pub struct DummyEdge {
deserialize_with = "decode_guard",
serialize_with = "encode_opt_boolexpr"
)]
pub guard: Option<expressions::BoolExpression>,
pub guard: Option<BoolExpression>,
#[serde(
deserialize_with = "decode_update",
serialize_with = "encode_opt_updates"
)]
pub update: Option<Vec<parse_edge::Update>>,
pub update: Option<Vec<Update>>,
#[serde(deserialize_with = "decode_sync")]
pub sync: String,
pub select: String,
Expand Down Expand Up @@ -138,7 +139,7 @@ pub struct DummyLocation {
//deserialize_with = "decode_invariant",
serialize_with = "encode_opt_boolexpr"
)]
pub invariant: Option<expressions::BoolExpression>,
pub invariant: Option<BoolExpression>,
#[serde(
//deserialize_with = "decode_location_type",
serialize_with = "encode_location_type",
Expand Down Expand Up @@ -180,12 +181,26 @@ pub fn decode_declarations<'de, D>(deserializer: D) -> Result<Declarations, D::E
where
D: Deserializer<'de>,
{
fn take_var_names<T: num::Integer + Copy>(
dest: &mut HashMap<String, T>,
counter: &mut T,
str: Vec<String>,
) {
for split_str in str.iter().skip(1) {
let comma_split: Vec<String> = split_str.split(',').map(|s| s.into()).collect();
for var in comma_split.into_iter().filter(|s| !s.is_empty()) {
dest.insert(var, *counter);
*counter = *counter + num::one();
}
}
}
let s = String::deserialize(deserializer)?;
//Split string into vector of strings
let decls: Vec<String> = s.split('\n').map(|s| s.into()).collect();
let mut ints: HashMap<String, i32> = HashMap::new();
let mut clocks: HashMap<String, ClockIndex> = HashMap::new();
let mut counter: ClockIndex = 1;
let mut clock_counter = 1;
let mut int_counter = 1;
for string in decls {
//skip comments
if string.starts_with("//") || string.is_empty() {
Expand All @@ -199,24 +214,9 @@ where
let variable_type = split_string[0].as_str();

if variable_type == "clock" {
for split_str in split_string.iter().skip(1) {
let comma_split: Vec<String> =
split_str.split(',').map(|s| s.into()).collect();
for var in comma_split {
if !var.is_empty() {
clocks.insert(var, counter);
counter += 1;
}
}
}
take_var_names(&mut clocks, &mut clock_counter, split_string);
} else if variable_type == "int" {
for split_str in split_string.iter().skip(1) {
let comma_split: Vec<String> =
split_str.split(',').map(|s| s.into()).collect();
for var in comma_split {
ints.insert(var, 0);
}
}
take_var_names(&mut ints, &mut int_counter, split_string);
} else {
panic!("Not implemented read for type: \"{}\"", variable_type);
}
Expand All @@ -228,23 +228,21 @@ where
}

/// Function used for deserializing guards
pub fn decode_guard<'de, D>(
deserializer: D,
) -> Result<Option<expressions::BoolExpression>, D::Error>
pub fn decode_guard<'de, D>(deserializer: D) -> Result<Option<BoolExpression>, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
if s.is_empty() {
return Ok(None);
}
parse_edge::parse_guard(&s).map(Some).map_err(|err| {
parse_guard(&s).map(Some).map_err(|err| {
serde::de::Error::custom(format!("Could not parse {} got error: {:?}", s, err))
})
}

//Function used for deserializing updates
pub fn decode_update<'de, D>(deserializer: D) -> Result<Option<Vec<parse_edge::Update>>, D::Error>
pub fn decode_update<'de, D>(deserializer: D) -> Result<Option<Vec<Update>>, D::Error>
where
D: Deserializer<'de>,
{
Expand All @@ -253,23 +251,21 @@ where
return Ok(None);
}

parse_edge::parse_updates(&s).map(Some).map_err(|err| {
parse_updates(&s).map(Some).map_err(|err| {
serde::de::Error::custom(format!("Could not parse {} got error: {:?}", s, err))
})
}

//Function used for deserializing invariants
pub fn decode_invariant<'de, D>(
deserializer: D,
) -> Result<Option<expressions::BoolExpression>, D::Error>
pub fn decode_invariant<'de, D>(deserializer: D) -> Result<Option<BoolExpression>, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
if s.is_empty() {
return Ok(None);
}
match parse_edge::parse_guard(&s) {
match parse_guard(&s) {
Ok(edge_attribute) => Ok(Some(edge_attribute)),
Err(e) => panic!("Could not parse invariant {} got error: {:?}", s, e),
}
Expand Down Expand Up @@ -350,23 +346,16 @@ pub fn encode_declarations<S>(decls: &Declarations, serializer: S) -> Result<S::
where
S: Serializer,
{
let mut output = String::from("clock ");
let mut it = decls.clocks.iter();
if let Some((first_clock, _)) = it.next() {
output = output.add(first_clock);

for (clock, _) in it {
output = output.add(&format!(", {}", clock));
}
output = output.add(";");

return serializer.serialize_str(&output);
let it = decls.clocks.keys().join(", ");
if it.is_empty() {
serializer.serialize_str("")
} else {
serializer.serialize_str(format!("clock {}", it).as_str())
}
serializer.serialize_str("")
}

pub fn encode_opt_boolexpr<S>(
opt_expr: &Option<expressions::BoolExpression>,
opt_expr: &Option<BoolExpression>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
Expand All @@ -379,28 +368,22 @@ where
}
}

pub fn encode_boolexpr<S>(
expr: &expressions::BoolExpression,
serializer: S,
) -> Result<S::Ok, S::Error>
pub fn encode_boolexpr<S>(expr: &BoolExpression, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&expr.encode_expr())
}

pub fn encode_arithexpr<S>(
expr: &expressions::ArithExpression,
serializer: S,
) -> Result<S::Ok, S::Error>
pub fn encode_arithexpr<S>(expr: &ArithExpression, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&expr.encode_expr())
}

pub fn encode_opt_updates<S>(
opt_updates: &Option<Vec<parse_edge::Update>>,
opt_updates: &Option<Vec<Update>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
Expand Down
15 changes: 8 additions & 7 deletions src/system/query_failures.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::fmt::Display;
use std::{collections::HashSet, fmt};

use crate::model_objects::{Component, State, StatePair};
Expand Down Expand Up @@ -527,10 +528,10 @@ pub enum SyntaxFailure {
}

impl SyntaxFailure {
pub fn unparsable(msg: impl Into<String>, path: impl Into<String>) -> SyntaxResult {
pub fn unparseable<M: Display, P: Display>(msg: M, path: P) -> SyntaxResult {
Err(SyntaxFailure::Unparsable {
msg: msg.into(),
path: path.into(),
msg: msg.to_string(),
path: path.to_string(),
})
}
}
Expand All @@ -539,8 +540,8 @@ impl SyntaxFailure {
// --- Format Display Impl --- //
// ---------------------------- //

impl fmt::Display for DeterminismFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
impl Display for DeterminismFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"The system '{}' is not deterministic in state {} for {}",
Expand All @@ -549,8 +550,8 @@ impl fmt::Display for DeterminismFailure {
}
}

impl fmt::Display for RefinementFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl Display for RefinementFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RefinementFailure::CutsDelaySolutions {
system,
Expand Down

0 comments on commit 4925fbf

Please sign in to comment.