folded fake builder, started adapting tests and added example file

This commit is contained in:
Torsten Ruger 2014-04-24 17:17:17 +03:00
parent 601dc22b2e
commit 305f2380a9
5 changed files with 65 additions and 29 deletions

View File

@ -1,7 +1,7 @@
module Vm
class Number < Struct.new :value
def eval(context, builder)
builder.ldc value
builder.mov "r0" , value
end
end

29
test/example.vm Normal file
View File

@ -0,0 +1,29 @@
function plus(a, b) {
minus(a, minus(0, b))
}
function times(a, b) {
if (eq(b, 0)) {
0
} else {
plus(a, times(a, minus(b, 1)))
}
}
function eq(a, b) {
if (minus(a, b)) {
0
} else {
1
}
}
function factorial(n) {
if (eq(n, 1)) {
1
} else {
times(n, factorial(minus(n, 1)))
}
}
print(factorial(4))

View File

@ -1,21 +0,0 @@
class FakeBuilder
attr_reader :result
def initialize
@result = ''
end
def class_builder
'example'
end
def int
'int'
end
def method_missing(name, *args, &block)
@result += ([name] + args.flatten).join(', ').sub(',', '')
@result += "\n"
block.call(self) if name.to_s == 'public_static_method'
end
end

7
test/test_complier.rb Executable file
View File

@ -0,0 +1,7 @@
(puts("Usage: #{} SOURCE"); exit) if ARGV.empty?
require_relative 'helper'
require 'vm/compiler'
Thnad::Compiler.new(ARGV.first).compile

View File

@ -4,10 +4,31 @@ $: << File.expand_path(File.dirname(__FILE__))
require 'minitest/autorun'
require 'minitest/spec'
require 'vm/nodes'
require 'fake_builder'
include Vm
class FakeBuilder
attr_reader :result
def initialize
@result = ''
end
def class_builder
'example'
end
def int
'int'
end
def method_missing(name, *args, &block)
@result += ([name] + args.flatten).join(', ').sub(',', '')
@result += "\n"
block.call(self) if name.to_s == 'public_static_method'
end
end
describe 'Nodes' do
before do
@context = Hash.new
@ -17,7 +38,7 @@ describe 'Nodes' do
it 'emits a number' do
input = Vm::Number.new 42
expected = <<HERE
ldc 42
mov r0, 42
HERE
input.eval @context, @builder
@ -30,7 +51,7 @@ HERE
input = Vm::Funcall.new 'baz', [Vm::Number.new(42),
Vm::Name.new('foo')]
expected = <<HERE
ldc 42
mov r0, 42
iload 0
invokestatic example, baz, int, int, int
HERE
@ -46,12 +67,12 @@ HERE
Vm::Number.new(42),
Vm::Number.new(667)
expected = <<HERE
ldc 0
mov r0, 0
ifeq else
ldc 42
mov r0, 42
goto endif
label else
ldc 667
mov r0, 667
label endif
HERE
@ -67,7 +88,7 @@ HERE
expected = <<HERE
public_static_method foo, int, int
ldc 5
mov r0, 5
ireturn
HERE