Compare commits

..

No commits in common. "4b30bf288ad228f4edf7434dc06ee3d510b6e9f2" and "90b0f830e07b45d65c98d818f288424a59100787" have entirely different histories.

5 changed files with 34 additions and 160 deletions

View File

@ -1,4 +1,3 @@
// https://red-bean.com/sgf/
// https://red-bean.com/sgf/user_guide/index.html // https://red-bean.com/sgf/user_guide/index.html
// https://red-bean.com/sgf/sgf4.html // https://red-bean.com/sgf/sgf4.html
@ -95,45 +94,23 @@ impl<'a> From<ParseSizeError> for Error<'a> {
} }
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Debug)]
pub enum Rank {
Kyu(u8),
Dan(u8),
Pro(u8),
}
impl TryFrom<&str> for Rank {
type Error = String;
fn try_from(r: &str) -> Result<Rank, Self::Error> {
let parts = r.split(" ").map(|s| s.to_owned()).collect::<Vec<String>>();
let cnt = parts[0].parse::<u8>().map_err(|err| format!("{:?}", err))?;
match parts[1].to_ascii_lowercase().as_str() {
"kyu" => Ok(Rank::Kyu(cnt)),
"dan" => Ok(Rank::Dan(cnt)),
"pro" => Ok(Rank::Pro(cnt)),
_ => Err("unparsable".to_owned()),
}
}
}
#[derive(Clone, Debug)]
pub struct GameTree { pub struct GameTree {
pub file_format: i8, pub file_format: i8,
pub app_name: Option<String>, pub app: Option<String>,
pub game_type: GameType, pub game_type: GameType,
pub board_size: Size, pub board_size: Size,
pub info: GameInfo,
// pub text: String, pub text: String,
} }
#[derive(Clone, Debug, Default)]
pub struct GameInfo { pub struct GameInfo {
pub annotator: Option<String>, pub annotator: Option<String>,
pub copyright: Option<String>, pub copyright: Option<String>,
pub event: Option<String>, pub event: Option<String>,
// Games can be played across multiple days, even multiple years. The format specifies // Games can be played across multiple days, even multiple years. The format specifies
// shortcuts. // shortcuts.
pub date: Vec<chrono::NaiveDate>, pub date_time: Vec<chrono::NaiveDate>,
pub location: Option<String>, pub location: Option<String>,
// special rules for the round-number and type // special rules for the round-number and type
pub round: Option<String>, pub round: Option<String>,
@ -141,17 +118,16 @@ pub struct GameInfo {
pub source: Option<String>, pub source: Option<String>,
pub time_limits: Option<std::time::Duration>, pub time_limits: Option<std::time::Duration>,
pub game_keeper: Option<String>, pub game_keeper: Option<String>,
pub komi: Option<f32>,
pub game_name: Option<String>, pub game_name: Option<String>,
pub game_comments: Option<String>, pub game_comments: Option<String>,
pub black_player: Option<String>, pub black_player: Option<String>,
pub black_rank: Option<Rank>, pub black_rank: Option<String>,
pub black_team: Option<String>, pub black_team: Option<String>,
pub white_player: Option<String>, pub white_player: Option<String>,
pub white_rank: Option<Rank>, pub white_rank: Option<String>,
pub white_team: Option<String>, pub white_team: Option<String>,
pub opening: Option<String>, pub opening: Option<String>,
@ -159,7 +135,6 @@ pub struct GameInfo {
pub result: Option<GameResult>, pub result: Option<GameResult>,
} }
#[derive(Clone, Debug, PartialEq)]
pub enum GameResult { pub enum GameResult {
Annulled, Annulled,
Draw, Draw,
@ -167,43 +142,14 @@ pub enum GameResult {
White(Win), White(Win),
} }
impl TryFrom<&str> for GameResult {
type Error = String;
fn try_from(s: &str) -> Result<GameResult, Self::Error> {
println!("Result try_from: {:?}", s);
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,
_ => panic!("unknown result format"),
};
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 { pub enum Win {
Score(f32), Score(i32),
Resignation, Resignation,
Forfeit, Forfeit,
Time, Time,
} }
#[derive(Clone, Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum GameType { pub enum GameType {
Go, Go,
Unsupported, Unsupported,
@ -239,7 +185,7 @@ pub fn parse_sgf<'a>(input: &'a str) -> Result<Vec<GameTree>, Error<'a>> {
Some(prop) => prop.values[0].parse::<i8>().unwrap(), Some(prop) => prop.values[0].parse::<i8>().unwrap(),
None => 4, None => 4,
}; };
let app_name = tree.sequence[0] let app = tree.sequence[0]
.find_prop("AP") .find_prop("AP")
.map(|prop| prop.values[0].clone()); .map(|prop| prop.values[0].clone());
let board_size = match tree.sequence[0].find_prop("SZ") { let board_size = match tree.sequence[0].find_prop("SZ") {
@ -249,38 +195,14 @@ pub fn parse_sgf<'a>(input: &'a str) -> Result<Vec<GameTree>, Error<'a>> {
height: 19, height: 19,
}, },
}; };
let mut info = GameInfo::default();
info.black_player = tree.sequence[0]
.find_prop("PB")
.map(|prop| prop.values.join(", "));
info.black_rank = tree.sequence[0]
.find_prop("BR")
.and_then(|prop| Rank::try_from(prop.values[0].as_str()).ok());
info.white_player = tree.sequence[0]
.find_prop("PW")
.map(|prop| prop.values.join(", "));
info.white_rank = tree.sequence[0]
.find_prop("WR")
.and_then(|prop| Rank::try_from(prop.values[0].as_str()).ok());
info.result = tree.sequence[0]
.find_prop("RE")
.and_then(|prop| GameResult::try_from(prop.values[0].as_str()).ok());
info.time_limits = tree.sequence[0]
.find_prop("TM")
.and_then(|prop| prop.values[0].parse::<u64>().ok())
.and_then(|seconds| Some(std::time::Duration::from_secs(seconds)));
Ok(GameTree { Ok(GameTree {
file_format, file_format,
app_name,
app,
game_type: GameType::Go, game_type: GameType::Go,
board_size, board_size,
info, text: input.to_owned(),
}) })
}) })
.collect::<Result<Vec<GameTree>, Error>>()?; .collect::<Result<Vec<GameTree>, Error>>()?;
@ -317,7 +239,7 @@ mod tests {
assert_eq!(trees.len(), 1); assert_eq!(trees.len(), 1);
let tree = &trees[0]; let tree = &trees[0];
assert_eq!(tree.file_format, 4); assert_eq!(tree.file_format, 4);
assert_eq!(tree.app_name, None); assert_eq!(tree.app, None);
assert_eq!(tree.game_type, GameType::Go); assert_eq!(tree.game_type, GameType::Go);
assert_eq!( assert_eq!(
tree.board_size, tree.board_size,
@ -333,7 +255,7 @@ mod tests {
assert_eq!(trees.len(), 1); assert_eq!(trees.len(), 1);
let tree = &trees[0]; let tree = &trees[0];
assert_eq!(tree.file_format, 4); assert_eq!(tree.file_format, 4);
assert_eq!(tree.app_name, None); assert_eq!(tree.app, None);
assert_eq!(tree.game_type, GameType::Go); assert_eq!(tree.game_type, GameType::Go);
assert_eq!( assert_eq!(
tree.board_size, tree.board_size,
@ -344,32 +266,4 @@ mod tests {
); );
}); });
} }
#[test]
fn it_parses_game_info() {
with_file(std::path::Path::new("test_data/print1.sgf"), |trees| {
assert_eq!(trees.len(), 1);
let tree = &trees[0];
assert_eq!(tree.info.black_player, Some("Takemiya Masaki".to_owned()));
assert_eq!(tree.info.black_rank, Some(Rank::Dan(9)));
assert_eq!(tree.info.white_player, Some("Cho Chikun".to_owned()));
assert_eq!(tree.info.white_rank, Some(Rank::Dan(9)));
assert_eq!(tree.info.result, Some(GameResult::White(Win::Resignation)));
assert_eq!(
tree.info.time_limits,
Some(std::time::Duration::from_secs(28800))
);
assert_eq!(
tree.info.date,
vec![
chrono::NaiveDate::from_ymd_opt(1996, 10, 18).unwrap(),
chrono::NaiveDate::from_ymd_opt(1996, 10, 19).unwrap(),
]
);
assert_eq!(tree.info.event, Some("21st Meijin".to_owned()));
assert_eq!(tree.info.event, Some("2 (final)".to_owned()));
assert_eq!(tree.info.source, Some("Go World #78".to_owned()));
assert_eq!(tree.info.game_keeper, Some("Arno Hollosi".to_owned()));
});
}
} }

View File

@ -1,3 +1,5 @@
use std::num::ParseIntError;
use nom::{ use nom::{
branch::alt, branch::alt,
bytes::complete::{escaped_transform, tag}, bytes::complete::{escaped_transform, tag},
@ -7,7 +9,6 @@ use nom::{
sequence::delimited, sequence::delimited,
IResult, IResult,
}; };
use std::num::ParseIntError;
#[derive(Debug)] #[derive(Debug)]
pub enum ParseSizeError { pub enum ParseSizeError {
@ -21,7 +22,7 @@ impl From<ParseIntError> for ParseSizeError {
} }
} }
#[derive(Clone, Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub struct Size { pub struct Size {
pub width: i32, pub width: i32,
pub height: i32, pub height: i32,
@ -119,6 +120,7 @@ pub fn parse_collection<'a, E: nom::error::ParseError<&'a str>>(
// note: must fix or preserve illegally formatted game-info properties // note: must fix or preserve illegally formatted game-info properties
// note: must correct or delete illegally foramtted properties, but display a warning // 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, Tree, E> { fn parse_tree<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Tree, E> {
println!("::: parse_tree: {}", input);
let (input, _) = multispace0(input)?; let (input, _) = multispace0(input)?;
delimited(tag("("), parse_sequence, tag(")"))(input) delimited(tag("("), parse_sequence, tag(")"))(input)
} }
@ -126,6 +128,7 @@ fn parse_tree<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult
fn parse_sequence<'a, E: nom::error::ParseError<&'a str>>( fn parse_sequence<'a, E: nom::error::ParseError<&'a str>>(
input: &'a str, input: &'a str,
) -> IResult<&'a str, Tree, E> { ) -> IResult<&'a str, Tree, E> {
println!("::: parse_sequence: {}", input);
let (input, _) = multispace0(input)?; let (input, _) = multispace0(input)?;
let (input, nodes) = many1(parse_node)(input)?; let (input, nodes) = many1(parse_node)(input)?;
let (input, _) = multispace0(input)?; let (input, _) = multispace0(input)?;
@ -142,6 +145,7 @@ fn parse_sequence<'a, E: nom::error::ParseError<&'a str>>(
} }
fn parse_node<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Node, E> { fn parse_node<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Node, E> {
println!("::: parse_node: {}", input);
let (input, _) = multispace0(input)?; let (input, _) = multispace0(input)?;
let (input, _) = tag(";")(input)?; let (input, _) = tag(";")(input)?;
let (input, properties) = many1(parse_property)(input)?; let (input, properties) = many1(parse_property)(input)?;
@ -151,6 +155,7 @@ fn parse_node<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult
fn parse_property<'a, E: nom::error::ParseError<&'a str>>( fn parse_property<'a, E: nom::error::ParseError<&'a str>>(
input: &'a str, input: &'a str,
) -> IResult<&'a str, Property, E> { ) -> IResult<&'a str, Property, E> {
println!(":: parse_property: {}", input);
let (input, _) = multispace0(input)?; let (input, _) = multispace0(input)?;
let (input, ident) = alpha1(input)?; let (input, ident) = alpha1(input)?;
let (input, values) = many1(parse_propval)(input)?; let (input, values) = many1(parse_propval)(input)?;
@ -173,8 +178,14 @@ fn parse_propval<'a, E: nom::error::ParseError<&'a str>>(
input: &'a str, input: &'a str,
) -> IResult<&'a str, String, E> { ) -> IResult<&'a str, String, E> {
let (input, _) = multispace0(input)?; let (input, _) = multispace0(input)?;
println!("- {}", input);
let (input, _) = tag("[")(input)?; let (input, _) = tag("[")(input)?;
println!("-- {}", input);
let (input, value) = parse_propval_text(input)?; let (input, value) = parse_propval_text(input)?;
println!("--- {}", input);
let (input, _) = tag("]")(input)?; let (input, _) = tag("]")(input)?;
Ok((input, value.unwrap_or(String::new()))) Ok((input, value.unwrap_or(String::new())))

17
kifu/core/Cargo.lock generated
View File

@ -60,15 +60,6 @@ dependencies = [
"unicode-width", "unicode-width",
] ]
[[package]]
name = "cool_asserts"
version = "2.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee9f254e53f61e2688d3677fa2cbe4e9b950afd56f48819c98817417cf6b28ec"
dependencies = [
"indent_write",
]
[[package]] [[package]]
name = "core-foundation-sys" name = "core-foundation-sys"
version = "0.8.4" version = "0.8.4"
@ -161,12 +152,6 @@ dependencies = [
"cxx-build", "cxx-build",
] ]
[[package]]
name = "indent_write"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cfe9645a18782869361d9c8732246be7b410ad4e919d3609ebabdac00ba12c3"
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.6" version = "1.0.6"
@ -186,8 +171,6 @@ dependencies = [
name = "kifu-core" name = "kifu-core"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"chrono",
"cool_asserts",
"go-sgf", "go-sgf",
"grid", "grid",
"serde", "serde",

View File

@ -6,13 +6,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
chrono = { version = "0.4" }
go-sgf = { path = "../../go-sgf" } go-sgf = { path = "../../go-sgf" }
grid = { version = "0.9" } grid = { version = "0.9" }
serde_json = { version = "1" } serde_json = { version = "1" }
serde = { version = "1", features = [ "derive" ] } serde = { version = "1", features = [ "derive" ] }
thiserror = { version = "1" } thiserror = { version = "1" }
typeshare = { version = "1" } typeshare = { version = "1" }
[dev-dependencies]
cool_asserts = { version = "2" }

View File

@ -57,7 +57,6 @@ impl Database {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;
use cool_asserts::assert_matches;
#[test] #[test]
fn it_reads_empty_database() { fn it_reads_empty_database() {
@ -74,14 +73,5 @@ mod test {
for game in db.all_games() { for game in db.all_games() {
assert_eq!(game.game_type, GameType::Go); assert_eq!(game.game_type, GameType::Go);
} }
assert_matches!(db.all_games().find(|g| g.info.black_player == Some("Steve".to_owned())),
Some(game) => {
assert_eq!(game.info.black_player, Some("Steve".to_owned()));
assert_eq!(game.info.white_player, Some("Savanni".to_owned()));
assert_eq!(game.info.date, vec![chrono::NaiveDate::from_ymd_opt(2023, 4, 19).unwrap()]);
assert_eq!(game.info.komi, Some(6.5));
}
);
} }
} }