jbarnette (owner)

Revisions

  • f89c76 Sun Feb 08 23:05:08 -0800 2009
gist: 60694 Download_button fork
public
Public Clone URL: git://gist.github.com/60694.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
      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