Skip to content

Instantly share code, notes, and snippets.

@artob
Created July 26, 2009 15:35
Show Gist options
  • Save artob/155811 to your computer and use it in GitHub Desktop.
Save artob/155811 to your computer and use it in GitHub Desktop.
Simple JVM assembler based on the BiteScript gem for JRuby.
# Simple JVM assembler using the BiteScript gem for JRuby.
# @see http://kenai.com/projects/jvmscript
require 'rubygems'
require 'bitescript'
class JVM
class Assembler
attr_reader :options
def self.compile(name, options = {}, &block)
self.new(name, options, &block).compile!
end
def initialize(name, options = {}, &block)
@options = options
@file = BiteScript::FileBuilder.new(options[:source_file] || __FILE__)
@class = @file.public_class(name.to_s)
@method = @class.public_static_method('main', @class.void, @class.string[])
@method.start
if block_given?
case block.arity
when 1 then block.call(@method)
else @method.instance_eval(&block)
end
end
end
def assemble(&block)
@method.instance_eval(&block)
self
end
def compile!
assemble { returnvoid }
@method.stop
@file.generate do |filename, class_builder|
File.open(filename, 'wb') do |file|
file.write(class_builder.generate)
end
end
end
def method_missing(op, *args, &block)
if @method.respond_to?(op)
@method.send(op, *args, &block)
else
super # throws NoMethodError
end
end
end
end
if __FILE__ == $0
# JVM instruction set reference:
# @see http://homepages.inf.ed.ac.uk/kwxm/JVM/codeByFn.html
# A starting point:
JVM::Assembler.compile('hello') do
ldc "Hello, world!"
println
end
# Small integer arithmetic:
JVM::Assembler.compile('fixnum') do
ldc 7
ldc 6
imul
println(int)
end
# Big integer arithmetic:
JVM::Assembler.compile('bignum') do
BigDecimal = java.math.BigDecimal
def ldc_bignum(num)
new BigDecimal
dup
ldc num.to_s
invokespecial BigDecimal, '<init>', [void, string]
end
ldc_bignum 10**100
ldc_bignum 2**64
invokevirtual BigDecimal, :subtract, [BigDecimal, BigDecimal]
invokevirtual BigDecimal, :toString, [string]
println(string)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment