Support "[["

This commit is contained in:
Pedro de Oliveira 2014-08-14 02:41:56 +01:00
parent e9309a7fb5
commit a3db0d510a
2 changed files with 37 additions and 13 deletions

View File

@ -4,23 +4,31 @@ tv_flag equ $5c3c ; TV flags variable
last_k equ $5c08 ; Last pressed key
; Brainfuck Operators
OP_INC_DP equ ">"
OP_DEC_DP equ "<"
OP_INC_VAL equ "+"
OP_DEC_VAL equ "-"
OP_OUT equ "."
OP_IN equ ","
OP_JMP_FWD equ "["
OP_JMP_BCK equ "]"
OP_INC_DP equ ">" ; $3e - 62
OP_DEC_DP equ "<" ; $3c - 60
OP_INC_VAL equ "+" ; $2b - 43
OP_DEC_VAL equ "-" ; $2d - 45
OP_OUT equ "." ; $2e - 46
OP_IN equ "," ; $2c - 44
OP_JMP_FWD equ "[" ; $5b - 91
OP_JMP_BCK equ "]" ; $5d - 93
; Brainfuck source
; Hello World
;brainfuck db "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.", 0
brainfuck db "++++[>++++++++++<-]>++.>+++++++++++++.<<++[>.<-]>>.<<+++[>.<-]>>.<<++++[>.<-]>>.<<+++++[>.<-]>>.", 0
; Arvorezinha
;brainfuck db "++++[>++++++++++<-]>++.>+++++++++++++.<<++[>.<-]>>.<<+++[>.<-]>>.<<++++[>.<-]>>.<<+++++[>.<-]>>.", 0
; To test the "," operator
;brainfuck db "++++++++++>+[,<.>.]", 0
; Bad Boy Hello world
brainfuck db ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>>+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.", 0
; Variables
memory_pos db $0,$80 ; Current memory position
; Contains the address on where the BF memory begins
source_pos db $0,$0 ; Current source position
branch_count db $0
;lookup_tbl db F_INC_DP,F_INC_DP+1, F_DEC_DP, F_DEC_DP+1
start
xor a ; a = 0
@ -31,7 +39,7 @@ main
ld hl, brainfuck ; Get source first position
ld de, (source_pos) ;
add hl, de ; First position + current position
ld a, (hl) ; Read opcode from source
; EOF
@ -74,6 +82,7 @@ continue
ld de, (source_pos) ; Increment source position
inc de
ld (source_pos), de
jr main ; Do it again
end_main
@ -148,7 +157,7 @@ F_IN_LOOP
F_JMP_FWD
ld de, (memory_pos) ; If the value at current memory
ld a, (de) ; position is 0, skip until the next
cp 0 ; "]"
cp $0 ; "]"
jr z, SKIP_LOOP
ld de, (source_pos) ; Save the "[" source position on the
@ -157,6 +166,10 @@ F_JMP_FWD
; Increments the source position until a "]" is found
SKIP_LOOP
ld a, (branch_count) ; Increment the number of branches
inc a
ld (branch_count), a
SKIP_LOOP_2
ld de, (source_pos) ; Increment source position
inc de
ld (source_pos), de
@ -164,8 +177,19 @@ SKIP_LOOP
ld hl, brainfuck ; String first position
add hl, de ; First position + current position
ld a, (hl) ; Read opcode from source
cp OP_JMP_FWD ; Is it a "[" ?
jr z, F_JMP_FWD ; Do it again
cp OP_JMP_BCK ; Is it a "]"?
jr nz, SKIP_LOOP ; No? Then increment again
jr nz, SKIP_LOOP_2 ; Repeat until found
ld a, (branch_count) ; If the number of branches is not 0
dec a ; we need to find the next "]"
ld (branch_count), a
cp $0
jr nz, SKIP_LOOP_2
jp continue
; -------------------------------------

Binary file not shown.