How tristanmorgan/bfg works
Main Components
• Command-Line Entry Point: The main entry is in the cmd/bfg directory (main.go). This acts as the gateway where command line arguments are processed (e.g., choosing between eight-bit mode, pretty print, or version display) and which drives the overall execution.
• Parser Module: Located in the "parser" folder, this module is responsible for reading the Brainfuck source code, tokenising it (as seen in tokenise.go), and assembling an intermediate representation of the instructions (instruction.go).
• Optimizer & Transformation Layers: Within the parser module (including files like execute.go, print.go, etc.), patterns are recognized (e.g., replacements for repeated + or -, loop optimizations such as converting [-] into a set-to-zero command, pointer jumps, and even vector multiply or duplicate instructions). This indicates a two-step processing: first parsing/tokenization and then applying multiple optimizations before execution.
• Execution Engine: After parsing and optimizations, the interpreter executes the Brainfuck program. The execution part is integrated into the parser’s execute module (execute.go), where the optimized instructions are run, managing memory (with behavior like wrap-around at 65535 and EOF as -1) and I/O buffering.
• I/O and Buffering Subsystem: Buffered output logic is highlighted (flush on newline, after 200 chars, etc.) and there is configuration for using either signed int storage or 8-bit cells.
Relationships and Data Flow
• Start at the Command-Line Interface (CLI). The main function receives the Brainfuck source file and any optional arguments.
• The CLI passes the source to the Parser Module. Within parsing, the tokenisation process converts the raw Brainfuck code into tokens.
• Next, the Optimizer analyzes these tokens and applies several transformation rules based on patterns described in the README (e.g., repeated operations merged to a single command, loop boundaries precomputed).
• Once optimized, the control flows into the Execution Engine, which interprets the instructions, manages the memory tape, and handles I/O.
• The result is then output to STDOUT (or printed in a pretty format if the option is provided), with the buffering mechanism ensuring performance and timely output.
Architectural Patterns and Design Principles
• Modularity: The separation between the command interface (cmd directory) and the parsing/execution backend (parser directory) is central. This clear separation helps with understanding, testing, and maintaining the code.
• Optimise-Then-Execute: Emphasizing a two-phased processing model (parsing with optimization followed by execution) is a critical design principle.
• Configurability: Options provided via command-line flags (such as eight-bit execution) are integrated into the overall processing pipeline to alter behavior dynamically.