Skip to content

Instantly share code, notes, and snippets.

@gnab
Created January 14, 2011 13:37
Show Gist options
  • Save gnab/779609 to your computer and use it in GitHub Desktop.
Save gnab/779609 to your computer and use it in GitHub Desktop.
Parslet test
require 'parslet'
class SimpleExpressionParser < Parslet::Parser
rule(:space) { match['\s'].repeat(1) }
rule(:space?) { space.maybe }
rule(:integer) { match('\d').repeat(1).as(:int) >> space? }
rule(:identifier) { match('\w').repeat(1).as(:id) >> space? }
rule(:lparan) { str('(') >> space? }
rule(:rparan) { str(')') >> space? }
rule(:addsub) { match['+-'].as(:op) >> space? }
rule(:muldiv) { match['*/'].as(:op) >> space? }
rule(:value) { integer | identifier | lparan >> expression >> rparan }
rule(:term) { value.as(:left) >> muldiv >> term.as(:right) | value }
rule(:expression) { term.as(:left) >> addsub >> expression.as(:right) | term }
rule(:statement) { expression }
rule(:input) { space? >> statement.repeat(0) }
root(:input)
end
puts SimpleExpressionParser.new.parse(' a * (b + 2) - 5')
# {:left=>{:left=>{:id=>"a"}, :op=>"*", :right=>{:left=>{:id=>"b"}, :op=>"+", :right=>{:int=>"2"}}}, :op=>"-", :right=>{:int=>"5"}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment