0
0
Fork 0
mirror of https://git.sr.ht/~rabbits/uxn synced 2024-11-28 00:33:02 +00:00
uxn/projects/examples/exercises/brainfuck.tal

93 lines
1.7 KiB
Tal
Raw Normal View History

2021-11-13 02:51:39 +00:00
( brainfuck interpreter )
%!~ { NEQk NIP }
%DEC { #01 SUB }
%DEC2 { #0001 SUB2 }
%DECr { LITr 01 SUBr }
%RTN { JMP2r }
%HALT { #0101 #0e DEO2 }
%EMIT { #18 DEO }
%MEMORY { #8000 }
|0000
2021-11-13 16:08:21 +00:00
@ptr $2
2021-11-13 02:51:39 +00:00
|0100 ( -> )
2021-11-13 16:08:21 +00:00
MEMORY .ptr STZ2
2021-11-13 02:51:39 +00:00
;program
&while
LDAk ,op JSR
INC2 LDAk ,&while JCN
POP2
HALT
BRK
@op ( op -- )
2021-11-13 15:57:54 +00:00
( Move the pointer to the right )
2021-11-13 16:08:21 +00:00
LIT '> !~ ,&movr JCN [ .ptr LDZ2k INC2 ROT STZ2 POP RTN ] &movr
2021-11-13 15:57:54 +00:00
( Move the pointer to the left )
2021-11-13 16:08:21 +00:00
LIT '< !~ ,&movl JCN [ .ptr LDZ2k DEC2 ROT STZ2 POP RTN ] &movl
2021-11-13 15:57:54 +00:00
( Increment the memory cell at the pointer )
2021-11-13 16:08:21 +00:00
LIT '+ !~ ,&incr JCN [ .ptr LDZ2 STH2k LDA INC STH2r STA POP RTN ] &incr
2021-11-13 15:57:54 +00:00
( Decrement the memory cell at the pointer )
2021-11-13 16:08:21 +00:00
LIT '- !~ ,&decr JCN [ .ptr LDZ2 STH2k LDA DEC STH2r STA POP RTN ] &decr
2021-11-13 15:57:54 +00:00
( Output the character signified by the cell at the pointer )
2021-11-13 16:08:21 +00:00
LIT '. !~ ,&emit JCN [ .ptr LDZ2 LDA EMIT POP RTN ] &emit
2021-11-13 15:57:54 +00:00
( Jump past the matching ] if the cell at the pointer is 0 )
LIT '[ !~ ,&next JCN [ POP ,goto-next JSR RTN ] &next
2021-11-13 15:57:54 +00:00
( Jump back to the matching [ if the cell at the pointer is nonzero )
LIT '] !~ ,&prev JCN [ POP ,goto-back JSR RTN ] &prev
2021-11-13 02:51:39 +00:00
POP
RTN
@goto-next ( -- )
2021-11-13 16:08:21 +00:00
.ptr LDZ2 LDA #00 EQU JMP RTN
2021-11-13 02:51:39 +00:00
( depth ) LITr 00
INC2
&loop
2021-11-13 16:08:21 +00:00
LDAk LIT '[ NEQ JMP INCr
2021-11-13 02:51:39 +00:00
LDAk LIT '] NEQ ,&no-end JCN
STHkr #00 EQU ,&end JCN
DECr
&no-end
INC2 LDAk ,&loop JCN
&end
( depth ) POPr
RTN
@goto-back ( -- )
2021-11-13 16:08:21 +00:00
.ptr LDZ2 LDA #00 NEQ JMP RTN
2021-11-13 02:51:39 +00:00
( depth ) LITr 00
DEC2
&loop
2021-11-13 16:08:21 +00:00
LDAk LIT '] NEQ JMP INCr
2021-11-13 02:51:39 +00:00
LDAk LIT '[ NEQ ,&no-end JCN
STHkr #00 EQU ,&end JCN
DECr
&no-end
DEC2 LDAk ,&loop JCN
&end
( depth ) POPr
RTN
@program ( Hello World! )
"++++++++[>++++[>++>+++>+++>+<<<<
"-]>+>+>->>+[<]<-]>>.>---.+++++++
"..+++.>>.<-.<.+++.------.-------
"-.>>+.>++.