I have recently written a Brainfuck interpreter in C#. I tested it with the examples given on EsoLang website. It does not handle errors right now.
Questions:
- Even that it can run only one program at once, should I maybe put the variables into the class (create new class) or just leave them inside the
BF
method? - Should I split all of the code from the cases and create separate methods for them, accessing them from the
switch
?
Of course, I am also looking for all other suggestions on how I can improve this code.
using System;
namespace BF
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length == 0) {
Console.WriteLine("Specify the source file!");
} else {
if (System.IO.File.Exists(args[0]) == true) {
BF(System.IO.File.ReadAllText(args[0]).ToCharArray());
} else {
Console.WriteLine("The path to the file is not valid!");
}
}
}
private static void BF(char[] instructions)
{
int instructionPointer = 0;
int[] memory = new int[30000];
int pointer = 1;
while (instructionPointer < instructions.Length) {
switch (instructions[instructionPointer]) {
case '>': {
pointer += 1;
break;
}
case '<': {
pointer -= 1;
break;
}
case '+': {
memory[pointer] += 1;
break;
}
case '-': {
memory[pointer] -= 1;
break;
}
case '.': {
Console.Write((char)memory[pointer]);
break;
}
case ',': {
memory[pointer] = byte.Parse(Console.Read().ToString());
break;
}
case '[':
{
if (memory[pointer] == 0) {
int s = 0;
int ptr = instructionPointer + 1;
while (instructions[ptr] != ']' || s > 0) {
if (instructions[ptr] == '[') {
s += 1;
} else if (instructions[ptr] == ']') {
s -= 1;
}
ptr += 1;
instructionPointer = ptr;
}
}
break;
}
case ']': {
if (memory[pointer] != 0) {
int s = 0;
int ptr = instructionPointer - 1;
while (instructions[ptr] != '[' || s > 0) {
if (instructions[ptr] == ']') {
s += 1;
} else if (instructions[ptr] == '[') {
s -= 1;
}
ptr -= 1;
instructionPointer = ptr;
}
}
break;
}
}
instructionPointer += 1;
}
}
}
}