Compare commits

..

2 Commits

2 changed files with 188 additions and 45 deletions

View File

@ -5,26 +5,35 @@ use crate::{
use std::{collections::HashSet, time::Duration};
use uuid::Uuid;
#[derive(Clone, Debug, PartialEq)]
pub enum GameError {
InvalidGame,
RequiredPropertiesMissing,
InvalidGameNode(GameNodeError),
}
#[derive(Clone, Debug, PartialEq)]
pub enum MoveNodeError {
IncompatibleProperty,
IncompatibleProperty(parser::Property),
ConflictingProperty,
NotAMoveNode,
ChildError(Box<GameNodeError>),
}
#[derive(Clone, Debug, PartialEq)]
pub enum SetupNodeError {
IncompatibleProperty,
IncompatibleProperty(parser::Property),
ConflictingProperty,
ConflictingPosition,
}
#[derive(Clone, Debug, PartialEq)]
pub enum GameError {
InvalidGame,
NotASetupNode,
ChildError(Box<GameNodeError>),
}
#[derive(Clone, Debug, PartialEq)]
pub enum GameNodeError {
UnsupportedGameNode,
UnsupportedGameNode(MoveNodeError, SetupNodeError),
ConflictingProperty,
ConflictingPosition,
}
#[derive(Clone, Debug, PartialEq, Default)]
@ -58,7 +67,7 @@ pub struct Game {
source: Option<String>,
time_limit: Option<Duration>,
overtime: Option<String>,
data_entry: Option<String>,
transcriber: Option<String>,
children: Vec<GameNode>,
}
@ -91,7 +100,7 @@ impl Game {
source: None,
time_limit: None,
overtime: None,
data_entry: None,
transcriber: None,
children: vec![],
}
@ -113,7 +122,89 @@ impl TryFrom<&parser::Tree> for Game {
type Error = GameError;
fn try_from(tree: &parser::Tree) -> Result<Self, Self::Error> {
unimplemented!()
let mut ty = None;
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)
}
}
@ -177,10 +268,16 @@ impl Node for GameNode {
impl TryFrom<&parser::Node> for GameNode {
type Error = GameNodeError;
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
MoveNode::try_from(n)
.map(GameNode::MoveNode)
.or_else(|_| SetupNode::try_from(n).map(GameNode::SetupNode))
.map_err(|_| Self::Error::UnsupportedGameNode)
let move_node = MoveNode::try_from(n);
let setup_node = SetupNode::try_from(n);
match (move_node, setup_node) {
(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))
}
}
}
}
@ -236,7 +333,7 @@ impl TryFrom<&parser::Node> for MoveNode {
type Error = MoveNodeError;
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
match n.mv() {
let mut s = match n.mv() {
Some((color, mv)) => {
let mut s = Self::new(color, mv);
@ -277,14 +374,24 @@ impl TryFrom<&parser::Node> for MoveNode {
parser::Property::Unknown(UnknownProperty { ident, value }) => {
s.unknown_props.push((ident.clone(), value.clone()));
}
_ => return Err(Self::Error::IncompatibleProperty),
_ => return Err(Self::Error::IncompatibleProperty(prop.clone())),
}
}
Ok(s)
}
None => Err(MoveNodeError::IncompatibleProperty),
}
None => Err(Self::Error::NotAMoveNode),
}?;
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)
}
}
@ -334,7 +441,7 @@ impl TryFrom<&parser::Node> for SetupNode {
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
match n.setup() {
Some(elements) => Self::new(elements),
None => Err(Self::Error::IncompatibleProperty),
None => Err(Self::Error::NotASetupNode),
}
}
}
@ -473,9 +580,9 @@ mod move_node_tests {
],
next: vec![],
};
assert_eq!(
assert_matches!(
MoveNode::try_from(&n),
Err(MoveNodeError::IncompatibleProperty)
Err(MoveNodeError::IncompatibleProperty(_))
);
}
}
@ -528,9 +635,9 @@ mod path_test {
#[cfg(test)]
mod file_test {
use crate::Win;
use super::*;
use crate::Win;
use cool_asserts::assert_matches;
use parser::parse_collection;
use std::{fs::File, io::Read};
@ -606,7 +713,7 @@ mod file_test {
assert_eq!(game.source, None);
assert_eq!(game.time_limit, Some(Duration::from_secs(1800)));
assert_eq!(game.overtime, Some("5x30 byo-yomi".to_owned()));
assert_eq!(game.data_entry, None);
assert_eq!(game.transcriber, None);
/*
Property {
@ -618,27 +725,26 @@ mod file_test {
for i in 0..16 {
assert_eq!(node.properties[i], expected_properties[i]);
}
*/
let node = node.next().unwrap();
let expected_properties = vec![
Property {
ident: "B".to_owned(),
values: vec!["pp".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 = game.children();
let node = children.first().unwrap();
assert_matches!(node, GameNode::MoveNode(node) => {
assert_eq!(node.color, Color::Black);
assert_eq!(node.mv, Move::Move("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())
)});
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 expected_properties = vec![
Property {

View File

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