Class: AmberVM::Languages::Math::Compiler

Inherits:
Object
  • Object
show all
Includes:
Interpreter
Defined in:
lib/amber/languages/math/compiler.rb

Constant Summary collapse

FUNCTION_MAP =
{
  '+' => :add,
  '-' => :sub,
  '/' => :div,
  '*' => :mul,
  '^' => :power
}

Class Method Summary collapse

Methods included from Interpreter

const, env, makevs

Class Method Details

.compile(tree) ⇒ Object



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
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
# File 'lib/amber/languages/math/compiler.rb', line 13

def Compiler.compile tree
  if tree.is_a? Array
    compile(tree.first)
  elsif tree.is_a? Hash
    case tree[:type]
      when :number
      Interpreter.const(:number, tree[:number])
      when :function
      params = tree[:params].map {|p| compile(p)}
      case tree[:op]
        when '-'
        CoreCall.new :neg, params
      else
        FunctionCall.new tree[:op], params
      end
      when :ident
      Interpreter::Variable.new(Interpreter.const(:string, tree[:ident]))
      when :op
      case tree[:op]
        when ';'
        s = Interpreter::Sequence.new()
        if (tree[:left][:type] == :op) and (tree[:left][:op] == ';')
          s += compile(tree[:left])
        else
          s << compile(tree[:left])
        end
        if (tree[:right][:type] == :op) and (tree[:right][:op] == ';')
          s += compile(tree[:right])
        else
          s << compile(tree[:right])
        end
        when '='
        case tree[:left][:type]
          when :ident
          Interpreter::Assignment.new(Interpreter.const(:string, tree[:left][:ident]),compile(tree[:right]))
          when :function
          body = Interpreter::Sequence.new()
          i = 0
          tree[:left][:params].each do |p|
            raise ArgumentError, "Bad ype for a function parameter: #{p[:type]} " if p[:type] != :ident
            body << Interpreter::Assignment.new(Interpreter.const(:string, p[:ident]), Interpreter::Parameter.new(Interpreter.const(:number, i)))
            i += 1
          end
          body << compile(tree[:right])
          Interpreter::FunctionDefinition.new(Interpreter.const(:string, tree[:left][:op]), AmberVM::Classes::Block.new(body))
        else
          raise ArgumentError, "Bad name for a variable!"
        end
      else
        CoreCall.new(FUNCTION_MAP[tree[:op]], [compile(tree[:left]),compile(tree[:right])])
      end
    end
  end
end