module Game.Goatee.Sgf.Parser (
parseString,
parseFile,
) where
import Control.Applicative ((<*), (*>))
import Data.Maybe (fromMaybe)
import Game.Goatee.Common
import Game.Goatee.Sgf.Property
import Game.Goatee.Sgf.Tree
import Game.Goatee.Sgf.Types
import Text.ParserCombinators.Parsec (
(<?>), Parser, char, eof, many, many1, parse, spaces, upper,
)
parseString :: String -> Either String Collection
parseString str = case parse collection "<collection>" str of
Left err -> Left $ show err
Right (Collection roots) -> onLeft concatErrors $
onRight Collection $
andEithers $
map processRoot roots
where processRoot :: Node -> Either String Node
processRoot = checkFormatVersion . ttToPass
checkFormatVersion :: Node -> Either String Node
checkFormatVersion root =
let version = case findProperty propertyFF root of
Nothing -> defaultFormatVersion
Just (FF x) -> x
x -> error $ "Expected FF or nothing, received " ++ show x ++ "."
in if version `elem` supportedFormatVersions
then Right root
else Left $
"Unsupported SGF version " ++ show version ++ ". Only versions " ++
show supportedFormatVersions ++ " are supported."
ttToPass :: Node -> Node
ttToPass root =
let SZ width height = fromMaybe (SZ boardSizeDefault boardSizeDefault) $
findProperty propertySZ root
in if width <= 19 && height <= 19
then ttToPass' width height root
else root
ttToPass' width height node =
node { nodeProperties = map ttToPass'' $ nodeProperties node
, nodeChildren = map (ttToPass' width height) $ nodeChildren node
}
ttToPass'' prop = case prop of
B (Just (19, 19)) -> B Nothing
W (Just (19, 19)) -> W Nothing
_ -> prop
concatErrors errs = "The following errors occurred while parsing:" ++
concatMap ("\n-> " ++) errs
parseFile :: String -> IO (Either String Collection)
parseFile = fmap parseString . readFile
collection :: Parser Collection
collection = fmap Collection (spaces *> many (gameTree <* spaces) <* eof)
<?> "collection"
gameTree :: Parser Node
gameTree = do
char '('
nodes <- spaces *> many1 (node <* spaces) <?> "sequence"
subtrees <- many (gameTree <* spaces) <?> "subtrees"
char ')'
let (sequence, [final]) = splitAt (length nodes 1) nodes
return $ foldr (\seqNode childNode -> seqNode { nodeChildren = [childNode] })
(final { nodeChildren = subtrees })
sequence
node :: Parser Node
node = fmap (\props -> emptyNode { nodeProperties = props })
(char ';' *> spaces *> many (property <* spaces)
<?> "node")
property :: Parser Property
property = do
name <- many1 upper
spaces
propertyValueParser $ descriptorForName name