2026-02-01 16:33:20 -08:00
|
|
|
|
with javascript_semantics
|
|
|
|
|
|
constant NOP = 0b000_00000, -- no operation
|
|
|
|
|
|
LDA = 0b001_00000, -- load accumulator, a := memory [xxxxx]
|
|
|
|
|
|
STA = 0b010_00000, -- store accumulator, memory [xxxxx] := a
|
|
|
|
|
|
ADD = 0b011_00000, -- add, a := a + memory [xxxxx]
|
|
|
|
|
|
SUB = 0b100_00000, -- subtract, a := a – memory [xxxxx]
|
|
|
|
|
|
BRZ = 0b101_00000, -- branch on zero, if a = 0 then goto xxxxx
|
|
|
|
|
|
JMP = 0b110_00000, -- jump, goto xxxxx
|
|
|
|
|
|
STP = 0b111_00000, -- stop
|
|
|
|
|
|
OP = 0b111_00000, -- operator mask
|
|
|
|
|
|
ARG = 0b000_11111 -- memory location (0 based)
|
2023-07-01 11:58:00 -04:00
|
|
|
|
|
2026-02-01 16:33:20 -08:00
|
|
|
|
procedure execute(string name, sequence program)
|
|
|
|
|
|
sequence memory = deep_copy(program)
|
|
|
|
|
|
integer pc = 1, a = 0
|
|
|
|
|
|
while true do
|
|
|
|
|
|
integer ppc = memory[pc],
|
|
|
|
|
|
op = and_bitsu(ppc,OP),
|
|
|
|
|
|
arg = and_bits(ppc,ARG)+1
|
|
|
|
|
|
pc += 1
|
|
|
|
|
|
switch op do
|
|
|
|
|
|
case NOP: break
|
|
|
|
|
|
case LDA: a = memory[arg]
|
|
|
|
|
|
case STA: memory[arg] = a
|
|
|
|
|
|
case ADD: a = and_bitsu(a+memory[arg],#FF)
|
|
|
|
|
|
case SUB: a = and_bitsu(a-memory[arg],#FF)
|
|
|
|
|
|
case BRZ: if a=0 then pc = arg end if
|
|
|
|
|
|
case JMP: pc = arg
|
|
|
|
|
|
case STP: printf(1,"%12s: %3d\n",{name,a})
|
|
|
|
|
|
return
|
|
|
|
|
|
end switch
|
|
|
|
|
|
end while
|
|
|
|
|
|
end procedure
|
2023-07-01 11:58:00 -04:00
|
|
|
|
|
2026-02-01 16:33:20 -08:00
|
|
|
|
execute("2+2",{LDA+3, ADD+4, STP, 2,2})
|
|
|
|
|
|
execute("7*8",{LDA+12, ADD+10, STA+12, LDA+11, SUB+13, STA+11, BRZ+8, JMP+0,
|
|
|
|
|
|
LDA+12, STP, 8,7,0,1})
|
|
|
|
|
|
execute("fibonacci",{LDA+14, STA+15, ADD+13, STA+14, LDA+15, STA+13, LDA+16,
|
|
|
|
|
|
SUB+17, BRZ+11, STA+16, JMP+0, LDA+14, STP, 1,1,0,8,1})
|
|
|
|
|
|
execute("linkedList",{LDA+13, ADD+15, STA+5, ADD+16, STA+7, NOP, STA+14, NOP,
|
|
|
|
|
|
BRZ+11, STA+15, JMP+0, LDA+14, STP, LDA+0, 0,28,1,0,0,
|
|
|
|
|
|
0,6,0,2,26,5,20,3,30,1,22,4,24})
|
|
|
|
|
|
execute("prisoner",{NOP, NOP, STP, 0, LDA+3, SUB+29, BRZ+18, LDA+3, STA+29,
|
|
|
|
|
|
BRZ+14, LDA+1, ADD+31, STA+1, JMP+2, LDA+0, ADD+31, STA+0,
|
|
|
|
|
|
JMP+2, LDA+3, STA+29, LDA+1, ADD+30, ADD+3, STA+1, LDA+0,
|
|
|
|
|
|
ADD+30, ADD+3, STA+0, JMP+2, 0, 1, 3})
|
|
|
|
|
|
-- subtractions yielding negative results
|
|
|
|
|
|
execute("0-255",{LDA+3,SUB+4,STP, 0,255})
|
|
|
|
|
|
execute("0-1",{LDA+3, SUB+4, STP, 0,1})
|
|
|
|
|
|
-- overflow on addition
|
|
|
|
|
|
execute("1+255",{LDA+3, ADD+4, STP, 1, 255})
|