gno/usr.bin/awk/tests/asm.print

38 lines
1.2 KiB
Plaintext
Raw Normal View History

# asm - assembler and interpreter for simple computer
# usage: awk -f asm program-file data-files...
# this is a special version to produce a listing
BEGIN {
srcfile = ARGV[1]
ARGV[1] = "" # remaining files are data
tempfile = "/tmp/asm.temp"
n = split("const get put ld st add sub jpos jz j halt", x)
for (i = 1; i <= n; i++) # create table of op codes
op[x[i]] = i-1
# ASSEMBLER PASS 1
nextmem = 0 # new
FS = "[ \t]+"
while (getline <srcfile > 0) {
input[nextmem] = $0 # new: remember source line
sub(/#.*/, "") # strip comments
symtab[$1] = nextmem # remember label location
if ($2 != "") { # save op, addr if present
print $2 "\t" $3 >tempfile
nextmem++
}
}
close(tempfile)
# ASSEMBLER PASS 2
nextmem = 0
while (getline <tempfile > 0) {
if ($2 !~ /^[0-9]*$/) # if symbolic addr,
$2 = symtab[$2] # replace by numeric value
mem[nextmem++] = 1000 * op[$1] + $2 # pack into word
}
for (i = 0; i < nextmem; i++) # new: print memory
printf("%3d: %05d %s\n", i, mem[i], input[i]) # new
}