Avatar of hamberge

hamberge's solution

to SGF Parsing in the C# Track

Published at Jul 31 2019 · 0 comments
Instructions
Test suite
Solution

Parsing a Smart Game Format string.

SGF is a standard format for storing board game files, in particular go.

SGF is a fairly simple format. An SGF file usually contains a single tree of nodes where each node is a property list. The property list contains key value pairs, each key can only occur once but may have multiple values.

An SGF file may look like this:

(;FF[4]C[root]SZ[19];B[aa];W[ab])

This is a tree with three nodes:

  • The top level node has three properties: FF[4] (key = "FF", value = "4"), C[root](key = "C", value = "root") and SZ[19] (key = "SZ", value = "19"). (FF indicates the version of SGF, C is a comment and SZ is the size of the board.)
    • The top level node has a single child which has a single property: B[aa]. (Black plays on the point encoded as "aa", which is the 1-1 point (which is a stupid place to play)).
      • The B[aa] node has a single child which has a single property: W[ab].

As you can imagine an SGF file contains a lot of nodes with a single child, which is why there's a shorthand for it.

SGF can encode variations of play. Go players do a lot of backtracking in their reviews (let's try this, doesn't work, let's try that) and SGF supports variations of play sequences. For example:

(;FF[4](;B[aa];W[ab])(;B[dd];W[ee]))

Here the root node has two variations. The first (which by convention indicates what's actually played) is where black plays on 1-1. Black was sent this file by his teacher who pointed out a more sensible play in the second child of the root node: B[dd] (4-4 point, a very standard opening to take the corner).

A key can have multiple values associated with it. For example:

(;FF[4];AB[aa][ab][ba])

Here AB (add black) is used to add three black stones to the board.

There are a few more complexities to SGF (and parsing in general), which you can mostly ignore. You should assume that the input is encoded in UTF-8, the tests won't contain a charset property, so don't worry about that. Furthermore you may assume that all newlines are unix style (\n, no \r or \r\n will be in the tests) and that no optional whitespace between properties, nodes, etc will be in the tests.

The exercise will have you parse an SGF string and return a tree structure of properties. You do not need to encode knowledge about the data types of properties, just use the rules for the text type everywhere.

Hints

  • To parse the text, you could try to use the Sprache library. You can also find a good tutorial here.

Running the tests

To run the tests, run the command dotnet test from within the exercise directory.

Initially, only the first test will be enabled. This is to encourage you to solve the exercise one step at a time. Once you get the first test passing, remove the Skip property from the next test and work on getting that test passing. Once none of the tests are skipped and they are all passing, you can submit your solution using exercism submit SgfParsing.cs

Further information

For more detailed information about the C# track, including how to get help if you're having trouble, please visit the exercism.io C# language page.

SgfParsingTest.cs

// This file was auto-generated based on version 1.2.0 of the canonical data.

using System;
using System.Collections.Generic;
using Xunit;

public class SgfParsingTest
{
    [Fact]
    public void Empty_input()
    {
        var encoded = "";
        Assert.Throws<ArgumentException>(() => SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Tree_with_no_nodes()
    {
        var encoded = "()";
        Assert.Throws<ArgumentException>(() => SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Node_without_tree()
    {
        var encoded = ";";
        Assert.Throws<ArgumentException>(() => SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Node_without_properties()
    {
        var encoded = "(;)";
        var expected = new SgfTree(new Dictionary<string, string[]>());
        Assert.Equal(expected, SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Single_node_tree()
    {
        var encoded = "(;A[B])";
        var expected = new SgfTree(new Dictionary<string, string[]> { ["A"] = new[] { "B" } });
        Assert.Equal(expected, SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Multiple_properties()
    {
        var encoded = "(;A[b]C[d])";
        var expected = new SgfTree(new Dictionary<string, string[]> { ["A"] = new[] { "b" }, ["C"] = new[] { "d" } });
        Assert.Equal(expected, SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Properties_without_delimiter()
    {
        var encoded = "(;A)";
        Assert.Throws<ArgumentException>(() => SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void All_lowercase_property()
    {
        var encoded = "(;a[b])";
        Assert.Throws<ArgumentException>(() => SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Upper_and_lowercase_property()
    {
        var encoded = "(;Aa[b])";
        Assert.Throws<ArgumentException>(() => SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Two_nodes()
    {
        var encoded = "(;A[B];B[C])";
        var expected = new SgfTree(new Dictionary<string, string[]> { ["A"] = new[] { "B" } }, new SgfTree(new Dictionary<string, string[]> { ["B"] = new[] { "C" } }));
        Assert.Equal(expected, SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Two_child_trees()
    {
        var encoded = "(;A[B](;B[C])(;C[D]))";
        var expected = new SgfTree(new Dictionary<string, string[]> { ["A"] = new[] { "B" } }, new SgfTree(new Dictionary<string, string[]> { ["B"] = new[] { "C" } }), new SgfTree(new Dictionary<string, string[]> { ["C"] = new[] { "D" } }));
        Assert.Equal(expected, SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Multiple_property_values()
    {
        var encoded = "(;A[b][c][d])";
        var expected = new SgfTree(new Dictionary<string, string[]> { ["A"] = new[] { "b", "c", "d" } });
        Assert.Equal(expected, SgfParser.ParseTree(encoded));
    }

    [Fact(Skip = "Remove to run test")]
    public void Escaped_property()
    {
        var encoded = "(;A[\\]b\\nc\\nd\\t\\te \\n\\]])";
        var expected = new SgfTree(new Dictionary<string, string[]> { ["A"] = new[] { "]b\nc\nd  e \n]" } });
        Assert.Equal(expected, SgfParser.ParseTree(encoded));
    }
}
using System;
using System.Collections.Generic;
using Sprache;
using System.Linq;

public class SgfTree
{
    public SgfTree(IDictionary<string, string[]> data, params SgfTree[] children)
    {
        Data = data;
        Children = children;
    }

    public IDictionary<string, string[]> Data { get; }
    public SgfTree[] Children { get; }
}

public static class SgfParser
{
    public static SgfTree ParseTree(string input)
    {
        try
        {
            return SgfTreeParser.Parse(input);
        }
        catch (Sprache.ParseException e)
        {
            throw new ArgumentException($"Invalid input: {e.Message}");
        }
    }

    private class Property
    {
        public Property(string name, string[] values)
        {
            Name = name;
            Values = values;
        }

        public string Name { get; }
        public string[] Values { get; }
    }

    private static readonly Parser<string> PropertyNameParser = //e.g., A
        from name in Parse.Upper.AtLeastOnce().Text()
        select name;

    private static readonly Parser<char> ValueCharParser = //any char, taking escape characters into consideration
        Parse.String("\\]").Return(']')
        .Or(Parse.String("\\n").Return('\n'))
        .Or(Parse.String("\\t").Return(' '))
        .Or(Parse.AnyChar);
            
    private static readonly Parser<string> PropertyValueParser = //e.g., [aa]
        from open in Parse.Char('[')
        from content in ValueCharParser.Except(Parse.Char(']')).AtLeastOnce().Text()
        from close in Parse.Char(']')
        select content;

    private static readonly Parser<Property> PropertyParser = //e.g., A[aa][bb]
        from name in PropertyNameParser
        from propertyValues in PropertyValueParser.AtLeastOnce()
        select new Property(name, propertyValues.ToArray());

    private static readonly Parser<Dictionary<string, string[]>> NodeDataParser = //e.g., full node, including multiple properties - ;A[b][c]C[d]
        from open in Parse.Char(';')
        from properties in PropertyParser.Many()
        select properties.ToDictionary(p => p.Name, p => p.Values); 

    private static readonly Parser<SgfTree> SingleNodeParser = //if a node occurs without parens
        from node in NodeDataParser
        select new SgfTree(node);

    private static readonly Parser<SgfTree> NodeChainParser = //chain node parsers -- first node data then parse next node(s) as children
        from node in NodeDataParser
        from trees in SingleNodeParser.Once().Or(SgfTreeParser.Many())
        select new SgfTree(node, trees.ToArray());

    private static Parser<SgfTree> SgfTreeParser = //full tree parser, doubles as a parser for when there are multiple nodes at the same tree level
        from open in Parse.Char('(')
        from sgfTree in NodeChainParser
        from close in Parse.Char(')')
        select sgfTree;

}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?