Created
April 29, 2010 22:22
-
-
Save anonymous/384362 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module SgfParser | |
class Tree | |
private | |
def parse | |
while char = next_character | |
case char | |
when '(' then store_branch | |
when ')' then fetch_branch | |
when ';' then advance_node | |
when '[' then get_and_store_property | |
else store_character(char) | |
end | |
end | |
end | |
def current_node | |
@current_node ||= @root | |
end | |
def content | |
@content ||= {} | |
end | |
def identity | |
@identify ||= "" | |
end | |
def advance_node | |
parent = current_node | |
@current_node = Node.new :parent => parent | |
parent.add_properties content | |
parent.add_children @current_node | |
clear_temporary_data | |
end | |
def store_branch | |
@branches ||= [] | |
@branches.unshift @current_node | |
end | |
def fetch_branch | |
@current_node = @branches.shift | |
clear_temporary_data | |
end | |
def get_and_store_property | |
@content[@identity] ||= "" | |
@content[@identity] << get_property | |
@identity = "" | |
end | |
def get_property | |
buffer = "" | |
while true | |
parsed_bit = @stream.sysread(1) | |
break if parsed_bit == "]" | |
parsed_bit << @stream.sysread(1) if parsed_bit == "\\" | |
parsed_bit = "]" if parsed_bit == "\\]" | |
buffer << parsed_bit | |
end | |
buffer | |
end | |
def clear_temporary_data | |
@content.clear | |
@identity = "" | |
end | |
def clean_string | |
@sgf.gsub! "\\\\n\\\\r", "" | |
@sgf.gsub! "\\\\r\\\\n", "" | |
@sgf.gsub! "\\\\r", "" | |
@sgf.gsub! "\\\\n", "" | |
#@sgf.gsub! "\n", "" | |
@sgf | |
end | |
def character_available? | |
@stream ||= StringIO.new(clean_string, 'r') | |
!@stream.eof? | |
end | |
def next_character | |
character_available? && @stream.sysread(1) | |
end | |
def store_character(char) | |
@identity << char unless char == "\n" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment