Compiler is now C compiler

This commit is contained in:
pjht 2018-03-01 16:21:16 -06:00
parent e2f807391b
commit fc3eaf7abe
7 changed files with 146 additions and 135 deletions

1
.rspec
View File

@ -1 +0,0 @@
--require spec_helper -f d

View File

@ -1,22 +1,118 @@
def compile(prog)
temp={}
nextvar=0
code=""
lines=[]
i=0
prog.split(";").each do |line|
lines[i]=line.strip
i+=1
# TODO: Make compilation two-phase:
=begin
Phase one will accept an array of tokens and update the tables accordingly.
Phase two wil take the data from the tables and do the actual compilation.
=end
$types=[:int,:void]
$functable={}
$cfunc=nil
$outfile=nil
class CompilationError < StandardError; end
class String
def is_integer?
self.to_i.to_s == self
end
lines.each do |line|
line=line.split(" ")
if line[0] == "var"
temp[line[2]]=nextvar
nextvar+=1
end
if line[0] == "let"
code += "push constant #{line[3]}\npop temp #{temp[line[1]]}"
end
end
return temp,code
end
def get_index(var)
vartable=$functable[$cfunc][:vars]
if vartable.include? var
return vartable.find_index(var)
else
raise CompilationError,"No such variable #{var}"
end
end
def tokenize_line(line)
split_line=line.split(" ")
cmd=split_line.shift.to_sym
tokens=[]
if $types.include? cmd
if /(\w+)\((.*)\) \{/.match(split_line.join(" "))
tokens.push(:func)
tokens.push($1.to_sym)
tokens.push($2)
else
tokens.push(:newvar)
tokens.push(cmd)
tokens.push(split_line[0].to_sym)
end
else
if split_line[0] == "="
tokens.push(:assignment)
tokens.push(cmd.to_sym)
tokens.push(split_line[1])
end
if cmd == "}"
tokens.push(:endfunc)
end
end
return tokens
end
def phase_one(tokens)
if $cfunc==nil and tokens[0] != :func
raise CompilationError, "Code must be inside a fuction"
end
case tokens[0]
when :func
$functable[tokens[1]]={:vars=>[],:code=>[]}
$cfunc=tokens[1]
when :endfunc
$cfunc=nil
when :newvar
$functable[$cfunc][:vars].push(tokens[2])
else
$functable[$cfunc][:code].push(tokens)
end
end
def phase_two
$functable.each do |func,info|
vars=info[:vars]
$outfile.puts "function Main.#{func.to_s} #{vars.length}"
info[:code].each do |line|
#puts "Parsing line #{line}"
action=line.shift
case action
when :assignment
index=get_index(line[0])
if line[1].is_integer?
$outfile.puts "push constant #{line[1].to_i}"
$outfile.puts "pop local #{index}"
else
index1=get_index(line[1])
$outfile.puts "push local #{index1}"
end
end
end
$outfile.puts "return"
$outfile.puts(" ")
end
end
def write_init
sysfile=File.new("Sys.vm","w")
sysfile.puts("function Sys.init 0")
sysfile.puts("call Main.main 0")
sysfile.puts("label halt")
sysfile.puts("goto halt")
sysfile.puts(" ")
end
if !File.exists? "vmprog"
Dir.mkdir("vmprog")
end
Dir.chdir("vmprog")
$outfile=File.new("Main.vm","w")
write_init()
phase_one(tokenize_line("int main() {"))
phase_one(tokenize_line("int x"))
phase_one(tokenize_line("x = 10"))
phase_one(tokenize_line("int y"))
phase_one(tokenize_line("y = 10"))
phase_one(tokenize_line("}"))
puts $functable
phase_two

View File

@ -1,6 +1,6 @@
$debug=true
$pfdebug=true
$fdebug=false
$fdebug=true
$mname="the initialization code"
$arg=[]
$local=[]
@ -214,19 +214,19 @@ end
prog=<<-END
# Memory class
function Memory.alloc 0
function Memory.alloc 1
push static 0
pop temp 0
pop local 0
push static 0
push argument 0
add
pop static 0
push temp 0
push local 0
return
# Array class
function x[y]=z 0
function Array.set 0
push argument 0
push argument 1
add
@ -235,7 +235,7 @@ function x[y]=z 0
pop this 0
return
function x[y] 0
function Array.get 0
push argument 0
push argument 1
add
@ -285,7 +285,7 @@ return
# Main class
function Main.main 1
# Set t=Test.new
# t=Test.new
call Test.new 0
pop local 0
# t.var=10
@ -311,4 +311,14 @@ END
boundtest=<<-END
pop pointer 2
END
runprog(prog)
testing=<<-END
function main 2
push constant 10
pop local 0
push constant 10
pop local 1
return
call main 0
END
runprog(testing)

View File

@ -1,6 +0,0 @@
require_relative "../compiler.rb"
describe "compile" do
it "handles int definitions" do
expect(compile("var int number")).to eq [{"number"=>0}, ""]
end
end

View File

@ -1,100 +0,0 @@
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end

7
vmprog/Main.vm Normal file
View File

@ -0,0 +1,7 @@
function Main.main 2
push constant 10
pop local 0
push constant 10
pop local 1
return

5
vmprog/Sys.vm Normal file
View File

@ -0,0 +1,5 @@
function Sys.init 0
call Main.main 0
label halt
goto halt