Writing a BF Compiler for .net (Part 3: pointer++ and pointer--)
The last posting gave an introduction to the concepts and we started looking at the memory[pointer]++/--
functions. Today is a quicky post to look at two other instructions, pointer++
and pointer--
or >
and <
in BF.
Unsurprisingly, these are extremely simple operations, requiring only 5 IL Commands:
IL_0000: ldsfld int16 BFHelloWorldCSharp.Program::pointer
IL_0005: ldc.i4.1
IL_0006: add
IL_0007: conv.i2
IL_0008: stsfld int16 BFHelloWorldCSharp.Program::pointer
ldsfld loads a static field onto the evaluation stack, ldc.i4.1 pushes the number 1 to the stack, add takes the two values from the stack and pushes the result back. conv.i2 converts the value on the stack (which is an Int32) to Int16 (2-Byte Int), pads it to be Int32 (as that is the smallest datatype possible on the stack) and pushes it back. stsfld then replaces the value in the static variable with the value from the stack.
As usual, pointer--
works the exact same way with the difference of using sub instead of add. One word of note: sub subtracts value2 from value1. While the order doesn't matter for add, it does for sub. Also note that add and sub do not detect overflow, so you can happily add 1 to Int16.MaxValue. If you want overflow checking, there is sub.ovf and add.ovf which throw an OverflowException.
With the 4 easy operations done, we will look at . and , next for input and output. Finally, we will look at [ and ]. After we have looked at the IL for each operation, we will write our compiler.
- Writing a BF Compiler for .Net