Compare commits
7 Commits
5af36d220e
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 0c6027cae2 | |||
| 845bb5f46e | |||
| e2a6de89bc | |||
| 6428a39791 | |||
| a8c5660460 | |||
| 683d45b865 | |||
| 5fa2d16ae1 |
2
.gitignore
vendored
2
.gitignore
vendored
@ -3,3 +3,5 @@
|
||||
.direnv
|
||||
cmake-build-debug
|
||||
cmake-build-release
|
||||
.cache/clangd/index
|
||||
result
|
||||
|
||||
@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.25)
|
||||
project(BrainfuckInterpreter)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
# find_package(Boost 1.81 COMPONENTS program_options REQUIRED)
|
||||
|
||||
@ -10,6 +11,7 @@ include_directories(include)
|
||||
add_executable(bfuck
|
||||
src/main.cpp
|
||||
src/lex.cpp
|
||||
src/interpret.cpp
|
||||
)
|
||||
|
||||
# target_link_libraries(lasm Boost::program_options)
|
||||
|
||||
1
HelloWorld.bf
Normal file
1
HelloWorld.bf
Normal file
@ -0,0 +1 @@
|
||||
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
|
||||
@ -1 +0,0 @@
|
||||
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.+++.
|
||||
1
compile_commands.json
Symbolic link
1
compile_commands.json
Symbolic link
@ -0,0 +1 @@
|
||||
./cmake-build-release/compile_commands.json
|
||||
100
flake.lock
generated
100
flake.lock
generated
@ -1,52 +1,15 @@
|
||||
{
|
||||
"nodes": {
|
||||
"devshell": {
|
||||
"inputs": {
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": "nixpkgs"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1705332421,
|
||||
"narHash": "sha256-USpGLPme1IuqG78JNqSaRabilwkCyHmVWY0M9vYyqEA=",
|
||||
"owner": "numtide",
|
||||
"repo": "devshell",
|
||||
"rev": "83cb93d6d063ad290beee669f4badf9914cc16ec",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "devshell",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1701680307,
|
||||
"narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=",
|
||||
"lastModified": 1731533236,
|
||||
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "4022d587cbbfd70fe950c1e2083a02621806a725",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-utils_2": {
|
||||
"inputs": {
|
||||
"systems": "systems_2"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1705309234,
|
||||
"narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
|
||||
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -57,59 +20,46 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1704161960,
|
||||
"narHash": "sha256-QGua89Pmq+FBAro8NriTuoO/wNaUtugt29/qqA8zeeM=",
|
||||
"lastModified": 1751180975,
|
||||
"narHash": "sha256-BKk4yDiXr4LdF80OTVqYJ53Q74rOcA/82EClXug8xsY=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "63143ac2c9186be6d9da6035fa22620018c85932",
|
||||
"rev": "a48741b083d4f36dd79abd9f760c84da6b4dc0e5",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixpkgs-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs_2": {
|
||||
"locked": {
|
||||
"lastModified": 1705566941,
|
||||
"narHash": "sha256-CLNtVRDA8eUPk+bxsCCZtRO0Cp+SpHdn1nNOLoFypLs=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "b06ff4bf8f4ad900fe0c2a61fc2946edc3a84be7",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixpkgs-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
"id": "nixpkgs",
|
||||
"type": "indirect"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"devshell": "devshell",
|
||||
"flake-utils": "flake-utils_2",
|
||||
"nixpkgs": "nixpkgs_2"
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": "nixpkgs",
|
||||
"rust-overlay": "rust-overlay"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"rust-overlay": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"lastModified": 1751251399,
|
||||
"narHash": "sha256-y+viCuy/eKKpkX1K2gDvXIJI/yzvy6zA3HObapz9XZ0=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "b22d5ee8c60ed1291521f2dde48784edd6bf695b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"systems_2": {
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
|
||||
254
flake.nix
254
flake.nix
@ -1,86 +1,246 @@
|
||||
{
|
||||
description = "C/C++ Environment";
|
||||
rec {
|
||||
description = "C++ Brainfuck Interpreter";
|
||||
|
||||
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
|
||||
inputs.flake-utils.url = "github:numtide/flake-utils";
|
||||
inputs.devshell.url = "github:numtide/devshell";
|
||||
inputs = {
|
||||
nixpkgs.url = "nixpkgs"; # Use nixpkgs from system registry
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
|
||||
rust-overlay.url = "github:oxalica/rust-overlay";
|
||||
rust-overlay.inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
|
||||
outputs = {
|
||||
self,
|
||||
nixpkgs,
|
||||
flake-utils,
|
||||
devshell,
|
||||
rust-overlay,
|
||||
}:
|
||||
# Create a shell (and possibly package) for each possible system, not only x86_64-linux
|
||||
flake-utils.lib.eachDefaultSystem (system: let
|
||||
pkgs = import nixpkgs {
|
||||
inherit system;
|
||||
config.allowUnfree = true; # For clion
|
||||
overlays = [devshell.overlays.default];
|
||||
config.allowUnfree = true;
|
||||
overlays = [
|
||||
rust-overlay.overlays.default
|
||||
];
|
||||
};
|
||||
inherit (pkgs) lib stdenv;
|
||||
|
||||
# ===========================================================================================
|
||||
# Define custom dependencies
|
||||
# ===========================================================================================
|
||||
|
||||
python = pkgs.python313.withPackages (p:
|
||||
with p; [
|
||||
pyside6
|
||||
ffmpeg-python
|
||||
matplotlib
|
||||
numpy
|
||||
]);
|
||||
|
||||
rust = pkgs.rust-bin.stable.latest.default.override {
|
||||
extensions = ["rust-src"]; # Include the Rust stdlib source (for IntelliJ)
|
||||
};
|
||||
|
||||
# NOTE: Usual 64 bit compilers that don't collide
|
||||
# 64 bit C/C++ compilers that don't collide (use the same libc)
|
||||
bintools = pkgs.wrapBintoolsWith {
|
||||
bintools = pkgs.bintools.bintools;
|
||||
bintools = pkgs.bintools.bintools; # Unwrapped bintools
|
||||
libc = pkgs.glibc;
|
||||
};
|
||||
gcc13 = pkgs.hiPrio (pkgs.wrapCCWith {
|
||||
cc = pkgs.gcc13.cc;
|
||||
gcc = pkgs.hiPrio (pkgs.wrapCCWith {
|
||||
cc = pkgs.gcc.cc; # Unwrapped gcc
|
||||
libc = pkgs.glibc;
|
||||
bintools = bintools;
|
||||
});
|
||||
clang16 = pkgs.wrapCCWith {
|
||||
cc = pkgs.clang_16.cc;
|
||||
clang = pkgs.wrapCCWith {
|
||||
cc = pkgs.clang.cc; # Unwrapped clang
|
||||
libc = pkgs.glibc;
|
||||
bintools = bintools;
|
||||
};
|
||||
|
||||
# NOTE: Multilib compilers that don't collide
|
||||
bintools_multi = pkgs.wrapBintoolsWith {
|
||||
bintools = pkgs.bintools.bintools; # Get the unwrapped bintools from the wrapper
|
||||
# Multilib C/C++ compilers that don't collide (use the same libc)
|
||||
bintools_multilib = pkgs.wrapBintoolsWith {
|
||||
bintools = pkgs.bintools.bintools; # Unwrapped bintools
|
||||
libc = pkgs.glibc_multi;
|
||||
};
|
||||
gcc13_multi = pkgs.hiPrio (pkgs.wrapCCWith {
|
||||
cc = pkgs.gcc13.cc; # Get the unwrapped gcc from the wrapper
|
||||
gcc_multilib = pkgs.hiPrio (pkgs.wrapCCWith {
|
||||
cc = pkgs.gcc.cc; # Unwrapped gcc
|
||||
libc = pkgs.glibc_multi;
|
||||
bintools = bintools_multi;
|
||||
bintools = bintools_multilib;
|
||||
});
|
||||
clang16_multi = pkgs.wrapCCWith {
|
||||
cc = pkgs.clang_16.cc;
|
||||
clang_multilib = pkgs.wrapCCWith {
|
||||
cc = pkgs.clang.cc; # Unwrapped clang
|
||||
libc = pkgs.glibc_multi;
|
||||
bintools = bintools_multi;
|
||||
bintools = bintools_multilib;
|
||||
};
|
||||
in {
|
||||
# devShell = pkgs.devshell.mkShell ...
|
||||
devShell = pkgs.devshell.mkShell {
|
||||
name = "C/C++ Environment";
|
||||
|
||||
packages = with pkgs; [
|
||||
# Compilers
|
||||
# ===========================================================================================
|
||||
# Specify dependencies
|
||||
# https://nixos.org/manual/nixpkgs/stable/#ssec-stdenv-dependencies-overview
|
||||
# Just for a "nix develop" shell, buildInputs can be used for everything.
|
||||
# ===========================================================================================
|
||||
|
||||
# Add dependencies to nativeBuildInputs if they are executed during the build:
|
||||
# - Those which are needed on $PATH during the build, for example cmake and pkg-config
|
||||
# - Setup hooks, for example makeWrapper
|
||||
# - Interpreters needed by patchShebangs for build scripts (with the --build flag), which can be the case for e.g. perl
|
||||
nativeBuildInputs = with pkgs; [
|
||||
# Languages:
|
||||
# python
|
||||
# rust
|
||||
bintools
|
||||
gcc13
|
||||
clang16
|
||||
# bintools_multi
|
||||
# gcc13_multi
|
||||
# clang15_multi
|
||||
gcc
|
||||
clang
|
||||
# bintools_multilib
|
||||
# gcc_multilib
|
||||
# clang_multilib
|
||||
|
||||
# Native buildinputs
|
||||
# C/C++:
|
||||
gdb
|
||||
valgrind
|
||||
gnumake
|
||||
cmake
|
||||
# nasm
|
||||
# pkg-config
|
||||
|
||||
# Development
|
||||
# bear # To generate compilation database
|
||||
gdb
|
||||
cling # To try out my bullshit implementations
|
||||
# doxygen # Generate docs + graphs
|
||||
# Qt:
|
||||
# qt6.wrapQtAppsHook # For the shellHook
|
||||
];
|
||||
|
||||
commands = [
|
||||
# {
|
||||
# name = "ide";
|
||||
# help = "Run clion for project";
|
||||
# command = "clion &>/dev/null ./ &";
|
||||
# }
|
||||
# Add dependencies to buildInputs if they will end up copied or linked into the final output or otherwise used at runtime:
|
||||
# - Libraries used by compilers, for example zlib
|
||||
# - Interpreters needed by patchShebangs for scripts which are installed, which can be the case for e.g. perl
|
||||
buildInputs = with pkgs; [
|
||||
# C/C++:
|
||||
# boost
|
||||
# sfml
|
||||
|
||||
# Qt:
|
||||
# qt6.qtbase
|
||||
# qt6.full
|
||||
];
|
||||
|
||||
# ===========================================================================================
|
||||
# Define buildable + installable packages
|
||||
# ===========================================================================================
|
||||
|
||||
package = stdenv.mkDerivation {
|
||||
inherit nativeBuildInputs buildInputs;
|
||||
pname = "bfuck";
|
||||
version = "1.0.0";
|
||||
src = ./.;
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin
|
||||
mv ./bfuck $out/bin
|
||||
'';
|
||||
};
|
||||
in rec {
|
||||
# Provide package for "nix build"
|
||||
defaultPackage = package;
|
||||
defaultApp = flake-utils.lib.mkApp {
|
||||
drv = defaultPackage;
|
||||
};
|
||||
|
||||
# Provide environment for "nix develop"
|
||||
devShell = pkgs.mkShell {
|
||||
inherit nativeBuildInputs buildInputs;
|
||||
name = description;
|
||||
|
||||
# =========================================================================================
|
||||
# Define environment variables
|
||||
# =========================================================================================
|
||||
|
||||
# Rust stdlib source:
|
||||
# RUST_SRC_PATH = "${rust}/lib/rustlib/src/rust/library";
|
||||
|
||||
# Custom dynamic libraries:
|
||||
# LD_LIBRARY_PATH = builtins.concatStringsSep ":" [
|
||||
# # Rust Bevy GUI app
|
||||
# "${pkgs.xorg.libX11}/lib"
|
||||
# "${pkgs.xorg.libXcursor}/lib"
|
||||
# "${pkgs.xorg.libXrandr}/lib"
|
||||
# "${pkgs.xorg.libXi}/lib"
|
||||
# "${pkgs.libGL}/lib"
|
||||
# ];
|
||||
|
||||
# Dynamic libraries from buildinputs:
|
||||
# LD_LIBRARY_PATH = nixpkgs.lib.makeLibraryPath buildInputs;
|
||||
|
||||
# =========================================================================================
|
||||
# Define shell environment
|
||||
# =========================================================================================
|
||||
|
||||
# Setup the shell when entering the "nix develop" environment (bash script).
|
||||
shellHook = let
|
||||
mkCmakeScript = type: let
|
||||
typeLower = lib.toLower type;
|
||||
in
|
||||
pkgs.writers.writeFish "cmake-${typeLower}.fish" ''
|
||||
cd $FLAKE_PROJECT_ROOT
|
||||
|
||||
echo "Removing build directory ./cmake-build-${typeLower}/"
|
||||
rm -rf ./cmake-build-${typeLower}
|
||||
|
||||
echo "Creating build directory"
|
||||
mkdir cmake-build-${typeLower}
|
||||
cd cmake-build-${typeLower}
|
||||
|
||||
echo "Running cmake"
|
||||
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE="${type}" -DCMAKE_EXPORT_COMPILE_COMMANDS="On" ..
|
||||
|
||||
echo "Linking compile_commands.json"
|
||||
cd ..
|
||||
ln -sf ./cmake-build-${typeLower}/compile_commands.json ./compile_commands.json
|
||||
'';
|
||||
|
||||
cmakeDebug = mkCmakeScript "Debug";
|
||||
cmakeRelease = mkCmakeScript "Release";
|
||||
|
||||
mkBuildScript = type: let
|
||||
typeLower = lib.toLower type;
|
||||
in
|
||||
pkgs.writers.writeFish "cmake-build.fish" ''
|
||||
cd $FLAKE_PROJECT_ROOT/cmake-build-${typeLower}
|
||||
|
||||
echo "Running cmake"
|
||||
cmake --build .
|
||||
'';
|
||||
|
||||
buildDebug = mkBuildScript "Debug";
|
||||
buildRelease = mkBuildScript "Release";
|
||||
|
||||
# Use this to specify commands that should be ran after entering fish shell
|
||||
initProjectShell = pkgs.writers.writeFish "init-shell.fish" ''
|
||||
echo "Entering \"${description}\" environment..."
|
||||
|
||||
# Determine the project root, used e.g. in cmake scripts
|
||||
set -g -x FLAKE_PROJECT_ROOT (git rev-parse --show-toplevel)
|
||||
|
||||
# Build the provided NixOS package
|
||||
abbr -a build "nix build -L"
|
||||
|
||||
# Rust Bevy:
|
||||
# abbr -a build-release-windows "CARGO_FEATURE_PURE=1 cargo xwin build --release --target x86_64-pc-windows-msvc"
|
||||
|
||||
# C/C++:
|
||||
abbr -a cmake-debug "${cmakeDebug}"
|
||||
abbr -a cmake-release "${cmakeRelease}"
|
||||
abbr -a build-debug "${buildDebug}"
|
||||
abbr -a build-release "${buildRelease}"
|
||||
'';
|
||||
in
|
||||
builtins.concatStringsSep "\n" [
|
||||
# Launch into pure fish shell
|
||||
''
|
||||
exec "$(type -p fish)" -C "source ${initProjectShell} && abbr -a menu '${pkgs.bat}/bin/bat "${initProjectShell}"'"
|
||||
''
|
||||
|
||||
# Qt: Launch into wrapped fish shell
|
||||
# ''
|
||||
# fishdir=$(mktemp -d)
|
||||
# makeWrapper "$(type -p fish)" "$fishdir/fish" "''${qtWrapperArgs[@]}"
|
||||
# exec "$fishdir/fish" -C "source ${initProjectShell} && abbr -a menu '${pkgs.bat}/bin/bat "${initProjectShell}"'"
|
||||
# ''
|
||||
];
|
||||
};
|
||||
});
|
||||
|
||||
53
include/interpret.hpp
Normal file
53
include/interpret.hpp
Normal file
@ -0,0 +1,53 @@
|
||||
#ifndef __INTERPRET_H_
|
||||
#define __INTERPRET_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <map>
|
||||
#include <functional>
|
||||
|
||||
/**
|
||||
* @brief Interpreter for a BrainFuck program
|
||||
*/
|
||||
class Interpreter {
|
||||
private:
|
||||
const std::map<char, std::function<void(Interpreter *)>> instruction_map = {
|
||||
{'>', &Interpreter::_increment_pointer},
|
||||
{'<', &Interpreter::_decrement_pointer},
|
||||
{'+', &Interpreter::_increment_value},
|
||||
{'-', &Interpreter::_decrement_value},
|
||||
{'.', &Interpreter::_print_value},
|
||||
{',', &Interpreter::_read_value},
|
||||
{'[', &Interpreter::_jump_forward_if_zero},
|
||||
{']', &Interpreter::_jump_backward_if_nonzero},
|
||||
};
|
||||
|
||||
// Runtime VM
|
||||
bool running;
|
||||
const std::string program;
|
||||
uint32_t program_counter;
|
||||
uint32_t pointer;
|
||||
std::vector<uint8_t> memory;
|
||||
|
||||
// These functions implement the BrainFuck statements
|
||||
auto _increment_pointer() -> void; // >
|
||||
auto _decrement_pointer() -> void; // <
|
||||
auto _increment_value() -> void; // +
|
||||
auto _decrement_value() -> void; // -
|
||||
auto _print_value() -> void; // .
|
||||
auto _read_value() -> void; // ,
|
||||
auto _jump_forward_if_zero() -> void; // [
|
||||
auto _jump_backward_if_nonzero() -> void; // ]
|
||||
|
||||
public:
|
||||
explicit Interpreter(std::string_view program);
|
||||
|
||||
// These functions control the interpreter flow
|
||||
auto abort() -> void;
|
||||
auto step() -> void;
|
||||
auto run() -> void;
|
||||
};
|
||||
|
||||
#endif
|
||||
@ -11,6 +11,6 @@
|
||||
*/
|
||||
bool lex_brainfuck_file(const std::string &path, std::string &tokens);
|
||||
|
||||
bool token_string_valid(std::string_view tokens);
|
||||
bool program_valid(const std::string_view tokens);
|
||||
|
||||
#endif
|
||||
153
src/interpret.cpp
Normal file
153
src/interpret.cpp
Normal file
@ -0,0 +1,153 @@
|
||||
#include "interpret.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
|
||||
//
|
||||
// Private functions
|
||||
//
|
||||
|
||||
static const constexpr uint8_t MIN_VALUE = static_cast<uint8_t>(0);
|
||||
static const constexpr uint8_t MAX_VALUE = static_cast<uint8_t>(-1);
|
||||
|
||||
auto Interpreter::_increment_pointer() -> void {
|
||||
if (pointer == std::numeric_limits<uint32_t>::max()) {
|
||||
std::cout << "Can't increment pointer: Max size reached!" << std::endl;
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
|
||||
pointer++;
|
||||
|
||||
// If our currently allocated memory is exceeded, double it
|
||||
if (pointer == memory.size()) {
|
||||
memory.resize(memory.size() * 2, MIN_VALUE);
|
||||
}
|
||||
}
|
||||
|
||||
auto Interpreter::_decrement_pointer() -> void {
|
||||
if (pointer == 0) {
|
||||
std::cout << "Can't decrement pointer: Min size reached!" << std::endl;
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
|
||||
pointer--;
|
||||
}
|
||||
|
||||
auto Interpreter::_increment_value() -> void {
|
||||
if (memory[pointer] == MAX_VALUE) {
|
||||
std::cout << "Can't increment value: Max value reached!" << std::endl;
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
|
||||
memory[pointer]++;
|
||||
}
|
||||
|
||||
auto Interpreter::_decrement_value() -> void {
|
||||
if (memory[pointer] == MIN_VALUE) {
|
||||
std::cout << "Can't decrement value: Min value reached!" << std::endl;
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
|
||||
memory[pointer]--;
|
||||
}
|
||||
|
||||
auto Interpreter::_print_value() -> void {
|
||||
std::cout << static_cast<uint8_t>(memory[pointer]) << std::endl;
|
||||
}
|
||||
|
||||
auto Interpreter::_read_value() -> void {
|
||||
char input;
|
||||
std::cin.get(input);
|
||||
|
||||
if (static_cast<uint8_t>(input) < MIN_VALUE || static_cast<uint8_t>(input) > MAX_VALUE) {
|
||||
std::cout << "Invalid input! Must be element of ["
|
||||
<< MIN_VALUE << ", " << MAX_VALUE
|
||||
<< "]!" << std::endl;
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
|
||||
memory[pointer] = static_cast<uint8_t>(input);
|
||||
}
|
||||
|
||||
auto Interpreter::_jump_forward_if_zero() -> void {
|
||||
if (memory[pointer] != MIN_VALUE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the corresponding ']'
|
||||
int32_t jump_counter = 0;
|
||||
for (uint32_t index = program_counter; index < program.size(); ++index) {
|
||||
if (program[index] == '[') {
|
||||
++jump_counter;
|
||||
} else if (program[index] == ']') {
|
||||
--jump_counter;
|
||||
}
|
||||
|
||||
if (jump_counter == 0) {
|
||||
program_counter = index; // PC gets incremented later
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto Interpreter::_jump_backward_if_nonzero() -> void {
|
||||
if (memory[pointer] == MIN_VALUE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the corresponding '['
|
||||
int32_t jump_counter = 0;
|
||||
for (uint32_t index = program_counter; index > 0; --index) {
|
||||
if (program[index] == '[') {
|
||||
++jump_counter;
|
||||
} else if (program[index] == ']') {
|
||||
--jump_counter;
|
||||
}
|
||||
|
||||
if (jump_counter == 0) {
|
||||
program_counter = index; // PC gets incremented later
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Public functions
|
||||
//
|
||||
|
||||
Interpreter::Interpreter(const std::string_view program)
|
||||
: running(false), program(program), program_counter(0), pointer(0), memory(1024, MIN_VALUE) {
|
||||
std::cout << "Initialized interpreter with program size " << program.size() << "!\n" << std::endl;
|
||||
}
|
||||
|
||||
auto Interpreter::abort() -> void {
|
||||
running = false;
|
||||
std::cout << "Program aborted!" << std::endl;
|
||||
}
|
||||
|
||||
auto Interpreter::step() -> void {
|
||||
if (program_counter == program.size()) {
|
||||
std::cout << "Program finished!" << std::endl;
|
||||
running = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const char instruction = program[program_counter];
|
||||
|
||||
// Execute the correct action in the VM
|
||||
instruction_map.at(instruction)(this);
|
||||
|
||||
++program_counter;
|
||||
}
|
||||
|
||||
auto Interpreter::run() -> void {
|
||||
running = true;
|
||||
while (running) {
|
||||
step();
|
||||
}
|
||||
}
|
||||
27
src/lex.cpp
27
src/lex.cpp
@ -3,6 +3,7 @@
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <algorithm>
|
||||
#include <stack>
|
||||
|
||||
bool lex_brainfuck_file(const std::string &path, std::string &tokens) {
|
||||
if (!tokens.empty()) {
|
||||
@ -29,19 +30,35 @@ bool lex_brainfuck_file(const std::string &path, std::string &tokens) {
|
||||
}
|
||||
input_stream.close();
|
||||
|
||||
if (!token_string_valid(tokens)) {
|
||||
if (!program_valid(tokens)) {
|
||||
std::cout << "Program is invalid!" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
std::cout << "Lexed BrainFuck program:\n" << tokens << std::endl;
|
||||
std::cout << "Lexed valid BrainFuck program:\n" << tokens << std::endl;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool token_string_valid(const std::string_view tokens) {
|
||||
bool program_valid(const std::string_view tokens) {
|
||||
// Check tokens
|
||||
std::string valid_tokens = "><+-.,[]";
|
||||
|
||||
return std::ranges::all_of(tokens.begin(), tokens.end(), [&valid_tokens](const char c){
|
||||
bool tokens_valid = std::ranges::all_of(tokens.begin(), tokens.end(), [&valid_tokens](const char c){
|
||||
return valid_tokens.find(c) != std::string::npos;
|
||||
});
|
||||
|
||||
// Check bracket balance
|
||||
std::stack<char> brackets;
|
||||
for (const char c : tokens) {
|
||||
if (c == '[') {
|
||||
brackets.push('[');
|
||||
} else if (c == ']') {
|
||||
if (brackets.top() == '[') {
|
||||
brackets.pop();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tokens_valid && brackets.empty();
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
#include "lex.hpp"
|
||||
#include "interpret.hpp"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
@ -9,7 +10,12 @@ int main(int argc, char **argv) {
|
||||
std::cout << "Running " << argv[1] << "...\n" << std::endl;
|
||||
|
||||
std::string tokens;
|
||||
lex_brainfuck_file(argv[1], tokens);
|
||||
if (!lex_brainfuck_file(argv[1], tokens)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
Interpreter interpreter(tokens);
|
||||
interpreter.run();
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user