Compare commits
17 Commits
b2063943e9
...
70191d3687
Author | SHA1 | Date |
---|---|---|
Savanni D'Gerinel | 70191d3687 | |
Savanni D'Gerinel | 99bb36dbcd | |
Savanni D'Gerinel | d6a91b6af6 | |
Savanni D'Gerinel | 33d0897096 | |
Savanni D'Gerinel | d29928aa3c | |
Savanni D'Gerinel | c07e793b55 | |
Savanni D'Gerinel | f19c3a6d79 | |
Savanni D'Gerinel | 9db26562e4 | |
Savanni D'Gerinel | 6d8ece3d29 | |
Savanni D'Gerinel | 52f663264e | |
Savanni D'Gerinel | aa8cd9e178 | |
Savanni D'Gerinel | 31e70bfc2a | |
Savanni D'Gerinel | 18216160c9 | |
Savanni D'Gerinel | 8070148a99 | |
Savanni D'Gerinel | a6be0129d6 | |
Savanni D'Gerinel | aa053cd10f | |
Savanni D'Gerinel | 0700f13429 |
|
@ -2309,6 +2309,7 @@ dependencies = [
|
|||
"serde",
|
||||
"thiserror",
|
||||
"typeshare",
|
||||
"uuid 1.4.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -2726,6 +2727,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
@ -6,11 +6,13 @@ edition = "2021"
|
|||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
cool_asserts = { version = "*" }
|
||||
chrono = { version = "0.4", features = [ "serde" ] }
|
||||
nom = { version = "7" }
|
||||
serde = { version = "1", features = [ "derive" ] }
|
||||
thiserror = { version = "1"}
|
||||
typeshare = { version = "1" }
|
||||
uuid = { version = "1.4", features = ["v4", "serde"] }
|
||||
|
||||
[dev-dependencies]
|
||||
cool_asserts = { version = "2" }
|
||||
|
|
|
@ -107,6 +107,7 @@ pub fn parse_date_field(s: &str) -> Result<Vec<Date>, Error> {
|
|||
Ok(dates)
|
||||
}
|
||||
|
||||
/*
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
@ -158,3 +159,4 @@ mod test {
|
|||
);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
|
|
@ -0,0 +1,766 @@
|
|||
use crate::{
|
||||
parser::{self, Annotation, Evaluation, GameType, Move, SetupInstr, Size, UnknownProperty},
|
||||
Color, Date, GameResult,
|
||||
};
|
||||
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(parser::Property),
|
||||
ConflictingProperty,
|
||||
NotAMoveNode,
|
||||
ChildError(Box<GameNodeError>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SetupNodeError {
|
||||
IncompatibleProperty(parser::Property),
|
||||
ConflictingProperty,
|
||||
ConflictingPosition,
|
||||
NotASetupNode,
|
||||
ChildError(Box<GameNodeError>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GameNodeError {
|
||||
UnsupportedGameNode(MoveNodeError, SetupNodeError),
|
||||
ConflictingProperty,
|
||||
ConflictingPosition,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Default)]
|
||||
pub struct Player {
|
||||
pub name: Option<String>,
|
||||
pub rank: Option<String>,
|
||||
pub team: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Game {
|
||||
game_type: GameType,
|
||||
|
||||
// TODO: board size is not necessary in all games. Hive has no defined board size.
|
||||
board_size: Size,
|
||||
black_player: Player,
|
||||
white_player: Player,
|
||||
|
||||
app: Option<String>,
|
||||
annotator: Option<String>,
|
||||
copyright: Option<String>,
|
||||
dates: Vec<Date>,
|
||||
event: Option<String>,
|
||||
game_name: Option<String>,
|
||||
extra_info: Option<String>,
|
||||
opening_info: Option<String>,
|
||||
location: Option<String>,
|
||||
result: GameResult,
|
||||
round: Option<String>,
|
||||
rules: Option<String>,
|
||||
source: Option<String>,
|
||||
time_limit: Option<Duration>,
|
||||
overtime: Option<String>,
|
||||
transcriber: Option<String>,
|
||||
|
||||
children: Vec<GameNode>,
|
||||
}
|
||||
|
||||
impl Game {
|
||||
fn new(
|
||||
game_type: GameType,
|
||||
board_size: Size,
|
||||
black_player: Player,
|
||||
white_player: Player,
|
||||
) -> Self {
|
||||
Self {
|
||||
game_type,
|
||||
board_size,
|
||||
black_player,
|
||||
white_player,
|
||||
|
||||
app: None,
|
||||
annotator: None,
|
||||
copyright: None,
|
||||
dates: vec![],
|
||||
event: None,
|
||||
game_name: None,
|
||||
extra_info: None,
|
||||
opening_info: None,
|
||||
location: None,
|
||||
result: GameResult::Unknown,
|
||||
round: None,
|
||||
rules: None,
|
||||
source: None,
|
||||
time_limit: None,
|
||||
overtime: None,
|
||||
transcriber: None,
|
||||
|
||||
children: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for Game {
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
self.children.iter().collect::<Vec<&'a GameNode>>()
|
||||
}
|
||||
|
||||
fn add_child<'a>(&'a mut self, node: GameNode) -> &'a mut GameNode {
|
||||
self.children.push(node);
|
||||
self.children.last_mut().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&parser::Tree> for Game {
|
||||
type Error = GameError;
|
||||
|
||||
fn try_from(tree: &parser::Tree) -> Result<Self, Self::Error> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GameNode {
|
||||
MoveNode(MoveNode),
|
||||
SetupNode(SetupNode),
|
||||
}
|
||||
|
||||
pub trait Node {
|
||||
/// Provide a pre-order traversal of all of the nodes in the game tree.
|
||||
fn nodes<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
self.children()
|
||||
.iter()
|
||||
.map(|node| {
|
||||
let mut children = node.nodes();
|
||||
let mut v = vec![*node];
|
||||
v.append(&mut children);
|
||||
v
|
||||
})
|
||||
.flatten()
|
||||
.collect::<Vec<&'a GameNode>>()
|
||||
}
|
||||
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode>;
|
||||
fn add_child<'a>(&'a mut self, node: GameNode) -> &'a mut GameNode;
|
||||
}
|
||||
|
||||
impl GameNode {
|
||||
fn id(&self) -> Uuid {
|
||||
match self {
|
||||
GameNode::MoveNode(node) => node.id,
|
||||
GameNode::SetupNode(node) => node.id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for GameNode {
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
match self {
|
||||
GameNode::MoveNode(node) => node.children(),
|
||||
GameNode::SetupNode(node) => node.children(),
|
||||
}
|
||||
}
|
||||
|
||||
fn nodes<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
match self {
|
||||
GameNode::MoveNode(node) => node.nodes(),
|
||||
GameNode::SetupNode(node) => node.nodes(),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_child<'a>(&'a mut self, new_node: GameNode) -> &'a mut GameNode {
|
||||
match self {
|
||||
GameNode::MoveNode(node) => node.add_child(new_node),
|
||||
GameNode::SetupNode(node) => node.add_child(new_node),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&parser::Node> for GameNode {
|
||||
type Error = GameNodeError;
|
||||
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MoveNode {
|
||||
id: Uuid,
|
||||
color: Color,
|
||||
mv: Move,
|
||||
children: Vec<GameNode>,
|
||||
|
||||
time_left: Option<Duration>,
|
||||
moves_left: Option<usize>,
|
||||
name: Option<String>,
|
||||
evaluation: Option<Evaluation>,
|
||||
value: Option<f64>,
|
||||
comments: Option<String>,
|
||||
annotation: Option<Annotation>,
|
||||
unknown_props: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl MoveNode {
|
||||
pub fn new(color: Color, mv: Move) -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4(),
|
||||
color,
|
||||
mv,
|
||||
children: Vec::new(),
|
||||
|
||||
time_left: None,
|
||||
moves_left: None,
|
||||
name: None,
|
||||
evaluation: None,
|
||||
value: None,
|
||||
comments: None,
|
||||
annotation: None,
|
||||
unknown_props: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for MoveNode {
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
self.children.iter().collect::<Vec<&'a GameNode>>()
|
||||
}
|
||||
|
||||
fn add_child<'a>(&'a mut self, node: GameNode) -> &'a mut GameNode {
|
||||
self.children.push(node);
|
||||
self.children.last_mut().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&parser::Node> for MoveNode {
|
||||
type Error = MoveNodeError;
|
||||
|
||||
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
|
||||
let mut s = match n.mv() {
|
||||
Some((color, mv)) => {
|
||||
let mut s = Self::new(color, mv);
|
||||
|
||||
for prop in n.properties.iter() {
|
||||
match prop {
|
||||
parser::Property::Move((color, mv)) => {
|
||||
if s.color != *color || s.mv != *mv {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
}
|
||||
parser::Property::TimeLeft((color, duration)) => {
|
||||
if s.color != *color {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
if s.time_left.is_some() {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
s.time_left = Some(duration.clone());
|
||||
}
|
||||
parser::Property::Comment(cmt) => {
|
||||
if s.comments.is_some() {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
s.comments = Some(cmt.clone());
|
||||
}
|
||||
parser::Property::Evaluation(evaluation) => {
|
||||
if s.evaluation.is_some() {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
s.evaluation = Some(*evaluation)
|
||||
}
|
||||
parser::Property::Annotation(annotation) => {
|
||||
if s.annotation.is_some() {
|
||||
return Err(Self::Error::ConflictingProperty);
|
||||
}
|
||||
s.annotation = Some(*annotation)
|
||||
}
|
||||
parser::Property::Unknown(UnknownProperty { ident, value }) => {
|
||||
s.unknown_props.push((ident.clone(), value.clone()));
|
||||
}
|
||||
_ => return Err(Self::Error::IncompatibleProperty(prop.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(s)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SetupNode {
|
||||
id: Uuid,
|
||||
|
||||
positions: Vec<parser::SetupInstr>,
|
||||
children: Vec<GameNode>,
|
||||
}
|
||||
|
||||
impl SetupNode {
|
||||
pub fn new(positions: Vec<parser::SetupInstr>) -> Result<Self, SetupNodeError> {
|
||||
let mut board = HashSet::new();
|
||||
for position in positions.iter() {
|
||||
let point = match position {
|
||||
SetupInstr::Piece((_, point)) => point,
|
||||
SetupInstr::Clear(point) => point,
|
||||
};
|
||||
if board.contains(point) {
|
||||
return Err(SetupNodeError::ConflictingPosition);
|
||||
}
|
||||
board.insert(point);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
id: Uuid::new_v4(),
|
||||
positions,
|
||||
children: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Node for SetupNode {
|
||||
fn children<'a>(&'a self) -> Vec<&'a GameNode> {
|
||||
self.children.iter().collect::<Vec<&'a GameNode>>()
|
||||
}
|
||||
|
||||
fn add_child<'a>(&'a mut self, node: GameNode) -> &'a mut GameNode {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&parser::Node> for SetupNode {
|
||||
type Error = SetupNodeError;
|
||||
|
||||
fn try_from(n: &parser::Node) -> Result<Self, Self::Error> {
|
||||
match n.setup() {
|
||||
Some(elements) => Self::new(elements),
|
||||
None => Err(Self::Error::NotASetupNode),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path_to_node<'a>(node: &'a GameNode, id: Uuid) -> Vec<&'a GameNode> {
|
||||
if node.id() == id {
|
||||
return vec![node];
|
||||
}
|
||||
|
||||
for child in node.children() {
|
||||
let mut path = path_to_node(child, id);
|
||||
if path.len() > 1 {
|
||||
path.push(child);
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use cool_asserts::assert_matches;
|
||||
|
||||
#[test]
|
||||
fn it_can_create_an_empty_game_tree() {
|
||||
let tree = Game::new(
|
||||
GameType::Go,
|
||||
Size {
|
||||
width: 19,
|
||||
height: 19,
|
||||
},
|
||||
Player::default(),
|
||||
Player::default(),
|
||||
);
|
||||
assert_eq!(tree.nodes().len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_can_add_moves_to_a_game() {
|
||||
let mut game = Game::new(
|
||||
GameType::Go,
|
||||
Size {
|
||||
width: 19,
|
||||
height: 19,
|
||||
},
|
||||
Player::default(),
|
||||
Player::default(),
|
||||
);
|
||||
|
||||
let first_move = MoveNode::new(Color::Black, Move::Move("dd".to_owned()));
|
||||
let first_ = game.add_child(GameNode::MoveNode(first_move.clone()));
|
||||
let second_move = MoveNode::new(Color::White, Move::Move("qq".to_owned()));
|
||||
first_.add_child(GameNode::MoveNode(second_move.clone()));
|
||||
|
||||
let nodes = game.nodes();
|
||||
assert_eq!(nodes.len(), 2);
|
||||
assert_eq!(nodes[0].id(), first_move.id);
|
||||
assert_eq!(nodes[1].id(), second_move.id);
|
||||
}
|
||||
|
||||
fn it_can_set_up_a_game() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn it_can_load_tree_from_sgf() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn game_node_can_parse_sgf_move_node() {
|
||||
let n = parser::Node {
|
||||
properties: vec![
|
||||
parser::Property::Move((Color::White, Move::Move("dp".to_owned()))),
|
||||
parser::Property::TimeLeft((Color::White, Duration::from_secs(176))),
|
||||
parser::Property::Comment("Comments in the game".to_owned()),
|
||||
],
|
||||
next: vec![],
|
||||
};
|
||||
assert_matches!(GameNode::try_from(&n), Ok(GameNode::MoveNode(_)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod root_node_tests {
|
||||
fn it_rejects_move_properties() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn it_rejects_setup_properties() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn it_can_parse_a_root_sgf() {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod move_node_tests {
|
||||
use crate::parser::PositionList;
|
||||
|
||||
use super::*;
|
||||
use cool_asserts::assert_matches;
|
||||
|
||||
#[test]
|
||||
fn it_can_parse_an_sgf_move_node() {
|
||||
let n = parser::Node {
|
||||
properties: vec![
|
||||
parser::Property::Move((Color::White, Move::Move("dp".to_owned()))),
|
||||
parser::Property::TimeLeft((Color::White, Duration::from_secs(176))),
|
||||
parser::Property::Comment("Comments in the game".to_owned()),
|
||||
],
|
||||
next: vec![],
|
||||
};
|
||||
assert_matches!(MoveNode::try_from(&n), Ok(node) => {
|
||||
assert_eq!(node.color, Color::White);
|
||||
assert_eq!(node.mv, Move::Move("dp".to_owned()));
|
||||
assert_eq!(node.children, vec![]);
|
||||
assert_eq!(node.time_left, Some(Duration::from_secs(176)));
|
||||
assert_eq!(node.comments, Some("Comments in the game".to_owned()));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_rejects_an_sgf_setup_node() {
|
||||
let n = parser::Node {
|
||||
properties: vec![
|
||||
parser::Property::Move((Color::White, Move::Move("dp".to_owned()))),
|
||||
parser::Property::TimeLeft((Color::White, Duration::from_secs(176))),
|
||||
parser::Property::SetupBlackStones(PositionList(vec![
|
||||
"dd".to_owned(),
|
||||
"de".to_owned(),
|
||||
])),
|
||||
],
|
||||
next: vec![],
|
||||
};
|
||||
assert_matches!(
|
||||
MoveNode::try_from(&n),
|
||||
Err(MoveNodeError::IncompatibleProperty(_))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod setup_node_tests {
|
||||
use crate::parser::SetupInstr;
|
||||
|
||||
use super::*;
|
||||
use cool_asserts::assert_matches;
|
||||
|
||||
fn it_can_parse_an_sgf_setup_node() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_rejects_conflicting_placement_properties() {
|
||||
assert_matches!(
|
||||
SetupNode::new(vec![
|
||||
SetupInstr::Piece((Color::Black, "dd".to_owned())),
|
||||
SetupInstr::Piece((Color::Black, "dd".to_owned())),
|
||||
]),
|
||||
Err(SetupNodeError::ConflictingPosition)
|
||||
);
|
||||
assert_matches!(
|
||||
SetupNode::new(vec![
|
||||
SetupInstr::Piece((Color::Black, "dd".to_owned())),
|
||||
SetupInstr::Piece((Color::Black, "ee".to_owned())),
|
||||
SetupInstr::Piece((Color::White, "ee".to_owned())),
|
||||
]),
|
||||
Err(SetupNodeError::ConflictingPosition)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod path_test {
|
||||
fn returns_empty_list_if_no_game_nodes() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn returns_empty_list_if_node_not_found() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn path_excludes_root_node() {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod file_test {
|
||||
use super::*;
|
||||
use crate::Win;
|
||||
use cool_asserts::assert_matches;
|
||||
use parser::parse_collection;
|
||||
use std::{fs::File, io::Read};
|
||||
|
||||
fn with_text(text: &str, f: impl FnOnce(Vec<Game>)) {
|
||||
let (_, games) = parse_collection::<nom::error::VerboseError<&str>>(text).unwrap();
|
||||
let games = games
|
||||
.into_iter()
|
||||
.map(|game| Game::try_from(&game).expect("game to parse"))
|
||||
.collect::<Vec<Game>>();
|
||||
f(games);
|
||||
}
|
||||
|
||||
fn with_file(path: &std::path::Path, f: impl FnOnce(Vec<Game>)) {
|
||||
let mut file = File::open(path).unwrap();
|
||||
let mut text = String::new();
|
||||
let _ = file.read_to_string(&mut text);
|
||||
with_text(&text, f);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_can_load_basic_game_records() {
|
||||
with_file(
|
||||
std::path::Path::new("test_data/2020 USGO DDK, Round 1.sgf"),
|
||||
|games| {
|
||||
assert_eq!(games.len(), 1);
|
||||
let game = &games[0];
|
||||
|
||||
assert_eq!(game.game_type, GameType::Go);
|
||||
assert_eq!(
|
||||
game.board_size,
|
||||
Size {
|
||||
width: 19,
|
||||
height: 19
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
game.black_player,
|
||||
Player {
|
||||
name: Some("savanni".to_owned()),
|
||||
rank: Some("23k".to_owned()),
|
||||
team: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
game.white_player,
|
||||
Player {
|
||||
name: Some("Geckoz".to_owned()),
|
||||
rank: None,
|
||||
team: None
|
||||
}
|
||||
);
|
||||
assert_eq!(game.app, Some("CGoban:3".to_owned()));
|
||||
|
||||
assert_eq!(game.annotator, None);
|
||||
assert_eq!(game.copyright, None);
|
||||
assert_eq!(
|
||||
game.dates,
|
||||
vec![Date::Date(
|
||||
chrono::NaiveDate::from_ymd_opt(2020, 8, 5).unwrap()
|
||||
)]
|
||||
);
|
||||
assert_eq!(game.event, None);
|
||||
assert_eq!(game.game_name, None);
|
||||
assert_eq!(game.extra_info, None);
|
||||
assert_eq!(game.opening_info, None);
|
||||
assert_eq!(
|
||||
game.location,
|
||||
Some("The KGS Go Server at http://www.gokgs.com/".to_owned())
|
||||
);
|
||||
assert_eq!(game.result, GameResult::White(Win::Score(17.5)));
|
||||
assert_eq!(game.round, None);
|
||||
assert_eq!(game.rules, Some("AGA".to_owned()));
|
||||
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.transcriber, None);
|
||||
|
||||
/*
|
||||
Property {
|
||||
ident: "KM".to_owned(),
|
||||
values: vec!["7.50".to_owned()],
|
||||
},
|
||||
];
|
||||
|
||||
for i in 0..16 {
|
||||
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 {
|
||||
ident: "W".to_owned(),
|
||||
values: vec!["dp".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "WL".to_owned(),
|
||||
values: vec!["1765.099".to_owned()],
|
||||
},
|
||||
];
|
||||
for i in 0..2 {
|
||||
assert_eq!(node.properties[i], expected_properties[i]);
|
||||
}
|
||||
*/
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
162
sgf/src/go.rs
162
sgf/src/go.rs
|
@ -233,50 +233,6 @@ pub struct GameInfo {
|
|||
pub result: Option<GameResult>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GameResult {
|
||||
Annulled,
|
||||
Draw,
|
||||
Black(Win),
|
||||
White(Win),
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for GameResult {
|
||||
type Error = String;
|
||||
fn try_from(s: &str) -> Result<GameResult, Self::Error> {
|
||||
if s == "0" {
|
||||
Ok(GameResult::Draw)
|
||||
} else if s == "Void" {
|
||||
Ok(GameResult::Annulled)
|
||||
} else {
|
||||
let parts = s.split("+").collect::<Vec<&str>>();
|
||||
let res = match parts[0].to_ascii_lowercase().as_str() {
|
||||
"b" => GameResult::Black,
|
||||
"w" => GameResult::White,
|
||||
_ => return Ok(GameResult::Unknown(parts[0].to_owned())),
|
||||
};
|
||||
match parts[1].to_ascii_lowercase().as_str() {
|
||||
"r" | "resign" => Ok(res(Win::Resignation)),
|
||||
"t" | "time" => Ok(res(Win::Time)),
|
||||
"f" | "forfeit" => Ok(res(Win::Forfeit)),
|
||||
_ => {
|
||||
let score = parts[1].parse::<f32>().unwrap();
|
||||
Ok(res(Win::Score(score)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Win {
|
||||
Score(f32),
|
||||
Resignation,
|
||||
Forfeit,
|
||||
Time,
|
||||
}
|
||||
|
||||
/*
|
||||
enum PropType {
|
||||
Move,
|
||||
|
@ -389,121 +345,5 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn it_presents_the_mainline_of_game_without_branches() {
|
||||
with_file(
|
||||
std::path::Path::new("test_data/2020 USGO DDK, Round 1.sgf"),
|
||||
|trees| {
|
||||
assert_eq!(trees.len(), 1);
|
||||
let tree = &trees[0];
|
||||
|
||||
let node = &tree.root;
|
||||
assert_eq!(node.properties.len(), 16);
|
||||
let expected_properties = vec![
|
||||
Property {
|
||||
ident: "GM".to_owned(),
|
||||
values: vec!["1".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "FF".to_owned(),
|
||||
values: vec!["4".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "CA".to_owned(),
|
||||
values: vec!["UTF-8".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "AP".to_owned(),
|
||||
values: vec!["CGoban:3".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "ST".to_owned(),
|
||||
values: vec!["2".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "RU".to_owned(),
|
||||
values: vec!["AGA".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "SZ".to_owned(),
|
||||
values: vec!["19".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "KM".to_owned(),
|
||||
values: vec!["7.50".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "TM".to_owned(),
|
||||
values: vec!["1800".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "OT".to_owned(),
|
||||
values: vec!["5x30 byo-yomi".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "PW".to_owned(),
|
||||
values: vec!["Geckoz".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "PB".to_owned(),
|
||||
values: vec!["savanni".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "BR".to_owned(),
|
||||
values: vec!["23k".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "DT".to_owned(),
|
||||
values: vec!["2020-08-05".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "PC".to_owned(),
|
||||
values: vec!["The KGS Go Server at http://www.gokgs.com/".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "RE".to_owned(),
|
||||
values: vec!["W+17.50".to_owned()],
|
||||
},
|
||||
];
|
||||
|
||||
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 node = node.next().unwrap();
|
||||
let expected_properties = vec![
|
||||
Property {
|
||||
ident: "W".to_owned(),
|
||||
values: vec!["dp".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "WL".to_owned(),
|
||||
values: vec!["1765.099".to_owned()],
|
||||
},
|
||||
];
|
||||
for i in 0..2 {
|
||||
assert_eq!(node.properties[i], expected_properties[i]);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
fn it_presents_the_mainline_of_game_without_branches() {}
|
||||
}
|
||||
|
|
|
@ -1,67 +1,29 @@
|
|||
mod date;
|
||||
pub use date::Date;
|
||||
|
||||
pub mod go;
|
||||
// pub mod go;
|
||||
|
||||
mod tree;
|
||||
use tree::parse_collection;
|
||||
mod game;
|
||||
|
||||
mod parser;
|
||||
use parser::{parse_collection, Tree};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
InvalidField,
|
||||
InvalidBoardSize,
|
||||
Incomplete,
|
||||
InvalidSgf(VerboseNomError),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct VerboseNomError(nom::error::VerboseError<String>);
|
||||
|
||||
impl From<nom::error::VerboseError<&str>> for VerboseNomError {
|
||||
fn from(err: nom::error::VerboseError<&str>) -> Self {
|
||||
VerboseNomError(nom::error::VerboseError {
|
||||
errors: err
|
||||
.errors
|
||||
.into_iter()
|
||||
.map(|err| (err.0.to_owned(), err.1))
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<nom::Err<nom::error::VerboseError<&str>>> for Error {
|
||||
fn from(err: nom::Err<nom::error::VerboseError<&str>>) -> Self {
|
||||
match err {
|
||||
nom::Err::Incomplete(_) => Error::Incomplete,
|
||||
nom::Err::Error(e) => Error::InvalidSgf(VerboseNomError::from(e)),
|
||||
nom::Err::Failure(e) => Error::InvalidSgf(VerboseNomError::from(e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Error)]
|
||||
pub enum ParseError {
|
||||
#[error("An unknown error was found")]
|
||||
NomError(nom::error::Error<String>),
|
||||
}
|
||||
|
||||
impl From<nom::error::Error<&str>> for ParseError {
|
||||
fn from(err: nom::error::Error<&str>) -> Self {
|
||||
Self::NomError(nom::error::Error {
|
||||
input: err.input.to_owned(),
|
||||
code: err.code.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
mod types;
|
||||
pub use types::*;
|
||||
|
||||
/*
|
||||
pub enum Game {
|
||||
Go(go::Game),
|
||||
Unsupported(tree::Tree),
|
||||
}
|
||||
*/
|
||||
|
||||
pub fn parse_sgf(input: &str) -> Result<Vec<Game>, Error> {
|
||||
pub fn parse_sgf(input: &str) -> Result<Vec<Tree>, Error> {
|
||||
let (_, trees) = parse_collection::<nom::error::VerboseError<&str>>(input)?;
|
||||
Ok(trees)
|
||||
/*
|
||||
let (_, trees) = parse_collection::<nom::error::VerboseError<&str>>(input)?;
|
||||
Ok(trees
|
||||
.into_iter()
|
||||
|
@ -72,6 +34,7 @@ pub fn parse_sgf(input: &str) -> Result<Vec<Game>, Error> {
|
|||
_ => Game::Unsupported(t),
|
||||
})
|
||||
.collect::<Vec<Game>>())
|
||||
*/
|
||||
}
|
||||
|
||||
/*
|
||||
|
|
File diff suppressed because it is too large
Load Diff
562
sgf/src/tree.rs
562
sgf/src/tree.rs
|
@ -1,562 +0,0 @@
|
|||
use crate::Error;
|
||||
use nom::{
|
||||
branch::alt,
|
||||
bytes::complete::{escaped_transform, tag},
|
||||
character::complete::{alpha1, digit1, multispace0, multispace1, none_of},
|
||||
combinator::{opt, value},
|
||||
multi::{many0, many1, separated_list1},
|
||||
IResult,
|
||||
};
|
||||
use std::num::ParseIntError;
|
||||
|
||||
impl From<ParseSizeError> for Error {
|
||||
fn from(_: ParseSizeError) -> Self {
|
||||
Self::InvalidBoardSize
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ParseSizeError {
|
||||
ParseIntError(ParseIntError),
|
||||
InsufficientArguments,
|
||||
}
|
||||
|
||||
impl From<ParseIntError> for ParseSizeError {
|
||||
fn from(e: ParseIntError) -> Self {
|
||||
Self::ParseIntError(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Size {
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for Size {
|
||||
type Error = ParseSizeError;
|
||||
fn try_from(s: &str) -> Result<Self, Self::Error> {
|
||||
let parts = s
|
||||
.split(':')
|
||||
.map(|v| v.parse::<i32>())
|
||||
.collect::<Result<Vec<i32>, ParseIntError>>()?;
|
||||
match parts[..] {
|
||||
[width, height, ..] => Ok(Size { width, height }),
|
||||
[dim] => Ok(Size {
|
||||
width: dim,
|
||||
height: dim,
|
||||
}),
|
||||
[] => Err(ParseSizeError::InsufficientArguments),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Tree {
|
||||
pub root: Node,
|
||||
}
|
||||
|
||||
impl ToString for Tree {
|
||||
fn to_string(&self) -> String {
|
||||
format!("({})", self.root.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Node {
|
||||
pub properties: Vec<Property>,
|
||||
pub next: Vec<Node>,
|
||||
}
|
||||
|
||||
impl ToString for Node {
|
||||
fn to_string(&self) -> String {
|
||||
let props = self
|
||||
.properties
|
||||
.iter()
|
||||
.map(|prop| prop.to_string())
|
||||
.collect::<String>();
|
||||
|
||||
let next = if self.next.len() == 1 {
|
||||
self.next
|
||||
.iter()
|
||||
.map(|node| node.to_string())
|
||||
.collect::<Vec<String>>()
|
||||
.join("")
|
||||
} else {
|
||||
self.next
|
||||
.iter()
|
||||
.map(|node| format!("({})", node.to_string()))
|
||||
.collect::<Vec<String>>()
|
||||
.join("")
|
||||
};
|
||||
format!(";{}{}", props, next)
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
pub fn find_prop(&self, ident: &str) -> Option<Property> {
|
||||
self.properties
|
||||
.iter()
|
||||
.find(|prop| prop.ident == ident)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub fn next<'a>(&'a self) -> Option<&'a Node> {
|
||||
self.next.get(0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Property {
|
||||
pub ident: String,
|
||||
pub values: Vec<String>,
|
||||
}
|
||||
|
||||
impl ToString for Property {
|
||||
fn to_string(&self) -> String {
|
||||
let values = self
|
||||
.values
|
||||
.iter()
|
||||
.map(|val| format!("[{}]", val))
|
||||
.collect::<String>();
|
||||
format!("{}{}", self.ident, values)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_collection<'a, E: nom::error::ParseError<&'a str>>(
|
||||
input: &'a str,
|
||||
) -> IResult<&'a str, Vec<Tree>, E> {
|
||||
let (input, roots) = separated_list1(multispace1, parse_tree)(input)?;
|
||||
let trees = roots
|
||||
.into_iter()
|
||||
.map(|root| Tree { root })
|
||||
.collect::<Vec<Tree>>();
|
||||
|
||||
Ok((input, trees))
|
||||
}
|
||||
|
||||
// note: must preserve unknown properties
|
||||
// note: must fix or preserve illegally formatted game-info properties
|
||||
// note: must correct or delete illegally foramtted properties, but display a warning
|
||||
fn parse_tree<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Node, E> {
|
||||
let (input, _) = multispace0(input)?;
|
||||
let (input, _) = tag("(")(input)?;
|
||||
let (input, node) = parse_node(input)?;
|
||||
let (input, _) = multispace0(input)?;
|
||||
let (input, _) = tag(")")(input)?;
|
||||
|
||||
Ok((input, node))
|
||||
}
|
||||
|
||||
fn parse_node<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Node, E> {
|
||||
let (input, _) = multispace0(input)?;
|
||||
let (input, _) = opt(tag(";"))(input)?;
|
||||
let (input, properties) = many1(parse_property)(input)?;
|
||||
|
||||
let (input, next) = opt(parse_node)(input)?;
|
||||
let (input, mut next_seq) = many0(parse_tree)(input)?;
|
||||
|
||||
let mut next = next.map(|n| vec![n]).unwrap_or(vec![]);
|
||||
next.append(&mut next_seq);
|
||||
|
||||
Ok((input, Node { properties, next }))
|
||||
}
|
||||
|
||||
fn parse_property<'a, E: nom::error::ParseError<&'a str>>(
|
||||
input: &'a str,
|
||||
) -> IResult<&'a str, Property, E> {
|
||||
let (input, _) = multispace0(input)?;
|
||||
let (input, ident) = alpha1(input)?;
|
||||
let (input, values) = many1(parse_propval)(input)?;
|
||||
let (input, _) = multispace0(input)?;
|
||||
|
||||
let values = values
|
||||
.into_iter()
|
||||
.map(|v| v.to_owned())
|
||||
.collect::<Vec<String>>();
|
||||
Ok((
|
||||
input,
|
||||
Property {
|
||||
ident: ident.to_owned(),
|
||||
values,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_propval<'a, E: nom::error::ParseError<&'a str>>(
|
||||
input: &'a str,
|
||||
) -> IResult<&'a str, String, E> {
|
||||
let (input, _) = multispace0(input)?;
|
||||
let (input, _) = tag("[")(input)?;
|
||||
let (input, value) = parse_propval_text(input)?;
|
||||
let (input, _) = tag("]")(input)?;
|
||||
|
||||
Ok((input, value.unwrap_or(String::new())))
|
||||
}
|
||||
|
||||
fn parse_propval_text<'a, E: nom::error::ParseError<&'a str>>(
|
||||
input: &'a str,
|
||||
) -> IResult<&'a str, Option<String>, E> {
|
||||
let (input, value) = opt(escaped_transform(
|
||||
none_of("\\]"),
|
||||
'\\',
|
||||
alt((
|
||||
value("]", tag("]")),
|
||||
value("\\", tag("\\")),
|
||||
value("", tag("\n")),
|
||||
)),
|
||||
))(input)?;
|
||||
Ok((input, value.map(|v| v.to_owned())))
|
||||
}
|
||||
|
||||
pub fn parse_size<'a, E: nom::error::ParseError<&'a str>>(
|
||||
input: &'a str,
|
||||
) -> IResult<&'a str, Size, E> {
|
||||
let (input, dimensions) = separated_list1(tag(":"), digit1)(input)?;
|
||||
let (width, height) = match dimensions.as_slice() {
|
||||
[width] => (width.parse::<i32>().unwrap(), width.parse::<i32>().unwrap()),
|
||||
[width, height] => (
|
||||
width.parse::<i32>().unwrap(),
|
||||
height.parse::<i32>().unwrap(),
|
||||
),
|
||||
_ => (19, 19),
|
||||
};
|
||||
Ok((input, Size { width, height }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &'static str = "(;FF[4]C[root](;C[a];C[b](;C[c])
|
||||
(;C[d];C[e]))
|
||||
(;C[f](;C[g];C[h];C[i])
|
||||
(;C[j])))";
|
||||
|
||||
#[test]
|
||||
fn it_can_parse_properties() {
|
||||
let (_, prop) = parse_property::<nom::error::VerboseError<&str>>("C[a]").unwrap();
|
||||
assert_eq!(
|
||||
prop,
|
||||
Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["a".to_owned()]
|
||||
}
|
||||
);
|
||||
|
||||
let (_, prop) = parse_property::<nom::error::VerboseError<&str>>("C[a][b][c]").unwrap();
|
||||
assert_eq!(
|
||||
prop,
|
||||
Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_can_parse_a_standalone_node() {
|
||||
let (_, node) = parse_node::<nom::error::VerboseError<&str>>(";B[ab]").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
node,
|
||||
Node {
|
||||
properties: vec![Property {
|
||||
ident: "B".to_owned(),
|
||||
values: vec!["ab".to_owned()]
|
||||
}],
|
||||
next: vec![]
|
||||
}
|
||||
);
|
||||
|
||||
let (_, node) =
|
||||
parse_node::<nom::error::VerboseError<&str>>(";B[ab];W[dp];B[pq]C[some comments]")
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
node,
|
||||
Node {
|
||||
properties: vec![Property {
|
||||
ident: "B".to_owned(),
|
||||
values: vec!["ab".to_owned()]
|
||||
}],
|
||||
next: vec![Node {
|
||||
properties: vec![Property {
|
||||
ident: "W".to_owned(),
|
||||
values: vec!["dp".to_owned()]
|
||||
}],
|
||||
next: vec![Node {
|
||||
properties: vec![
|
||||
Property {
|
||||
ident: "B".to_owned(),
|
||||
values: vec!["pq".to_owned()]
|
||||
},
|
||||
Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["some comments".to_owned()]
|
||||
}
|
||||
],
|
||||
next: vec![],
|
||||
}]
|
||||
}]
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_can_parse_a_simple_sequence() {
|
||||
let (_, sequence) =
|
||||
parse_tree::<nom::error::VerboseError<&str>>("(;B[ab];W[dp];B[pq]C[some comments])")
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
sequence,
|
||||
Node {
|
||||
properties: vec![Property {
|
||||
ident: "B".to_owned(),
|
||||
values: vec!["ab".to_owned()]
|
||||
}],
|
||||
next: vec![Node {
|
||||
properties: vec![Property {
|
||||
ident: "W".to_owned(),
|
||||
values: vec!["dp".to_owned()]
|
||||
}],
|
||||
next: vec![Node {
|
||||
properties: vec![
|
||||
Property {
|
||||
ident: "B".to_owned(),
|
||||
values: vec!["pq".to_owned()]
|
||||
},
|
||||
Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["some comments".to_owned()]
|
||||
}
|
||||
],
|
||||
next: vec![],
|
||||
}]
|
||||
}],
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_can_parse_a_branching_sequence() {
|
||||
let text = "(;C[a];C[b](;C[c])(;C[d];C[e]))";
|
||||
let (_, tree) = parse_tree::<nom::error::VerboseError<&str>>(text).unwrap();
|
||||
|
||||
let expected = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["a".to_owned()],
|
||||
}],
|
||||
next: vec![Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["b".to_owned()],
|
||||
}],
|
||||
next: vec![
|
||||
Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["c".to_owned()],
|
||||
}],
|
||||
next: vec![],
|
||||
},
|
||||
Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["d".to_owned()],
|
||||
}],
|
||||
next: vec![Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["e".to_owned()],
|
||||
}],
|
||||
next: vec![],
|
||||
}],
|
||||
},
|
||||
],
|
||||
}],
|
||||
};
|
||||
|
||||
assert_eq!(tree, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_can_parse_example_1() {
|
||||
let (_, tree) = parse_tree::<nom::error::VerboseError<&str>>(EXAMPLE).unwrap();
|
||||
|
||||
let j = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["j".to_owned()],
|
||||
}],
|
||||
next: vec![],
|
||||
};
|
||||
let i = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["i".to_owned()],
|
||||
}],
|
||||
next: vec![],
|
||||
};
|
||||
let h = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["h".to_owned()],
|
||||
}],
|
||||
next: vec![i],
|
||||
};
|
||||
let g = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["g".to_owned()],
|
||||
}],
|
||||
next: vec![h],
|
||||
};
|
||||
let f = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["f".to_owned()],
|
||||
}],
|
||||
next: vec![g, j],
|
||||
};
|
||||
let e = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["e".to_owned()],
|
||||
}],
|
||||
next: vec![],
|
||||
};
|
||||
let d = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["d".to_owned()],
|
||||
}],
|
||||
next: vec![e],
|
||||
};
|
||||
let c = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["c".to_owned()],
|
||||
}],
|
||||
next: vec![],
|
||||
};
|
||||
let b = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["b".to_owned()],
|
||||
}],
|
||||
next: vec![c, d],
|
||||
};
|
||||
let a = Node {
|
||||
properties: vec![Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["a".to_owned()],
|
||||
}],
|
||||
next: vec![b],
|
||||
};
|
||||
let expected = Node {
|
||||
properties: vec![
|
||||
Property {
|
||||
ident: "FF".to_owned(),
|
||||
values: vec!["4".to_owned()],
|
||||
},
|
||||
Property {
|
||||
ident: "C".to_owned(),
|
||||
values: vec!["root".to_owned()],
|
||||
},
|
||||
],
|
||||
next: vec![a, f],
|
||||
};
|
||||
|
||||
assert_eq!(tree, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_can_regenerate_the_tree() {
|
||||
let (_, tree1) = parse_tree::<nom::error::VerboseError<&str>>(EXAMPLE).unwrap();
|
||||
let tree1 = Tree { root: tree1 };
|
||||
assert_eq!(
|
||||
tree1.to_string(),
|
||||
"(;FF[4]C[root](;C[a];C[b](;C[c])(;C[d];C[e]))(;C[f](;C[g];C[h];C[i])(;C[j])))"
|
||||
);
|
||||
let (_, tree2) = parse_tree::<nom::error::VerboseError<&str>>(&tree1.to_string()).unwrap();
|
||||
assert_eq!(tree1, Tree { root: tree2 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_parses_propvals() {
|
||||
let (_, propval) = parse_propval::<nom::error::VerboseError<&str>>("[]").unwrap();
|
||||
assert_eq!(propval, "".to_owned());
|
||||
|
||||
let (_, propval) =
|
||||
parse_propval::<nom::error::VerboseError<&str>>("[normal propval]").unwrap();
|
||||
assert_eq!(propval, "normal propval".to_owned());
|
||||
|
||||
let (_, propval) =
|
||||
parse_propval::<nom::error::VerboseError<&str>>(r"[need an [escape\] in the propval]")
|
||||
.unwrap();
|
||||
assert_eq!(propval, "need an [escape] in the propval".to_owned());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_parses_propvals_with_hard_linebreaks() {
|
||||
let (_, propval) = parse_propval_text::<nom::error::VerboseError<&str>>(
|
||||
"There are hard linebreaks & soft linebreaks.
|
||||
Soft linebreaks...",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
propval,
|
||||
Some(
|
||||
"There are hard linebreaks & soft linebreaks.
|
||||
Soft linebreaks..."
|
||||
.to_owned()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_parses_propvals_with_escaped_closing_brackets() {
|
||||
let (_, propval) =
|
||||
parse_propval_text::<nom::error::VerboseError<&str>>(r"escaped closing \] bracket")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
propval,
|
||||
Some(r"escaped closing ] bracket".to_owned()).to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_parses_propvals_with_soft_linebreaks() {
|
||||
let (_, propval) = parse_propval_text::<nom::error::VerboseError<&str>>(
|
||||
r"Soft linebreaks are linebreaks preceeded by '\\' like this one >o\
|
||||
k<. Hard line breaks are all other linebreaks.",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
propval,
|
||||
Some("Soft linebreaks are linebreaks preceeded by '\\' like this one >ok<. Hard line breaks are all other linebreaks.".to_owned())
|
||||
.to_owned()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_parses_sgf_with_newline_in_sequence() {
|
||||
let data = String::from(
|
||||
"(;FF[4]C[root](;C[a];C[b](;C[c])(;C[d];C[e]
|
||||
))(;C[f](;C[g];C[h];C[i])(;C[j])))",
|
||||
);
|
||||
parse_tree::<nom::error::VerboseError<&str>>(&data).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_parses_sgf_with_newline_between_two_sequence_closings() {
|
||||
let data = String::from(
|
||||
"(;FF[4]C[root](;C[a];C[b](;C[c])(;C[d];C[e])
|
||||
)(;C[f](;C[g];C[h];C[i])(;C[j])))",
|
||||
);
|
||||
parse_tree::<nom::error::VerboseError<&str>>(&data).unwrap();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
InvalidField,
|
||||
InvalidBoardSize,
|
||||
Incomplete,
|
||||
InvalidSgf(VerboseNomError),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct VerboseNomError(nom::error::VerboseError<String>);
|
||||
|
||||
impl From<nom::error::VerboseError<&str>> for VerboseNomError {
|
||||
fn from(err: nom::error::VerboseError<&str>) -> Self {
|
||||
VerboseNomError(nom::error::VerboseError {
|
||||
errors: err
|
||||
.errors
|
||||
.into_iter()
|
||||
.map(|err| (err.0.to_owned(), err.1))
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<nom::Err<nom::error::VerboseError<&str>>> for Error {
|
||||
fn from(err: nom::Err<nom::error::VerboseError<&str>>) -> Self {
|
||||
match err {
|
||||
nom::Err::Incomplete(_) => Error::Incomplete,
|
||||
nom::Err::Error(e) => Error::InvalidSgf(VerboseNomError::from(e)),
|
||||
nom::Err::Failure(e) => Error::InvalidSgf(VerboseNomError::from(e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Error)]
|
||||
pub enum ParseError {
|
||||
#[error("An unknown error was found")]
|
||||
NomError(nom::error::Error<String>),
|
||||
}
|
||||
|
||||
impl From<nom::error::Error<&str>> for ParseError {
|
||||
fn from(err: nom::error::Error<&str>) -> Self {
|
||||
Self::NomError(nom::error::Error {
|
||||
input: err.input.to_owned(),
|
||||
code: err.code.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Color {
|
||||
Black,
|
||||
White,
|
||||
}
|
||||
|
||||
impl Color {
|
||||
pub fn abbreviation(&self) -> String {
|
||||
match self {
|
||||
Color::White => "W",
|
||||
Color::Black => "B",
|
||||
}
|
||||
.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GameResult {
|
||||
Draw,
|
||||
Black(Win),
|
||||
White(Win),
|
||||
Void,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for GameResult {
|
||||
type Error = String;
|
||||
fn try_from(s: &str) -> Result<GameResult, Self::Error> {
|
||||
if s == "0" {
|
||||
Ok(GameResult::Draw)
|
||||
} else if s == "Void" {
|
||||
Ok(GameResult::Void)
|
||||
} else {
|
||||
let parts = s.split("+").collect::<Vec<&str>>();
|
||||
let res = match parts[0].to_ascii_lowercase().as_str() {
|
||||
"b" => GameResult::Black,
|
||||
"w" => GameResult::White,
|
||||
_ => return Ok(GameResult::Unknown),
|
||||
};
|
||||
match parts[1].to_ascii_lowercase().as_str() {
|
||||
"r" | "resign" => Ok(res(Win::Resignation)),
|
||||
"t" | "time" => Ok(res(Win::Time)),
|
||||
"f" | "forfeit" => Ok(res(Win::Forfeit)),
|
||||
_ => {
|
||||
let score = parts[1].parse::<f32>().unwrap();
|
||||
Ok(res(Win::Score(score)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Win {
|
||||
Score(f32),
|
||||
Resignation,
|
||||
Forfeit,
|
||||
Time,
|
||||
Unknown,
|
||||
}
|
Loading…
Reference in New Issue