Class: Interpreter

Inherits:
Object
  • Object
show all
Includes:
BigMath, Types
Defined in:
lib/rpl/interpreter.rb

Direct Known Subclasses

Rpl

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Types

new_object

Constructor Details

#initialize(stack = [], dictionary = Rpl::Lang::Dictionary.new) ⇒ Interpreter

Returns a new instance of Interpreter.



20
21
22
23
24
25
# File 'lib/rpl/interpreter.rb', line 20

def initialize( stack = [], dictionary = Rpl::Lang::Dictionary.new )
  @version = 0.7

  @dictionary = dictionary
  @stack = stack
end

Instance Attribute Details

#dictionaryObject (readonly)

Returns the value of attribute dictionary.



14
15
16
# File 'lib/rpl/interpreter.rb', line 14

def dictionary
  @dictionary
end

#precisionObject

Returns the value of attribute precision.



18
19
20
# File 'lib/rpl/interpreter.rb', line 18

def precision
  @precision
end

#stackObject (readonly)

Returns the value of attribute stack.



14
15
16
# File 'lib/rpl/interpreter.rb', line 14

def stack
  @stack
end

#versionObject (readonly)

Returns the value of attribute version.



14
15
16
# File 'lib/rpl/interpreter.rb', line 14

def version
  @version
end

Instance Method Details

#export_stackObject



81
82
83
# File 'lib/rpl/interpreter.rb', line 81

def export_stack
  @stack.map(&:to_s).join(' ')
end

#run(input) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rpl/interpreter.rb', line 27

def run( input )
  @dictionary.add_local_vars_layer

  Parser.parse( input.to_s ).each do |elt|
    if elt.instance_of?( RplName )
      break if %w[break quit exit].include?( elt.value )

      if elt.not_to_evaluate
        @stack << elt
      else
        command = @dictionary.lookup( elt.value )
        if command.nil?
          # if there isn't a command by that name then it's a name
          # elt[:type] = :name

          @stack << elt
        elsif command.is_a?( Proc )
          command.call
        else
          if command.instance_of?( RplProgram )
            run( command.value )
          else
            @stack << command
          end
        end
      end
    else
      @stack << elt
    end
  end

  @dictionary.remove_local_vars_layer

  # superfluous but feels nice
  @stack
end

#stack_extract(needs) ⇒ Object

Raises:

  • (ArgumentError)


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/rpl/interpreter.rb', line 64

def stack_extract( needs )
  raise ArgumentError, 'Not enough elements' if @stack.size < needs.size

  needs.each_with_index do |need, index|
    stack_index = (index + 1) * -1

    raise ArgumentError, "Type Error, needed #{need} got #{@stack[stack_index]}" unless need == :any || need.include?( @stack[stack_index].class )
  end

  args = []
  needs.size.times do
    args << @stack.pop
  end

  args
end