Parser wrażliwy na wcięcia z użyciem Parsleta w Ruby?
Próbuję przeanalizować prostą składnię wrażliwą na wcięcia za pomocąParslet biblioteka w Ruby.
Poniżej przedstawiono przykład składni, którą próbuję przeanalizować:
level0child0
level0child1
level1child0
level1child1
level2child0
level1child2
Powstałe drzewo wygląda tak:
[
{
:identifier => "level0child0",
:children => []
},
{
:identifier => "level0child1",
:children => [
{
:identifier => "level1child0",
:children => []
},
{
:identifier => "level1child1",
:children => [
{
:identifier => "level2child0",
:children => []
}
]
},
{
:identifier => "level1child2",
:children => []
},
]
}
]
Analizator składni, który mam teraz, może analizować węzły zagnieżdżenia poziomu 0 i 1, ale nie może analizować przeszłości:
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
Jasne jest, że potrzebuję dynamicznego licznika, który oczekuje, że 3 węzły wcięcia będą pasować do identyfikatora na poziomie zagnieżdżenia 3.
Jak mogę w ten sposób zaimplementować parser składni wrażliwy na wcięcia używając Parsleta? Czy to możliwe?