Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@blendmaster
Created February 24, 2012 04:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blendmaster/1897787 to your computer and use it in GitHub Desktop.
Save blendmaster/1897787 to your computer and use it in GitHub Desktop.
.hack assembler main logic in coco
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