Skip to content

Instantly share code, notes, and snippets.

@jbarnette
Created February 9, 2009 07:05
Show Gist options
  • Select an option

  • Save jbarnette/60694 to your computer and use it in GitHub Desktop.

Select an option

Save jbarnette/60694 to your computer and use it in GitHub Desktop.
class Calculator < Omerta::Grammar
def initialize
@vars = {}
end
rule :space => ' '
rule(:var => "<letter>:x <space>*") { |x| x }
rule :num do
alt("<num>:n <digit>:d") { |d| FIXME! }
alt("<digit>:d <space>*") { |d| FIXME! }
end
rule :pri_expr do
alt("<var>:x") { |x| @vars[x] }
alt("<num>:n") { |n| n }
alt("'(' <space>* <expr>:r ')' <space>*") { |r| r }
end
rule :mul_expr do
alt("<mul_expr>:x '*' <space>* <pri_expr>:y") { |x, y| x * y }
alt("<mul_expr>:x '/' <space>* <pri_expr>:y") { |x, y| x / y }
alt(:pri_expr)
end
rule :add_expr do
alt("<add_expr>:x '+' <space>* <mul_expr>:y") { |x, y| x + y }
alt("<add_expr>:x '-' <space>* <mul_expr>:y") { |x, y| x - y }
alt(:mul_expr)
end
rule :expr do
alt("<var>:x '=' <space>* <expr>:r") { |x, r| @vars[x] = r }
alt(:add_expr)
end
rule(:parse => "<space>* <expr>:r '\n'") { |r| p r }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment