Compare commits

..

No commits in common. "70191d3687afcceb9e9615fe95c768e38cd0c357" and "d6a91b6af6bf6768ca64b1ea07c2926eb588acbd" have entirely different histories.

2 changed files with 45 additions and 188 deletions

View File

@ -5,35 +5,26 @@ use crate::{
use std::{collections::HashSet, time::Duration}; use std::{collections::HashSet, time::Duration};
use uuid::Uuid; use uuid::Uuid;
#[derive(Clone, Debug, PartialEq)]
pub enum GameError {
InvalidGame,
RequiredPropertiesMissing,
InvalidGameNode(GameNodeError),
}
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub enum MoveNodeError { pub enum MoveNodeError {
IncompatibleProperty(parser::Property), IncompatibleProperty,
ConflictingProperty, ConflictingProperty,
NotAMoveNode,
ChildError(Box<GameNodeError>),
} }
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub enum SetupNodeError { pub enum SetupNodeError {
IncompatibleProperty(parser::Property), IncompatibleProperty,
ConflictingProperty,
ConflictingPosition, ConflictingPosition,
NotASetupNode, }
ChildError(Box<GameNodeError>),
#[derive(Clone, Debug, PartialEq)]
pub enum GameError {
InvalidGame,
} }
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub enum GameNodeError { pub enum GameNodeError {
UnsupportedGameNode(MoveNodeError, SetupNodeError), UnsupportedGameNode,
ConflictingProperty,
ConflictingPosition,
} }
#[derive(Clone, Debug, PartialEq, Default)] #[derive(Clone, Debug, PartialEq, Default)]
@ -67,7 +58,7 @@ pub struct Game {
source: Option<String>, source: Option<String>,
time_limit: Option<Duration>, time_limit: Option<Duration>,
overtime: Option<String>, overtime: Option<String>,
transcriber: Option<String>, data_entry: Option<String>,
children: Vec<GameNode>, children: Vec<GameNode>,
} }
@ -100,7 +91,7 @@ impl Game {
source: None, source: None,
time_limit: None, time_limit: None,
overtime: None, overtime: None,
transcriber: None, data_entry: None,
children: vec![], children: vec![],
} }
@ -122,89 +113,7 @@ impl TryFrom<&parser::Tree> for Game {
type Error = GameError; type Error = GameError;
fn try_from(tree: &parser::Tree) -> Result<Self, Self::Error> { fn try_from(tree: &parser::Tree) -> Result<Self, Self::Error> {
let mut ty = None; unimplemented!()
let mut size = None;
let mut black_player = Player {
name: None,
rank: None,
team: None,
};
let mut white_player = Player {
name: None,
rank: None,
team: None,
};
for prop in tree.root.properties.iter() {
match prop {
parser::Property::GameType(ty_) => ty = Some(ty_.clone()),
parser::Property::BoardSize(size_) => size = Some(size_.clone()),
parser::Property::BlackPlayer(name) => {
black_player.name = Some(name.clone());
}
parser::Property::WhitePlayer(name) => {
white_player.name = Some(name.clone());
}
parser::Property::BlackRank(rank) => {
black_player.rank = Some(rank.clone());
}
parser::Property::WhiteRank(rank) => {
white_player.rank = Some(rank.clone());
}
parser::Property::BlackTeam(team) => {
black_player.team = Some(team.clone());
}
parser::Property::WhiteTeam(team) => {
white_player.team = Some(team.clone());
}
_ => {}
}
}
let mut s = match (ty, size) {
(Some(ty), Some(size)) => Ok(Self::new(ty, size, black_player, white_player)),
_ => Err(Self::Error::RequiredPropertiesMissing),
}?;
for prop in tree.root.properties.iter() {
match prop {
parser::Property::GameType(_)
| parser::Property::BoardSize(_)
| parser::Property::BlackPlayer(_)
| parser::Property::WhitePlayer(_)
| parser::Property::BlackRank(_)
| parser::Property::WhiteRank(_)
| parser::Property::BlackTeam(_)
| parser::Property::WhiteTeam(_) => {}
parser::Property::Application(v) => s.app = Some(v.clone()),
parser::Property::Annotator(v) => s.annotator = Some(v.clone()),
parser::Property::Copyright(v) => s.copyright = Some(v.clone()),
parser::Property::EventDates(v) => s.dates = v.clone(),
parser::Property::EventName(v) => s.event = Some(v.clone()),
parser::Property::GameName(v) => s.game_name = Some(v.clone()),
parser::Property::ExtraGameInformation(v) => s.extra_info = Some(v.clone()),
parser::Property::GameOpening(v) => s.opening_info = Some(v.clone()),
parser::Property::GameLocation(v) => s.location = Some(v.clone()),
parser::Property::Result(v) => s.result = v.clone(),
parser::Property::Round(v) => s.round = Some(v.clone()),
parser::Property::Ruleset(v) => s.rules = Some(v.clone()),
parser::Property::Source(v) => s.source = Some(v.clone()),
parser::Property::TimeLimit(v) => s.time_limit = Some(v.clone()),
parser::Property::Overtime(v) => s.overtime = Some(v.clone()),
// parser::Property::Data(v) => s.transcriber = Some(v.clone()),
_ => {}
}
}
s.children = tree
.root
.next
.iter()
.map(|node| GameNode::try_from(node))
.collect::<Result<Vec<GameNode>, GameNodeError>>()
.map_err(GameError::InvalidGameNode)?;
Ok(s)
} }
} }
@ -268,16 +177,10 @@ impl Node for GameNode {
impl TryFrom<&parser::Node> for GameNode { impl TryFrom<&parser::Node> for GameNode {
type Error = GameNodeError; type Error = GameNodeError;
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> { fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
let move_node = MoveNode::try_from(n); MoveNode::try_from(n)
let setup_node = SetupNode::try_from(n); .map(GameNode::MoveNode)
.or_else(|_| SetupNode::try_from(n).map(GameNode::SetupNode))
match (move_node, setup_node) { .map_err(|_| Self::Error::UnsupportedGameNode)
(Ok(node), _) => Ok(Self::MoveNode(node)),
(Err(_), Ok(node)) => Ok(Self::SetupNode(node)),
(Err(move_err), Err(setup_err)) => {
Err(Self::Error::UnsupportedGameNode(move_err, setup_err))
}
}
} }
} }
@ -333,7 +236,7 @@ impl TryFrom<&parser::Node> for MoveNode {
type Error = MoveNodeError; type Error = MoveNodeError;
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> { fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
let mut s = match n.mv() { match n.mv() {
Some((color, mv)) => { Some((color, mv)) => {
let mut s = Self::new(color, mv); let mut s = Self::new(color, mv);
@ -374,24 +277,14 @@ impl TryFrom<&parser::Node> for MoveNode {
parser::Property::Unknown(UnknownProperty { ident, value }) => { parser::Property::Unknown(UnknownProperty { ident, value }) => {
s.unknown_props.push((ident.clone(), value.clone())); s.unknown_props.push((ident.clone(), value.clone()));
} }
_ => return Err(Self::Error::IncompatibleProperty(prop.clone())), _ => return Err(Self::Error::IncompatibleProperty),
} }
} }
Ok(s) Ok(s)
} }
None => Err(Self::Error::NotAMoveNode), None => Err(MoveNodeError::IncompatibleProperty),
}?; }
s.children = n
.next
.iter()
.map(|node| {
GameNode::try_from(node).map_err(|err| Self::Error::ChildError(Box::new(err)))
})
.collect::<Result<Vec<GameNode>, MoveNodeError>>()?;
Ok(s)
} }
} }
@ -441,7 +334,7 @@ impl TryFrom<&parser::Node> for SetupNode {
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> { fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
match n.setup() { match n.setup() {
Some(elements) => Self::new(elements), Some(elements) => Self::new(elements),
None => Err(Self::Error::NotASetupNode), None => Err(Self::Error::IncompatibleProperty),
} }
} }
} }
@ -580,9 +473,9 @@ mod move_node_tests {
], ],
next: vec![], next: vec![],
}; };
assert_matches!( assert_eq!(
MoveNode::try_from(&n), MoveNode::try_from(&n),
Err(MoveNodeError::IncompatibleProperty(_)) Err(MoveNodeError::IncompatibleProperty)
); );
} }
} }
@ -635,9 +528,9 @@ mod path_test {
#[cfg(test)] #[cfg(test)]
mod file_test { mod file_test {
use super::*;
use crate::Win; use crate::Win;
use cool_asserts::assert_matches;
use super::*;
use parser::parse_collection; use parser::parse_collection;
use std::{fs::File, io::Read}; use std::{fs::File, io::Read};
@ -713,7 +606,7 @@ mod file_test {
assert_eq!(game.source, None); assert_eq!(game.source, None);
assert_eq!(game.time_limit, Some(Duration::from_secs(1800))); assert_eq!(game.time_limit, Some(Duration::from_secs(1800)));
assert_eq!(game.overtime, Some("5x30 byo-yomi".to_owned())); assert_eq!(game.overtime, Some("5x30 byo-yomi".to_owned()));
assert_eq!(game.transcriber, None); assert_eq!(game.data_entry, None);
/* /*
Property { Property {
@ -725,26 +618,27 @@ mod file_test {
for i in 0..16 { for i in 0..16 {
assert_eq!(node.properties[i], expected_properties[i]); assert_eq!(node.properties[i], expected_properties[i]);
} }
*/
let children = game.children(); let node = node.next().unwrap();
let node = children.first().unwrap(); let expected_properties = vec![
assert_matches!(node, GameNode::MoveNode(node) => { Property {
assert_eq!(node.color, Color::Black); ident: "B".to_owned(),
assert_eq!(node.mv, Move::Move("pp".to_owned())); values: vec!["pp".to_owned()],
assert_eq!(node.time_left, Some(Duration::from_secs(1795))); },
assert_eq!(node.comments, Some("Geckoz [?]: Good game\nsavanni [23k?]: There we go! This UI is... tough.\nsavanni [23k?]: Have fun! Talk to you at the end.\nGeckoz [?]: Yeah, OGS is much better; I'm a UX professional\n".to_owned()) Property {
)}); ident: "BL".to_owned(),
values: vec!["1795.449".to_owned()],
},
Property {
ident: "C".to_owned(),
values: vec!["Geckoz [?]: Good game\nsavanni [23k?]: There we go! This UI is... tough.\nsavanni [23k?]: Have fun! Talk to you at the end.\nGeckoz [?]: Yeah, OGS is much better; I'm a UX professional\n".to_owned()],
}
];
for i in 0..3 {
assert_eq!(node.properties[i], expected_properties[i]);
}
let children = node.children();
let node = children.first().unwrap();
assert_matches!(node, GameNode::MoveNode(node) => {
assert_eq!(node.color, Color::White);
assert_eq!(node.mv, Move::Move("dp".to_owned()));
assert_eq!(node.time_left, Some(Duration::from_secs(1765)));
assert_eq!(node.comments, None);
});
/*
let node = node.next().unwrap(); let node = node.next().unwrap();
let expected_properties = vec![ let expected_properties = vec![
Property { Property {

View File

@ -300,7 +300,7 @@ impl Node {
.collect::<Vec<SetupInstr>>(), .collect::<Vec<SetupInstr>>(),
); );
} }
_ => return None, _ => unimplemented!(),
} }
} }
if setup.len() > 0 { if setup.len() > 0 {
@ -482,9 +482,6 @@ pub enum Property {
// BL, WL // BL, WL
TimeLeft((Color, Duration)), TimeLeft((Color, Duration)),
// TW, TB
Territory(Color, Vec<Position>),
Unknown(UnknownProperty), Unknown(UnknownProperty),
} }
@ -560,24 +557,6 @@ impl ToString for Property {
Property::User(value) => format!("US[{}]", value), Property::User(value) => format!("US[{}]", value),
Property::WhiteRank(value) => format!("WR[{}]", value), Property::WhiteRank(value) => format!("WR[{}]", value),
Property::WhiteTeam(value) => format!("WT[{}]", value), Property::WhiteTeam(value) => format!("WT[{}]", value),
Property::Territory(Color::White, positions) => {
format!(
"TW{}",
positions
.iter()
.map(|Position(p)| format!("[{}]", p))
.collect::<String>()
)
}
Property::Territory(Color::Black, positions) => {
format!(
"TB{}",
positions
.iter()
.map(|Position(p)| format!("[{}]", p))
.collect::<String>()
)
}
Property::Unknown(UnknownProperty { ident, value }) => { Property::Unknown(UnknownProperty { ident, value }) => {
format!("{}[{}]", ident, value) format!("{}[{}]", ident, value)
} }
@ -692,12 +671,6 @@ fn parse_property<'a, E: nom::error::ParseError<&'a str>>(
"US" => parse_propval(parse_simple_text().map(Property::User))(input)?, "US" => parse_propval(parse_simple_text().map(Property::User))(input)?,
"WR" => parse_propval(parse_simple_text().map(Property::WhiteRank))(input)?, "WR" => parse_propval(parse_simple_text().map(Property::WhiteRank))(input)?,
"WT" => parse_propval(parse_simple_text().map(Property::WhiteTeam))(input)?, "WT" => parse_propval(parse_simple_text().map(Property::WhiteTeam))(input)?,
"TW" => parse_territory()
.map(|p| Property::Territory(Color::White, p))
.parse(input)?,
"TB" => parse_territory()
.map(|p| Property::Territory(Color::Black, p))
.parse(input)?,
_ => parse_propval(parse_simple_text().map(|value| { _ => parse_propval(parse_simple_text().map(|value| {
Property::Unknown(UnknownProperty { Property::Unknown(UnknownProperty {
ident: ident.to_owned(), ident: ident.to_owned(),
@ -775,16 +748,6 @@ fn parse_game_result<'a, E: nom::error::ParseError<&'a str>>() -> impl Parser<&'
alt((parse_draw_result(), parse_void_result(), parse_win_result())) alt((parse_draw_result(), parse_void_result(), parse_win_result()))
} }
fn parse_territory<'a, E: nom::error::ParseError<&'a str>>(
) -> impl Parser<&'a str, Vec<Position>, E> {
many1(|input| {
let (input, _) = tag("[")(input)?;
let (input, position) = parse_simple_text().map(|v| Position(v)).parse(input)?;
let (input, _) = tag("]")(input)?;
Ok((input, position))
})
}
fn parse_propval<'a, E: nom::error::ParseError<&'a str>>( fn parse_propval<'a, E: nom::error::ParseError<&'a str>>(
mut parser: impl Parser<&'a str, Property, E>, mut parser: impl Parser<&'a str, Property, E>,
) -> impl FnMut(&'a str) -> IResult<&'a str, Property, E> { ) -> impl FnMut(&'a str) -> IResult<&'a str, Property, E> {