Skip to content

Instantly share code, notes, and snippets.

@MollsReis
Created April 22, 2014 07:37
Show Gist options
  • Save MollsReis/11168788 to your computer and use it in GitHub Desktop.
Save MollsReis/11168788 to your computer and use it in GitHub Desktop.
An example grammar/parser using the Ruby gem Treetop
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