2009-02-28 18 views
3

我目前正在嘗試編寫一個Treetop語法來解析簡單遊戲格式文件,並且目前它的工作大部分都在進行中。但是,有幾個問題出現了。Treetop SGF解析

  1. 我不確定如何實際訪問Treetop在解析後生成的結構。
  2. 有沒有更好的方式來處理捕捉所有字符比我的字符規則?
  3. 有一種情況是我似乎無法正確寫入。

    C [PLAYER1 [4K \]:您好player2 [3K \]:嗨]

我不能換我周圍的頭如何處理C []節點的嵌套結構與[]在裏面。

以下是我目前的進展情況。

SGF-grammar.treetop

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_/\-:;|'"\\<>(){}[email protected]#$%^&\*\+\-,\.\?!= \r\n\t]* 
end 

rule empty 
    '' 
end 
end 

而我的測試的情況下,目前不包括C []具有上述嵌套支架問題節點:

example.rb

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])") 
+0

任何人在近一年後閱讀這篇文章的結果是:http://github.com/boj/kantan-sgf - 不是世界上最有效的東西,但是是一個很棒的TreeTop/SGF解析實驗。 – bojo 2010-03-04 03:10:11

回答

3
  1. 結構來作爲SyntaxNodes的樹返回給您(如果結果爲零,請檢查parser.failure_reason)。你可以走這個樹,或者(建議這樣做),你可以使用你想要的功能來擴充它,只需要在根上調用你的主函數。

如果你的意思是「你如何從節點函數中訪問組件?」有幾種方法。你可以在他們獲得與元素[X]符號或規則:

rule url_prefix 
    protocol "://" host_name { 
     def example 
      assert element[0] == protocol 
      assert element[2] == host_name 
      unless protocol.text_value == "http" 
       print "#{protocol.text_value} not supported" 
       end 
      end 
     } 

您也可以命名它們像這樣:

rule phone_number 
    "(" area_code:(digit digit digit) ")" ... 

,然後按名稱指代他們。

  1. 如果你只想匹配那些字符,你的字符規則看起來很好。如果你想匹配任何字符,你可以像使用正則表達式一樣使用點(。)。

  2. 我不熟悉與您試圖解析語言,但你正在尋找的規則可能是這樣的:

rule comment 
    "C" balanced_square_bracket_string 
    end 
rule balanced_square_bracket_string 
    "[" ([^\[\]]/balanced_square_bracket_string)* "]" 
    end 

的中間部分第二條規則將任何不是方括號或嵌套字符串的任何內容與均衡方括號進行匹配。

P.S.有一個相當活躍的Google group,檔案在線&可搜索。

+0

感謝MarkusQ的提示。我要繼續圍繞這個方向,但是你讓我朝着正確的方向前進。 – bojo 2009-02-28 03:21:51