title: Treetop SGF Parsing
body: <p>I am currently trying to write a Treetop grammar to parse Simple Game Format files, and have it mostly working so far.  However, there are a few questions that have come up.</p>
  
  <ol>
  <li>I am unsure how to actually access the structure Treetop generates after a parse.</li>
  <li>Is there a better way to handle capturing all characters than my chars rule?</li>
  <li><p>There is a case for comments that I can't seem to write correctly.</p>
  
  <p>C[player1 [4k\]: hi player2 [3k\]: hi!]</p></li>
  </ol>
  
  <p>I can't wrap my head around how to deal with the nested structure of the C[] node with []'s inside them.</p>
  
  <p>The following is my current progress.</p>
  
  <p><strong>sgf-grammar.treetop</strong></p>
  
  <pre><code>grammar SgfGrammar
  rule node
      '(' chunk* ')' {
          def value
              text_value
          end
      }
  end
  
  rule chunk
      ';' property_set* {
          def value
              text_value
          end
      }
  end
  
  rule property_set
      property ('[' property_data ']')* / property '[' property_data ']' {
          def value
              text_value
          end
      }
  end
  
  rule property_data
      chars '[' (!'\]' . )* '\]' chars / chars / empty {
          def value
              text_value
          end
      }
  end
  
  rule property
      [A-Z]+ / [A-Z] {
          def value
              text_value
          end
      }
  end
  
  rule chars
      [a-zA-Z0-9_/\-:;|'"\\&lt;&gt;(){}!@#$%^&amp;\*\+\-,\.\?!= \r\n\t]*
  end
  
  rule empty
      ''
  end
  end
  </code></pre>
  
  <p>And my test case, currently excluding C[] nodes with the above mentioned nested bracket problem:</p>
  
  <p><strong>example.rb</strong></p>
  
  <pre><code>require 'rubygems'
  require 'treetop'
  require 'sgf-grammar'
  
  parser = SgfGrammarParser.new
  parser.parse("(;GM[1]FF[4]CA[UTF-8]AP[CGoban:3]ST[2]
  RU[Japanese]SZ[19]KM[0.50]TM[1800]OT[5x30 byo-yomi]
  PW[stoic]PB[bojo]WR[3k]BR[4k]DT[2008-11-30]RE[B+2.50])")
  </code></pre>