Class: RBF::Interpreter

Inherits:
Object
  • Object
show all
Defined in:
lib/rbf/interpreter.rb,
lib/rbf/interpreter/storage.rb

Defined Under Namespace

Classes: Storage

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Interpreter

Returns a new instance of Interpreter.



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rbf/interpreter.rb', line 21

def initialize (options={})
  @options = options

  @storage = Storage.new(options[:env] || [])
  @input   = STDIN
  @output  = options[:output] || STDOUT

  @parser    = RBF::Parser.syntax(RBF.syntax(options[:syntax])).new
  @transform = RBF::Transform.new
  @optimizer = RBF::Optimizer.new(options)
  @jit       = RBF::JIT.new(options)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



19
20
21
# File 'lib/rbf/interpreter.rb', line 19

def options
  @options
end

#outputObject (readonly)

Returns the value of attribute output.



19
20
21
# File 'lib/rbf/interpreter.rb', line 19

def output
  @output
end

#storageObject (readonly)

Returns the value of attribute storage.



19
20
21
# File 'lib/rbf/interpreter.rb', line 19

def storage
  @storage
end

Instance Method Details

#cycle(tree) ⇒ Object



71
72
73
74
75
76
77
78
79
# File 'lib/rbf/interpreter.rb', line 71

def cycle (tree)
  tree.each {|token|
    if token.is_a?(Array)
      loop(token)
    else
      send(token)
    end
  }
end

#evaluate(tree, options = nil) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rbf/interpreter.rb', line 44

def evaluate (tree, options=nil)
  options = @options.merge(options || {})

  if options[:catch]
    @output = StringIO.new
  else
    @output = options[:output] || STDOUT
  end

  tree = parse(tree)

  if JIT.supported? && !options[:catch]
    return @jit.compile(tree).execute
  end

  cycle(parse(tree))

  if options[:catch]
    @output.rewind
    @output.read
  end
end

#execute(path, options = nil) ⇒ Object



67
68
69
# File 'lib/rbf/interpreter.rb', line 67

def execute (path, options=nil)
  evaluate(File.read(path), options)
end

#loop(tree) ⇒ Object



81
82
83
84
85
# File 'lib/rbf/interpreter.rb', line 81

def loop (tree)
  while @storage.get != 0
    cycle(tree)
  end
end

#parse(text) ⇒ Object

Raises:

  • (SyntaxError)


34
35
36
37
38
39
40
41
42
# File 'lib/rbf/interpreter.rb', line 34

def parse (text)
  return text if text.is_a?(Array)

  parsed = @parser.parse_with_debug(text)

  raise SyntaxError, 'There is a syntax error' unless parsed

  @optimizer.optimize(@transform.apply(parsed))
end