Tagged: interpreter

Just another brainfuck interpreter

Why?

Honestly, why not?

The entry point

Not much to tell:

static void Main(string[] args)
{
    var parser = new Parser("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.");

    var instructions = parser.Instructions;

    var interpreter = new Interpreter(instructions);

    interpreter.Interpret();
}

The container classes

Some data classes and enums:

public enum Tokens
    {
        MoveFwd,
        MoveBack,
        Incr,
        Decr,
        While,
        Print,
        Input,
        WhileEnd,
        WhileStart,
        Unknown
    }

    public class Instruction
    {
        public Tokens Token { get; set; }

        public override string ToString()
        {
            return Token.ToString();
        }
    }

    class While : Instruction
    {
        public While()
        {
            Token = Tokens.While; 
        }

        public List<Instruction> Instructions { get; set; } 
    }

A helper function

A function to translate a character token into a known token

private Tokens GetToken(char input)
{
    switch (input)
    {
        case '+':
            return Tokens.Incr;
        case '-':
            return Tokens.Decr;;
        case '<':
            return Tokens.MoveBack;
        case '>':
            return Tokens.MoveFwd;
        case '.':
            return Tokens.Print;
        case ',':
            return Tokens.Input;
        case '[':
            return Tokens.WhileStart;
        case ']':
            return Tokens.WhileEnd;
    }
    
Read more