Created
April 22, 2014 07:37
-
-
Save MollsReis/11168788 to your computer and use it in GitHub Desktop.
An example grammar/parser using the Ruby gem Treetop
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
require 'treetop' | |
module Mine | |
class IntegerLiteral < Treetop::Runtime::SyntaxNode | |
def to_i | |
text_value.to_i | |
end | |
end | |
class Expression < Treetop::Runtime::SyntaxNode | |
def value | |
elements.map(&:to_i).reduce(:+) | |
end | |
end | |
class Parser | |
def initialize | |
Treetop.load_from_string(DATA.read) | |
@parser = MineParser.new | |
end | |
def parse(parse_string) | |
tree = @parser.parse(parse_string) | |
raise Exception, @parser.failure_reason if tree.nil? | |
clean_tree!(tree) | |
tree | |
end | |
private | |
def clean_tree!(root_node) | |
return if root_node.elements.nil? | |
root_node.elements.delete_if { |node| node.class.name == "Treetop::Runtime::SyntaxNode" } | |
root_node.elements.each { |node| clean_tree!(node) } | |
end | |
end | |
end | |
tree = Mine::Parser.new.parse('5 + 10') | |
puts tree.inspect; puts tree.value | |
__END__ | |
grammar Mine | |
rule expression | |
integer space? '+' space? integer <Expression> | |
end | |
rule integer | |
[0-9]+ <IntegerLiteral> | |
end | |
rule space | |
[\s]+ | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment