9086/cpu/brainfuck.asm

125 lines
2.0 KiB
NASM

; brainfuck.asm - Naive and unoptimised implementation of a brainfuck interpreter
;
; This file is part of the 9086 project.
;
; Copyright (c) 2023 Efthymios Kritikos
;
; This program is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program. If not, see <http://www.gnu.org/licenses/>.
mov si,#prog
mov BX,#data
mov CX,#bracket
dec si
INTERPRET:
inc si
mov al,[si]
cmp al,#'+
jz WAS_PLUS
cmp al,#'-
jz WAS_MINUS
cmp al,#'>
jz WAS_MR
cmp al,#'<
jz WAS_ML
cmp al,#'[
jz WAS_PL
cmp al,#']
jz WAS_PR
cmp al,#'.
jz WAS_PRINT
jmp PROG_END
WAS_PLUS:
inc BYTE [BX]
JMP INTERPRET
WAS_MINUS:
dec BYTE [BX]
JMP INTERPRET
WAS_MR:
inc bx
JMP INTERPRET
WAS_ML:
dec bx
JMP INTERPRET
WAS_PL:
MOV AL,[BX]
cmp AL,#0
jz SKIP_CODE_BLOCK
;have to enter loop
MOV AX,SI
inc CX
inc CX
push SI
MOV SI,CX
mov [SI],AX
POP SI
JMP INTERPRET
SKIP_CODE_BLOCK:
;have to skip loop
MOV DX,#0
SKIP_LOOP:
INC SI
mov AL,[SI]
CMP AL,#']
JZ WAS_CLOSE1
CMP AL,#'[
JZ WAS_OPEN1
JMP SKIP_LOOP
WAS_CLOSE1:
CMP DX,#0
JZ INTERPRET
DEC DX
JMP SKIP_LOOP
WAS_OPEN1:
INC DX
JMP SKIP_LOOP
WAS_PR:
mov AL,[BX]
cmp AL,#0
JZ EXIT_PR
push SI
MOV SI,CX
mov ax,[SI]
POP SI
mov si,ax
JMP INTERPRET
EXIT_PR:
DEC CX
DEC CX
jmp INTERPRET
WAS_PRINT:
mov ah, #0x02
MOV DL,[BX]
int #0x21
JMP INTERPRET
PROG_END:
hlt
bracket: .BLKB 280
data: .BLKB 560
;prog db '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.f'
prog:.ASCII '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'