41 lines
1.2 KiB
Awk
41 lines
1.2 KiB
Awk
#!/sbin/env awk -f
|
|
# POSIX AWK port of Subleq VM (16-bit variant)
|
|
# Accepts .dec files as input
|
|
# Usage: [busybox] awk -f subleq.awk program.dec
|
|
# Created by Luxferre in 2023, released into public domain
|
|
|
|
function L(v) { # cast any value to unsigned 16-bit integer
|
|
v = int(v)
|
|
while(v < 0) v += 65536
|
|
return int(v%65536)
|
|
}
|
|
|
|
function getchar(c, cmd) { # POSIX-compatible getchar emulation with sh read
|
|
(cmd="c='';IFS= read -r -n 1 -d $'\\0' c;printf '%u' \"'$c\"") | getline c
|
|
close(cmd)
|
|
return int(c)
|
|
}
|
|
|
|
BEGIN {
|
|
for(pc=0;pc<65536;pc++) MEM[pc] = 0 # init the memory array
|
|
pc = a = b = c = 0 # reset the program counter and other vars
|
|
}
|
|
|
|
# match on any 16-bit signed integer in the .dec file
|
|
{ for(i=1;i<=NF;i++) if($i ~ /^[-0-9][0-9]*$/) MEM[pc++] = L($i) }
|
|
|
|
END { # start the actual execution
|
|
for(pc=0;pc<32768;) {
|
|
a = MEM[pc++]; b = MEM[pc++]; c = MEM[pc++] # fill the cell addresses
|
|
# -1 in cell A => input to cell B
|
|
if(a == 65535) MEM[b] = L(getchar())
|
|
# -1 in cell B => output cell A
|
|
else if(b == 65535) printf("%c", MEM[a]%256)
|
|
# main OISC logic here
|
|
else {
|
|
MEM[b] = L(MEM[b] - MEM[a]) # subtract the first 2 cells and cast
|
|
if(MEM[b] == 0 || (MEM[b] > 32767)) pc = c # jump if result <=0
|
|
}
|
|
}
|
|
}
|