Created
February 24, 2012 04:41
-
-
Save blendmaster/1897787 to your computer and use it in GitHub Desktop.
.hack assembler main logic in coco
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
code = input | |
.replace /\/\/.*/gm '' # remove comments | |
.trim! | |
.split /\s+/ # turn into lines | |
.filter (it, i) -> # build symbol table and remove labels | |
if it.match /\(([A-Za-z\._$:][\w\.$:]*)\)$/ # that[1] is the first capturing group | |
symbols[that[1]] = i - len++ # len++ adjusts the symbol's line number to the filtered array | |
return false | |
true # keep actual instructions | |
.map -> # parse instructions | |
if symbol = (it.match /^@(.+)$/)?1 # convert A instructions | |
pad16 if symbols[symbol]? | |
that | |
else unless isNaN(that = parseInt symbol, 10) | |
that | |
else # map the variable | |
variables[symbol] ?= loc++ # return mapped location or the next available one | |
else if it.match /^(?:([AMD][MD]?[D]?)=)?(?:([01!+&|DAM\-]+))(?:;(\w+))?$/ # convert C instructions | |
[...,dest,comp,jump] = that | |
\111 + | |
bool(/M/.test(comp)) + # 1 when M appears in the comp field | |
(comps[comp] or die "invalid comp in \"#it\"") + # lookup table | |
# compute dest because it's relatively easy (compared to comp) | |
(if dest then bool(/A/.test(dest)) + bool(/D/.test(dest)) + bool(/M/.test(dest)) else \000) + | |
(jumps[jump] or die "invalid jump in \"#it\"") # lookup jump | |
else | |
die "invalid instruction: \"#it\"" | |
.join '\n' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment