Class: RPxem::Interpreter

Inherits:
Object
  • Object
show all
Defined in:
lib/rpxem/interpreter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mapping = {}) ⇒ Interpreter

Returns a new instance of Interpreter.



10
11
12
# File 'lib/rpxem/interpreter.rb', line 10

def initialize(mapping={})
  @mapping = default_mapping().merge(mapping)
end

Instance Attribute Details

#mappingObject

Returns the value of attribute mapping.



7
8
9
# File 'lib/rpxem/interpreter.rb', line 7

def mapping
  @mapping
end

#stackObject (readonly)

Returns the value of attribute stack.



8
9
10
# File 'lib/rpxem/interpreter.rb', line 8

def stack
  @stack
end

#tempObject (readonly)

Returns the value of attribute temp.



8
9
10
# File 'lib/rpxem/interpreter.rb', line 8

def temp
  @temp
end

Instance Method Details

#default_mappingObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/rpxem/interpreter.rb', line 40

def default_mapping
  {
    # I/O
    'p' => 'output_all',
    'o' => 'output',
    'n' => 'output_num',
    'i' => 'input',
    '_' => 'input_num',

    # Stack
    'c' => 'copy',
    's' => 'throw_away',
    'v' => 'reverse',

    # File contents
    'f' => 'read_file',
    'e' => 'emurate',

    # Rand
    'r' => 'rand',

    # Loop
    'w' => 'w',
    'x' => 'x',
    'y' => 'y',
    'z' => 'z',
    'a' => 'a',

    # Temporary area
    't' => 'to_temp',
    'm' => 'from_temp',

    # Do nothing
    'd' => 'void',

    # Math
    '+' => 'addition',
    '-' => 'subtraction',
    '!' => 'multiplication',
    '$' => 'quotient',
    '%' => 'surplus',
  }
end

#open(file, stack = RPxem::Stack.new, temp = nil) ⇒ Object

Open and execute a Pxem file



15
16
17
# File 'lib/rpxem/interpreter.rb', line 15

def open(file, stack=RPxem::Stack.new, temp=nil)
  run(File.basename(file), File.open(file).read, stack, temp)
end

#run(filename, source = '', stack = RPxem::Stack.new, temp = nil) ⇒ Object

Execute a Pxem code



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rpxem/interpreter.rb', line 20

def run(filename, source='', stack=RPxem::Stack.new, temp=nil)
  @filename, @source, @stack, @temp = filename.each_byte.to_a, source, stack, temp
  buffer, @cursor, length = RPxem::Stack.new, 0, @filename.length

  while (@cursor < length)
    char = @filename[@cursor]
    @cursor += 1
    if (@cursor < length && 46 == char && name = @mapping[@filename[@cursor].chr.downcase])
      @stack.push(*buffer)
      buffer = RPxem::Stack.new
      __send__(name)
      @cursor += 1
    else
      buffer.unshift(char)
    end
  end

  return @stack
end