Class: Obtuse::Evaluator

Inherits:
Object
  • Object
show all
Defined in:
lib/obtuse/evaluator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeEvaluator

Returns a new instance of Evaluator.



5
6
7
8
9
# File 'lib/obtuse/evaluator.rb', line 5

def initialize
  @stack     = []
  @parser    = Parser.new
  @transform = Transform.new
end

Instance Attribute Details

#stackObject (readonly)

Returns the value of attribute stack.



3
4
5
# File 'lib/obtuse/evaluator.rb', line 3

def stack
  @stack
end

Instance Method Details

#eval(input) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/obtuse/evaluator.rb', line 11

def eval(input)
  @transform.apply(@parser.parse(input)).each do |atom|
    case atom
    when Integer, String
      push atom
    when :+, :-, :*, :/, :%, :^
      atom = :** if atom == :^
      y, x = pop, pop
      if Integer === x && Integer === y ||
        String === x && String === y
        push x.send(atom, y)
      else
      end
    end
  end
end

#peekObject



36
37
38
# File 'lib/obtuse/evaluator.rb', line 36

def peek
  @stack.last
end

#popObject



32
33
34
# File 'lib/obtuse/evaluator.rb', line 32

def pop
  @stack.pop
end

#push(object) ⇒ Object



28
29
30
# File 'lib/obtuse/evaluator.rb', line 28

def push(object)
  @stack << object
end