Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os, sys;
- # ეს დიქშენარები არის გადაკოპირებული, იმიტომ რომ იგივე რომ დამეწერა მაინც იგივე კოდი გამოვიდოდა
- comp = {
- "0": "0101010",
- "1": "0111111",
- "-1": "0111010",
- "D": "0001100",
- "A": "0110000",
- "!D": "0001101",
- "!A": "0110001",
- "-D": "0001111",
- "-A": "0110011",
- "D+1": "0011111",
- "A+1": "0110111",
- "D-1": "0001110",
- "A-1": "0110010",
- "D+A": "0000010",
- "D-A": "0010011",
- "A-D": "0000111",
- "D&A": "0000000",
- "D|A": "0010101",
- "M": "1110000",
- "!M": "1110001",
- "-M": "1110011",
- "M+1": "1110111",
- "M-1": "1110010",
- "D+M": "1000010",
- "D-M": "1010011",
- "M-D": "1000111",
- "D&M": "1000000",
- "D|M": "1010101"
- }
- dest = {
- "null": "000",
- "M": "001",
- "D": "010",
- "A": "100",
- "MD": "011",
- "AM": "101",
- "AD": "110",
- "AMD": "111"
- }
- jump = {
- "null": "000",
- "JGT": "001",
- "JEQ": "010",
- "JGE": "011",
- "JLT": "100",
- "JNE": "101",
- "JLE": "110",
- "JMP": "111"
- }
- variable = {
- "SP": 0,
- "LCL": 1,
- "ARG": 2,
- "THIS": 3,
- "THAT": 4,
- "SCREEN": 16384,
- "KBD": 24576,
- "cursor": 16
- }
- for i in range(0, 16):
- st = 'R' + str(i)
- variable[st] = i
- # აქამდე გადაწერილია შემეზარა ამგენის დაწერა
- def getCommand(line):
- if (line.find('/') != -1):
- line = line[:line.find('/')]
- lineList = line.split(' ')
- line = ''.join(str(x) for x in lineList)
- lineList = line.split('\n')
- line = ''.join(str(x) for x in lineList)
- return line
- def Abinary(line):
- if line[0].isalpha():
- if line in variable:
- r = variable.get(line)
- else:
- variable[line] = variable.get('cursor')
- variable['cursor'] = variable['cursor'] + 1
- r = variable[line]
- else:
- r = int(line)
- return str(bin(r)[2:].zfill(16))
- def Cbinary(line):
- if not "=" in line:
- line = "null=" + line
- if not ";" in line:
- line = line + ";null"
- binary = ''
- splitt = line.split('=')
- binary = dest.get(splitt[0])
- splitt = splitt[1].split(';')
- binary = comp.get(splitt[0], 'damerxa') + binary
- binary += jump.get(splitt[1], 'damerxa')
- return '111' + binary
- def binary(line):
- if line[0] == '@':
- return Abinary(line[1:])
- return Cbinary(line)
- def firstRead():
- infile = open(root + ".asm")
- i = 0
- for line in infile:
- line = getCommand(line)
- if line == "":
- continue
- if line[0] == '(':
- line = line[1:-1]
- variable[line] = i
- continue
- i += 1
- infile.close()
- def readLines():
- infile = open(root + ".asm")
- outfile = open(root + ".hack", "w")
- i = 0
- for line in infile:
- line = getCommand(line)
- if line == "":
- continue
- if line[0] == '(':
- continue
- i = i + 1
- ans = binary(line)
- print(ans)
- outfile.write(ans + '\n')
- outfile.close()
- infile.close()
- root = sys.argv[1]
- firstRead()
- readLines()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement