Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.

Below are links to each of the versions of RCBF.

An implementation need only properly implement the following instructions:



Command

Description


 > 
 Move the pointer to the right


 < 
 Move the pointer to the left


 + 
 Increment the memory cell under the pointer


 - 
 Decrement the memory cell under the pointer


 . 
 Output the character signified by the cell at the pointer


 , 
 Input a character and store it in the cell at the pointer


 [ 
 Jump past the matching ] if the cell under the pointer is 0


 ] 
 Jump back to the matching [ if the cell under the pointer is nonzero

Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.




class Brainfu_k {
  @program : String; @mem : Int[];
  @ip : Int;  @dp : Int;
 
  New(program : String, size : Int) {
    @program := program;
    @mem := Int → New[size];  
  }
 
  function : Main(args : String[]) ~ Nil {
    if(args → Size() = 2) {
      Brainfu_k → New(args[0], args[1] → ToInt()) → Execute();
    };
  }
 
  method : Execute() ~ Nil {
    while(@ip < @program → Size()) {
      instr := @program → Get(@ip);
      select(instr) {
        label '>': { @dp += 1; }
        label '<': { @dp -= 1; }
        label '+': { @mem[@dp] := @mem[@dp] + 1; }
        label '-': { @mem[@dp] := @mem[@dp] - 1; }
        label '.': { value := @mem[@dp] → As(Char); value → Print(); }        
        label ',': { @mem[@dp] := Read(); }
        label '[': { JumpForward(); }
        label ']': { JumpBack(); }
      };
      @ip += 1;
    };
  }
 
  method : JumpForward() ~ Nil {  
    depth := 1;
    if(@mem[@dp] = 0) {
      while(@ip < @program → Size()) {
        instr := @program → Get(@ip);
        if(instr = ']') {
          depth -= 1;  if(depth = 0) { return;  };  
        }
        else if(instr = '[') { depth += 1; };
        @ip += 1;
      };
      "*** Unbalanced jump ***" → ErrorLine();
      Runtime → Exit(1);
    };
  }
 
  method : JumpBack() ~ Nil {    
    depth := 1;
    if(@mem[@dp] <> 0) {
      while(@ip > 0) {
        @ip -= 1;
        instr := @program → Get(@ip);
        if(instr = '[') {
          depth -= 1;  if(depth = 0) { return; };
        }
        else if(instr = ']') { depth += 1; };
      };
      "*** Unbalanced jump ***" → ErrorLine();
      Runtime → Exit(1);
    };
  }
 
  method : Read() ~ Int {    
    in := IO.Console → ReadString();
    if(in → Size() > 0) { return in → ToInt(); };
    return 0;
  }
}