Compiler/code generator: Difference between revisions

m
Better variable names; convert obscure code to a function
m (More clarifications)
m (Better variable names; convert obscure code to a function)
Line 736:
for x in s:
code.append(x)
 
def emit_word_at(at, n):
code[p1at:p1at+word_size] = int_to_bytes(len(code) - p1n)
 
def hole():
t = len(code)
emit_word(0)
return t
 
#***
def fetch_var_offset(valuename):
global globals_n
 
n = globals.get(valuename, None)
if n == None:
globals[valuename] = globals_n
n = globals_n
globals_n += 1
Line 749 ⟶ 757:
 
#***
def fetch_string_offset(valuethe_string):
global string_n
 
n = string_pool.get(valuethe_string, None)
if n == None:
string_pool[valuethe_string] = string_n
n = string_n
string_n += 1
Line 761 ⟶ 769:
#***
def code_gen(x):
global string_n
 
if x == None: return
elif x.node_type == nd_Ident:
Line 783 ⟶ 789:
code_gen(x.left) # expr
emit_byte(JZ) # if false, jump
p1 = lenhole(code) # make room for jump dest
emit_word(0) # make room for jump dest
code_gen(x.right.left) # if true statements
if (x.right.right != None):
emit_byte(JMP) # jump over else statements
p2 = lenhole(code)
emit_word_at(p1, len(code) - emit_word(0p1)
code[p1:p1+word_size] = int_to_bytes(len(code) - p1)
if (x.right.right != None):
code_gen(x.right.right) # else statements
code[emit_word_at(p2:p2+word_size], = int_to_bytes(len(code) - p2)
elif x.node_type == nd_While:
p1 = len(code)
code_gen(x.left)
emit_byte(JZ)
p2 = lenhole(code)
emit_word(0)
code_gen(x.right)
emit_byte(JMP) # jump back to the top
emit_word(p1 - len(code))
code[emit_word_at(p2:p2+word_size], = int_to_bytes(len(code) - p2)
elif x.node_type == nd_Sequence:
code_gen(x.left)
Line 835 ⟶ 838:
 
for k in sorted(string_pool, key=string_pool.get):
print('"' + k + '"')
 
pc = 0
Line 885 ⟶ 888:
def load_ast():
line = input_file.readline()
line_list = shlex.split(line, False, False)
 
text = line_list[0]
155

edits