我試圖在Ruby中使用Parslet庫解析簡單的縮進敏感語法。在Ruby中使用Parslet的縮進敏感解析器?
以下是我試圖解析語法的例子:
level0child0
level0child1
level1child0
level1child1
level2child0
level1child2
結果樹看起來就像這樣:
[
{
:identifier => "level0child0",
:children => []
},
{
:identifier => "level0child1",
:children => [
{
:identifier => "level1child0",
:children => []
},
{
:identifier => "level1child1",
:children => [
{
:identifier => "level2child0",
:children => []
}
]
},
{
:identifier => "level1child2",
:children => []
},
]
}
]
,我現在已經可以解析嵌套層次解析器0和1個節點,但不能解析過去那個:
require 'parslet'
class IndentationSensitiveParser < Parslet::Parser
rule(:indent) { str(' ') }
rule(:newline) { str("\n") }
rule(:identifier) { match['A-Za-z0-9'].repeat.as(:identifier) }
rule(:node) { identifier >> newline >> (indent >> identifier >> newline.maybe).repeat.as(:children) }
rule(:document) { node.repeat }
root :document
end
require 'ap'
require 'pp'
begin
input = DATA.read
puts '', '----- input ----------------------------------------------------------------------', ''
ap input
tree = IndentationSensitiveParser.new.parse(input)
puts '', '----- tree -----------------------------------------------------------------------', ''
ap tree
rescue IndentationSensitiveParser::ParseFailed => failure
puts '', '----- error ----------------------------------------------------------------------', ''
puts failure.cause.ascii_tree
end
__END__
user
name
age
recipe
name
foo
bar
很明顯,我需要一個dynami c計數器,期望3個縮進節點匹配嵌套級別3上的標識符。
如何以這種方式使用Parslet實現縮進敏感語法分析器?可能嗎?
不知道這是做更好的解析/建立獨立的階段。幾乎任何縮進級別的組合都是有效的和解析的,所以對我來說,這指向一個非常簡單的基於行的解析器,它只是捕獲縮進級別,然後是解析器輸出並構建嵌套結構的東西。 – 2013-05-12 07:56:14