Anonymous user
Execute Brain****/D: Difference between revisions
Version 1 updated
(Move 2 alternate implementations from Execute Brain****. http://rosettacode.org/mw/index.php?title=Execute_Brain****&action=history) |
(Version 1 updated) |
||
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}
==
An implementation of Rosetta Code [[Brainfuck|BrainF*ck]] interpreter in [[D]].
Implement notes:
*Memory is represented by an [[associative array]], so that negative addresses are allowed, though it is not efficient.
*Input and output are in character mode, rather than in numerical.
*Nesting level is checked during parsing, and if loops/brackets are not matched, an error is thrown before executing the code.
<lang d>import core.stdc.stdio, core.stdc.stdlib, std.file;
alias void delegate() Act
__gshared char[int] mem
__gshared Act[char] cmd
▲int ptr ; // mem pointer
static this() {
cmd['>'] = { if (!(++ptr in mem)) mem[ptr] = 0
cmd['<'] = { if (!(--ptr in mem)) mem[ptr] = 0
cmd['+'] = { mem[ptr]
cmd['-'] = { mem[ptr]
cmd['.'] = {
cmd[','] = {
int c = getc(stdin);
mem[ptr] = cast(char)c;
}
void bf(in string code) {
int cp = 0
int nested = 0
Act bfAct() {
Act[] acts
while(cp < code.length)▼
case '[':▼
nested++ ;▼
acts ~= bfAct() ; // begin inner loop▼
▲ break ;
case ']': ▼
if(--nested < 0) throw new Exception("Unmatched Loops") ;▼
default:▼
▲ if(cc in cmd)
acts ~= cmd[cc] ;▼
//else ignore other non-command char▼
▲ }
return { foreach(x ; acts){x();} } ;▼
}▼
Act run = bfAct() ;▼
if(nested != 0) throw new Exception("Unmatched Loops") ;▼
run() ; // execute the whole bf program▼
printf("\n") ;▼
▲ while (cp < code.length) {
void main(string[] args) { // if no argument, demo code will be run, else ▼
▲ case '[':
else ▼
bf(">+++++++++[<+++++++++>-]<+.>+++[<----->-]"▼
"<.-.++++.>++++++[<------>-]<--.>++++++++["▼
break;
"<+++++++++>-]<+.>++[<++>-]<+.>++++++++[<-"▼
"-------->-]<------.>++++++[<++++++>-]<.>+"▼
nested--;
if (nested < 0)
return {
while (mem[ptr]) {
foreach (x; acts)
x();
};
▲ default:
if (cc in cmd)
▲ // else ignore other non-command char
}
}
return {
x();
};
▲ }
// reset memory
mem = null;
mem[0] = 0;
ptr = 0;
if (nested != 0)
}
</lang>▼
void main(in string[] args) {
// argument is treated as filename of bf source and executed.
if (args.length > 1) {
bf(readText(args[1]));
▲ } else {
++++[<------->-]<.");
}
▲}</lang>
== Implementation 2 ==
|