1 module parse; 2 3 import brainfuck; 4 import input_stream; 5 6 BrainfuckInstruction[] parse_brainfuck(string code) { 7 code ~= "\u0000"; 8 return parse_block(new InputStream!(immutable char)(code), '\u0000'); 9 } 10 11 BrainfuckInstruction[] parse_block(InputStream!(immutable char) stream, char delimiter) { 12 BrainfuckInstruction[] insts; 13 char first_char = stream.read(); 14 15 while(first_char != delimiter) { 16 switch(first_char) { 17 case '+': 18 case '-': 19 auto amt = first_char == '+' ? 1 : -1; 20 21 auto c = cast(char) stream.read(); 22 while(c == '+' || c == '-') { 23 amt += c == '+' ? 1 : -1; 24 c = stream.read(); 25 } 26 27 insts ~= new Modify(amt); 28 stream.seek(-1); 29 break; 30 case '>': 31 case '<': 32 auto amt = first_char == '>' ? 1 : -1; 33 34 auto c = cast(char) stream.read(); 35 while(c == '>' || c == '<') { 36 amt += c == '>' ? 1 : -1; 37 c = stream.read(); 38 } 39 40 insts ~= new Select(amt); 41 stream.seek(-1); 42 break; 43 case '[': 44 insts ~= new Loop(parse_block(stream, ']')); 45 break; 46 case ',': 47 insts ~= new Input(); 48 break; 49 case '.': 50 insts ~= new Output(); 51 break; 52 default: 53 break; 54 } 55 56 first_char = stream.read(); 57 } 58 return insts; 59 }