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):
def hole():
t = len(code)
return t
#***
def fetch_var_offset(
global globals_n
n = globals.get(
if n == None:
globals[
n = globals_n
globals_n += 1
Line 749 ⟶ 757:
#***
def fetch_string_offset(
global string_n
n = string_pool.get(
if n == None:
string_pool[
n = string_n
string_n += 1
Line 761 ⟶ 769:
#***
def code_gen(x):
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 =
code_gen(x.right.left) # if true statements
if (x.right.right != None):
emit_byte(JMP) # jump over else statements
p2 =
emit_word_at(p1, len(code) -
▲ code[p1:p1+word_size] = int_to_bytes(len(code) - p1)
if (x.right.right != None):
code_gen(x.right.right) # else statements
elif x.node_type == nd_While:
p1 = len(code)
code_gen(x.left)
emit_byte(JZ)
p2 =
▲ emit_word(0)
code_gen(x.right)
emit_byte(JMP) # jump back to the top
emit_word(p1 - len(code))
elif x.node_type == nd_Sequence:
code_gen(x.left)
Line 835 ⟶ 838:
for k in sorted(string_pool, key=string_pool.get):
print(
pc = 0
Line 885 ⟶ 888:
def load_ast():
line = input_file.readline()
line_list = shlex.split(line, False, False)
text = line_list[0]
|