Skip to content

Instantly share code, notes, and snippets.

@sposterkil
Created September 16, 2014 05:18
Show Gist options
  • Save sposterkil/d35425c68fd5f21ca61d to your computer and use it in GitHub Desktop.
Save sposterkil/d35425c68fd5f21ca61d to your computer and use it in GitHub Desktop.
Instruction generator
def get_instructions(pattern_list):
"""Takes a list of regex patterns and compiles them to a list of VM
instructions via the lexc tool, and then returns that list."""
# The lexing compiler should be in the same folder as us
lexexec = os.path.abspath(os.path.join(sys.path[0], "lexc"))
# (Yes, this giant chain of os.path things checks that)
if not os.path.isfile(os.path.abspath(os.path.join(sys.path[0], "lexc"))):
print lexexec
raise IOError("Lexc executable not in same folder as program.")
command = [lexexec] + ["--pattern=%s" % str(pattern)
for pattern in pattern_list]
# Raw output from lexc
raw_inst = subprocess.check_output(command)
# Matches properly formatted lines, grouping instructions
# and their parameters
inst_match = re.compile(
r"\s+(?P<line>\d+)\s+(?P<inst>MATCH|JMP|SPLIT|CHAR)\s*(?P<a>\d+)?(?:, (?P<b>\d+))?")
# We ignore the last line here because it will always be blank
return [re.match(inst_match, line).groupdict()
for line in raw_inst.split("\n")[0:-1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment