created react app but not actually started doing anything nice

This commit is contained in:
nora 2021-06-18 16:11:51 +02:00
parent 812e492640
commit 3ee494fed9
39 changed files with 12654 additions and 925 deletions

View file

@ -1,13 +1,13 @@
# brainfuck
Brainfuck interpreters in different languages
Finished:
- Rust
- Java
WIP:
To-Do:
- Haskell
- TypeScript
- (JavaScript)
# brainfuck
Brainfuck interpreters in different languages
Finished:
- Rust
- Java
WIP:
To-Do:
- Haskell
- TypeScript
- (JavaScript)

View file

@ -1,2 +1,2 @@
.idea
.idea
.stack-work

16
bfi-haskell/.idea/.gitignore generated vendored
View file

@ -1,8 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/../../../../../../../:\Users\nilsh\IdeaProjects\brainfuck\bfi-haskell\.idea/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/../../../../../../../:\Users\nilsh\IdeaProjects\brainfuck\bfi-haskell\.idea/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/

View file

@ -1,11 +1,11 @@
<component name="libraryTable">
<library name="base-4.14.1.0">
<CLASSES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/base-4.14.1.0" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/base-4.14.1.0" />
</SOURCES>
</library>
<component name="libraryTable">
<library name="base-4.14.1.0">
<CLASSES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/base-4.14.1.0" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/base-4.14.1.0" />
</SOURCES>
</library>
</component>

View file

@ -1,11 +1,11 @@
<component name="libraryTable">
<library name="ghc-prim-0.6.1">
<CLASSES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/ghc-prim-0.6.1" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/ghc-prim-0.6.1" />
</SOURCES>
</library>
<component name="libraryTable">
<library name="ghc-prim-0.6.1">
<CLASSES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/ghc-prim-0.6.1" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/ghc-prim-0.6.1" />
</SOURCES>
</library>
</component>

View file

@ -1,11 +1,11 @@
<component name="libraryTable">
<library name="integer-gmp-1.0.3.0">
<CLASSES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/integer-gmp-1.0.3.0" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/integer-gmp-1.0.3.0" />
</SOURCES>
</library>
<component name="libraryTable">
<library name="integer-gmp-1.0.3.0">
<CLASSES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/integer-gmp-1.0.3.0" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="file://$USER_HOME$/AppData/Local/rikvdkleij/intellij-haskell/cache/lib/bfi-haskell/integer-gmp-1.0.3.0" />
</SOURCES>
</library>
</component>

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Haskell Tool Stack" project-jdk-type="Haskell Tool Stack SDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Haskell Tool Stack" project-jdk-type="Haskell Tool Stack SDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View file

@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/bfi-haskell.iml" filepath="$PROJECT_DIR$/bfi-haskell.iml" />
</modules>
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/bfi-haskell.iml" filepath="$PROJECT_DIR$/bfi-haskell.iml" />
</modules>
</component>
</project>

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View file

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="HASKELL_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/app" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/.stack-work" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="base-4.14.1.0" level="project" />
<orderEntry type="library" name="ghc-prim-0.6.1" level="project" />
<orderEntry type="library" name="integer-gmp-1.0.3.0" level="project" />
</component>
<?xml version="1.0" encoding="UTF-8"?>
<module type="HASKELL_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/app" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/.stack-work" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="base-4.14.1.0" level="project" />
<orderEntry type="library" name="ghc-prim-0.6.1" level="project" />
<orderEntry type="library" name="integer-gmp-1.0.3.0" level="project" />
</component>
</module>

View file

@ -1,11 +1,11 @@
++++++++++[>++++++++++<-]>>++++++++++>->>>>>>>>>>>>>>>>-->+++++++[->++
++++++++<]>[->+>+>+>+<<<<]+++>>+++>>>++++++++[-<++++<++++<++++>>>]++++
+[-<++++<++++>>]>>-->++++++[->+++++++++++<]>[->+>+>+>+<<<<]+++++>>+>++
++++>++++++>++++++++[-<++++<++++<++++>>>]++++++[-<+++<+++<+++>>>]>>-->
---+[-<+]-<[+[->+]-<<->>>+>[-]++[-->++]-->+++[---++[--<++]---->>-<+>[+
+++[----<++++]--[>]++[-->++]--<]>++[--+[-<+]->>[-]+++++[---->++++]-->[
->+<]>>[.>]++[-->++]]-->+++]---+[-<+]->>-[+>>>+[-<+]->>>++++++++++<<[-
>+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>
+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->+++
+++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]+[-<+]->>]+[-]<<<.>>>+[
++++++++++[>++++++++++<-]>>++++++++++>->>>>>>>>>>>>>>>>-->+++++++[->++
++++++++<]>[->+>+>+>+<<<<]+++>>+++>>>++++++++[-<++++<++++<++++>>>]++++
+[-<++++<++++>>]>>-->++++++[->+++++++++++<]>[->+>+>+>+<<<<]+++++>>+>++
++++>++++++>++++++++[-<++++<++++<++++>>>]++++++[-<+++<+++<+++>>>]>>-->
---+[-<+]-<[+[->+]-<<->>>+>[-]++[-->++]-->+++[---++[--<++]---->>-<+>[+
+++[----<++++]--[>]++[-->++]--<]>++[--+[-<+]->>[-]+++++[---->++++]-->[
->+<]>>[.>]++[-->++]]-->+++]---+[-<+]->>-[+>>>+[-<+]->>>++++++++++<<[-
>+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>
+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->+++
+++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]+[-<+]->>]+[-]<<<.>>>+[
-<+]-<<]

View file

@ -1,111 +1,111 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class Brainfuck {
private static final int MEM_SIZE = 0xFFFF;
public List<Character> minify(String program) {
List<Character> chars = List.of('>', '<', '+', '-', '.', ',', '[', ']');
return program.chars()
.mapToObj(c -> (char) c)
.filter(chars::contains)
.collect(Collectors.toList());
}
public String interpret(List<Character> pgm) {
StringBuilder out = new StringBuilder();
int pointer = 0;
short[] memory = new short[MEM_SIZE];
int pc = 0;
while (pc < pgm.size()) {
switch (pgm.get(pc)) {
case '>' -> {
if (pointer == MEM_SIZE - 1) {
pointer = 0;
} else {
pointer++;
}
}
case '<' -> {
if (pointer == 0) {
pointer = MEM_SIZE - 1;
} else {
pointer--;
}
}
case '+' -> increment(memory, pointer);
case '-' -> decrement(memory, pointer);
case '.' -> {
out.append((char) memory[pointer]);
}
case ',' -> {
} //todo implement i guess
case '[' -> {
if (memory[pointer] == 0) {
int level = 0;
while (pgm.get(pc) != ']' || level > -1) {
pc++;
char instruction = pgm.get(pc);
if (instruction == '[') level++;
else if (instruction == ']') level--;
}
}
}
case ']' -> { //error lies here
if (memory[pointer] != 0) {
int level = 0;
while (pgm.get(pc) != '[' || level > -1) {
pc--;
char instruction = pgm.get(pc);
if (instruction == '[') level--;
else if (instruction == ']') level++;
}
}
}
}
pc++;
}
return out.toString();
}
private void increment(short[] memory, int pointer) {
if (memory[pointer] == 0xFF) {
memory[pointer] = 0;
} else {
memory[pointer]++;
}
}
private void decrement(short[] memory, int pointer) {
if (memory[pointer] == 0) {
memory[pointer] = 0xFF;
} else {
memory[pointer]--;
}
}
public static void main(String[] args) throws IOException {
Brainfuck brainfuck = new Brainfuck();
if (args.length < 1) {
System.out.println("Please specify a path");
return;
}
String program = Files.readString(Paths.get(args[0]));
List<Character> minified = brainfuck.minify(program);
long time1 = System.currentTimeMillis();
String result = brainfuck.interpret(minified);
long time = System.currentTimeMillis() - time1;
System.out.println(result);
System.out.println("Finished execution in " + time + "ms");
}
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class Brainfuck {
private static final int MEM_SIZE = 0xFFFF;
public List<Character> minify(String program) {
List<Character> chars = List.of('>', '<', '+', '-', '.', ',', '[', ']');
return program.chars().parallel()
.mapToObj(c -> (char) c)
.filter(chars::contains)
.collect(Collectors.toList());
}
public String interpret(List<Character> pgm) {
StringBuilder out = new StringBuilder();
int pointer = 0;
short[] memory = new short[MEM_SIZE];
int pc = 0;
while (pc < pgm.size()) {
switch (pgm.get(pc)) {
case '>' -> {
if (pointer == MEM_SIZE - 1) {
pointer = 0;
} else {
pointer++;
}
}
case '<' -> {
if (pointer == 0) {
pointer = MEM_SIZE - 1;
} else {
pointer--;
}
}
case '+' -> increment(memory, pointer);
case '-' -> decrement(memory, pointer);
case '.' -> {
out.append((char) memory[pointer]);
}
case ',' -> {
} //todo implement i guess
case '[' -> {
if (memory[pointer] == 0) {
int level = 0;
while (pgm.get(pc) != ']' || level > -1) {
pc++;
char instruction = pgm.get(pc);
if (instruction == '[') level++;
else if (instruction == ']') level--;
}
}
}
case ']' -> { //error lies here
if (memory[pointer] != 0) {
int level = 0;
while (pgm.get(pc) != '[' || level > -1) {
pc--;
char instruction = pgm.get(pc);
if (instruction == '[') level--;
else if (instruction == ']') level++;
}
}
}
}
pc++;
}
return out.toString();
}
private void increment(short[] memory, int pointer) {
if (memory[pointer] == 0xFF) {
memory[pointer] = 0;
} else {
memory[pointer]++;
}
}
private void decrement(short[] memory, int pointer) {
if (memory[pointer] == 0) {
memory[pointer] = 0xFF;
} else {
memory[pointer]--;
}
}
public static void main(String[] args) throws IOException {
Brainfuck brainfuck = new Brainfuck();
if (args.length < 1) {
System.out.println("Please specify a path");
return;
}
String program = Files.readString(Paths.get(args[0]));
List<Character> minified = brainfuck.minify(program);
long time1 = System.currentTimeMillis();
String result = brainfuck.interpret(minified);
long time = System.currentTimeMillis() - time1;
System.out.println(result);
System.out.println("Finished execution in " + time + "ms");
}
}

8
bfi-rust/.gitignore vendored
View file

@ -1,5 +1,5 @@
/target
.idea
# brainfuck testing code, get your own
*.b
/target
.idea
# brainfuck testing code, get your own
*.b
*.bf

View file

@ -1,13 +1,13 @@
[package]
name = "bfinterpreter"
version = "0.1.1"
authors = ["Nilstrieb <nilstrieb@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[profile.dev]
[package]
name = "bfinterpreter"
version = "0.1.1"
authors = ["Nilstrieb <nilstrieb@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[profile.dev]
opt-level = 3

View file

@ -1,96 +1,96 @@
use crate::interpreter::optimized::PrintMode;
use std::str::Chars;
pub mod simple;
pub mod parsed;
pub mod optimized;
pub const MEM_SIZE: usize = 0xFFFF;
pub type Memory = [u8; MEM_SIZE];
#[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Clone)]
pub enum Statement {
Inc,
Dec,
R,
L,
Out,
DOut,
In,
Loop(Vec<Statement>),
}
const ALLOWED_CHARS: [char; 8] = ['>', '<', '+', '-', '.', ',', '[', ']'];
pub fn minify(code: &str) -> String {
code.chars().filter(|c| ALLOWED_CHARS.contains(c)).collect()
}
pub fn parse(chars: Chars, print_mode: PrintMode) -> Vec<Statement> {
let mut loop_stack = vec![vec![]];
for c in chars {
match c {
'+' => loop_stack.last_mut().unwrap().push(Statement::Inc),
'-' => loop_stack.last_mut().unwrap().push(Statement::Dec),
'>' => loop_stack.last_mut().unwrap().push(Statement::R),
'<' => loop_stack.last_mut().unwrap().push(Statement::L),
'.' => {
match print_mode {
PrintMode::ToString => loop_stack.last_mut().unwrap().push(Statement::Out),
PrintMode::DirectPrint => loop_stack.last_mut().unwrap().push(Statement::DOut)
}
}
',' => loop_stack.last_mut().unwrap().push(Statement::In),
'[' => loop_stack.push(vec![]),
']' => {
let statement = Statement::Loop(loop_stack.pop().unwrap());
loop_stack.last_mut().unwrap().push(statement);
}
_ => ()
}
}
loop_stack.pop().unwrap()
}
#[cfg(test)]
mod tests {
use crate::interpreter::{parse, minify};
use crate::interpreter::Statement::{Dec, In, Inc, L, Loop, Out, R};
#[test]
fn minify_test() {
let program = "sdahf+saga-46<sgbv>a[r]r.hr,e";
let expected = "+-<>[].,";
assert_eq!(String::from(expected), minify(program));
}
#[test]
fn parse_no_loop() {
let program = "+-<>,.";
let statements = vec![Inc, Dec, L, R, In, Out];
let result = parse(program.chars().collect(), false);
assert_eq!(statements, result);
}
#[test]
fn parse_simple_loop() {
let program = "+[<<]-";
let statements = vec![Inc, Loop(vec![L, L]), Dec];
let result = parse(program.chars().collect(), false);
assert_eq!(statements, result);
}
#[test]
fn parse_complex_loops() {
let program = ">[<[][<[<]>]>[>]]";
let statements = vec![R, Loop(vec![L, Loop(vec![]), Loop(vec![L, Loop(vec![L]), R]), R, Loop(vec![R])])];
let result = parse(program.chars().collect(), false);
assert_eq!(statements, result);
}
use crate::interpreter::optimized::PrintMode;
use std::str::Chars;
pub mod simple;
pub mod parsed;
pub mod optimized;
pub const MEM_SIZE: usize = 0xFFFF;
pub type Memory = [u8; MEM_SIZE];
#[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Clone)]
pub enum Statement {
Inc,
Dec,
R,
L,
Out,
DOut,
In,
Loop(Vec<Statement>),
}
const ALLOWED_CHARS: [char; 8] = ['>', '<', '+', '-', '.', ',', '[', ']'];
pub fn minify(code: &str) -> String {
code.chars().filter(|c| ALLOWED_CHARS.contains(c)).collect()
}
pub fn parse(chars: Chars, print_mode: PrintMode) -> Vec<Statement> {
let mut loop_stack = vec![vec![]];
for c in chars {
match c {
'+' => loop_stack.last_mut().unwrap().push(Statement::Inc),
'-' => loop_stack.last_mut().unwrap().push(Statement::Dec),
'>' => loop_stack.last_mut().unwrap().push(Statement::R),
'<' => loop_stack.last_mut().unwrap().push(Statement::L),
'.' => {
match print_mode {
PrintMode::ToString => loop_stack.last_mut().unwrap().push(Statement::Out),
PrintMode::DirectPrint => loop_stack.last_mut().unwrap().push(Statement::DOut)
}
}
',' => loop_stack.last_mut().unwrap().push(Statement::In),
'[' => loop_stack.push(vec![]),
']' => {
let statement = Statement::Loop(loop_stack.pop().unwrap());
loop_stack.last_mut().unwrap().push(statement);
}
_ => ()
}
}
loop_stack.pop().unwrap()
}
#[cfg(test)]
mod tests {
use crate::interpreter::{parse, minify};
use crate::interpreter::Statement::{Dec, In, Inc, L, Loop, Out, R};
#[test]
fn minify_test() {
let program = "sdahf+saga-46<sgbv>a[r]r.hr,e";
let expected = "+-<>[].,";
assert_eq!(String::from(expected), minify(program));
}
#[test]
fn parse_no_loop() {
let program = "+-<>,.";
let statements = vec![Inc, Dec, L, R, In, Out];
let result = parse(program.chars().collect(), false);
assert_eq!(statements, result);
}
#[test]
fn parse_simple_loop() {
let program = "+[<<]-";
let statements = vec![Inc, Loop(vec![L, L]), Dec];
let result = parse(program.chars().collect(), false);
assert_eq!(statements, result);
}
#[test]
fn parse_complex_loops() {
let program = ">[<[][<[<]>]>[>]]";
let statements = vec![R, Loop(vec![L, Loop(vec![]), Loop(vec![L, Loop(vec![L]), R]), R, Loop(vec![R])])];
let result = parse(program.chars().collect(), false);
assert_eq!(statements, result);
}
}

View file

@ -1,229 +1,229 @@
//! # optimization time
//! some better optimizations like set null, repeating and doing more stuff with simplifying stuff
//!
mod patterns;
use std::io::{Read, stdin, Write};
use crate::interpreter::{minify, parse, Statement, Memory, MEM_SIZE};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fmt;
use std::ops::Deref;
#[derive(PartialOrd, PartialEq, Ord, Eq, Clone, Debug)]
enum ExStatement {
Inc,
Dec,
R,
L,
Out,
DOut,
In,
Loop(Vec<ExStatement>),
SetNull,
Repeat(Box<ExStatement>, usize),
_ForLoop(usize, Box<ExStatement>),
}
impl From<Statement> for ExStatement {
fn from(s: Statement) -> Self {
match s {
Statement::L => ExStatement::L,
Statement::R => ExStatement::R,
Statement::Inc => ExStatement::Inc,
Statement::Dec => ExStatement::Dec,
Statement::In => ExStatement::In,
Statement::Out => ExStatement::Out,
Statement::Loop(v) => ExStatement::Loop(
v.into_iter().map(ExStatement::from).collect()
),
Statement::DOut => ExStatement::DOut
}
}
}
#[derive(Debug)]
pub struct BfErr {
msg: &'static str,
}
impl BfErr {
pub fn new(msg: &'static str) -> BfErr {
BfErr { msg }
}
}
impl Display for BfErr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Error interpreting brainfuck code: {}", self.msg)
}
}
impl Error for BfErr {}
pub enum PrintMode {
ToString,
DirectPrint,
}
pub fn run(pgm: &str, print_mode: PrintMode) -> Result<String, BfErr> {
let pgm = minify(pgm);
if pgm.is_empty() { return Err(BfErr::new("no program found")); };
let pgm = parse(pgm.chars(), print_mode);
let pgm = optimize(&pgm);
let out = interpret(&pgm);
Ok(out)
}
fn optimize(code: &[Statement]) -> Vec<ExStatement> {
let code = o_set_null(code);
o_repeat(code)
}
fn o_set_null(code: &[Statement]) -> Vec<ExStatement> {
code.iter().map(|s| {
match s {
Statement::Loop(v) => {
if let [Statement::Dec] = v[..] {
ExStatement::SetNull
} else {
ExStatement::Loop(optimize(v))
}
}
Statement::Inc => ExStatement::Inc,
Statement::Dec => ExStatement::Dec,
Statement::R => ExStatement::R,
Statement::L => ExStatement::L,
Statement::Out => ExStatement::Out,
Statement::DOut => ExStatement::DOut,
Statement::In => ExStatement::In,
}
}).collect()
}
fn o_repeat(code: Vec<ExStatement>) -> Vec<ExStatement> {
let mut amount = 0;
let mut result: Vec<ExStatement> = vec![];
for i in 0..code.len() {
if code.get(i) == code.get(i + 1) {
amount += 1;
} else if amount == 0 {
result.push(code[i].clone())
} else {
amount += 1;
result.push(ExStatement::Repeat(Box::new(code[i].clone()), amount as usize));
amount = 0;
}
}
result
}
fn interpret(pgm: &[ExStatement]) -> String {
let mut out = String::new();
let mut pointer: usize = 0;
let mut mem: [u8; MEM_SIZE] = [0; MEM_SIZE];
for s in pgm {
execute(s, &mut mem, &mut pointer, &mut out)
}
out
}
fn execute(statement: &ExStatement, mem: &mut Memory, pointer: &mut usize, out: &mut String) {
match statement {
ExStatement::R => if *pointer == MEM_SIZE - 1 { *pointer = 0 } else { *pointer += 1 },
ExStatement::L => if *pointer == 0 { *pointer = MEM_SIZE - 1 } else { *pointer -= 1 },
ExStatement::Inc => mem[*pointer] = mem[*pointer].wrapping_add(1),
ExStatement::Dec => mem[*pointer] = mem[*pointer].wrapping_sub(1),
ExStatement::SetNull => mem[*pointer] = 0,
ExStatement::Out => out.push(mem[*pointer] as u8 as char),
ExStatement::DOut => {
print!("{}", mem[*pointer] as u8 as char);
std::io::stdout().flush().unwrap();
}
ExStatement::In => {
let mut in_buffer = [0, 1];
stdin().read_exact(&mut in_buffer).unwrap();
mem[*pointer] = in_buffer[0] as u8;
}
ExStatement::Loop(vec) => {
while mem[*pointer] != 0 {
for s in vec {
execute(&s, mem, pointer, out);
}
}
}
ExStatement::Repeat(statement, amount) => {
match statement.deref() {
ExStatement::R => {
*pointer += amount;
if *pointer > MEM_SIZE {
*pointer %= MEM_SIZE
}
}
ExStatement::L => *pointer = (*pointer).wrapping_sub(*amount),
ExStatement::Inc => mem[*pointer] = mem[*pointer].wrapping_add(*amount as u8),
ExStatement::Dec => mem[*pointer] = mem[*pointer].wrapping_sub(*amount as u8),
ExStatement::Loop(v) => {
for _ in 0..*amount {
execute(&ExStatement::Loop(v.clone()), mem, pointer, out)
}
}
s => {
for _ in 0..*amount {
execute(s, mem, pointer, out)
}
}
}
}
ExStatement::_ForLoop(offset, statement) => {
*pointer += offset;
while mem[*pointer - offset] != 0 {
execute(statement, mem, pointer, out);
}
}
};
}
#[cfg(test)]
mod test {
use crate::interpreter::optimized::{run, o_repeat};
use crate::interpreter::optimized::ExStatement::{Inc, Repeat, R, L, Dec};
#[test]
fn run_loop() {
let program = "++++++++++[>++++++++++<-]>.";
let out = run(program, false).unwrap();
assert_eq!(out, String::from("d"));
}
#[test]
fn hello_world() {
let program = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
let out = run(program, false).unwrap();
assert_eq!(out, String::from("Hello World!\n"));
}
#[test]
fn o_repeat_simple() {
let code = vec![Inc, Inc, Inc, R];
let expected = vec![Repeat(Box::new(Inc), 3), R];
println!("{}", code.len());
assert_eq!(expected, o_repeat(code));
}
#[test]
fn o_repeat_long() {
let code = vec![Inc, Inc, Inc, R, L, L, L, Dec, L, L, Dec];
let expected = vec![Repeat(Box::new(Inc), 3), R, Repeat(Box::new(L), 3), Dec, Repeat(Box::new(L), 2), Dec];
assert_eq!(expected, o_repeat(code));
}
}
//! # optimization time
//! some better optimizations like set null, repeating and doing more stuff with simplifying stuff
//!
mod patterns;
use std::io::{Read, stdin, Write};
use crate::interpreter::{minify, parse, Statement, Memory, MEM_SIZE};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fmt;
use std::ops::Deref;
#[derive(PartialOrd, PartialEq, Ord, Eq, Clone, Debug)]
enum ExStatement {
Inc,
Dec,
R,
L,
Out,
DOut,
In,
Loop(Vec<ExStatement>),
SetNull,
Repeat(Box<ExStatement>, usize),
_ForLoop(usize, Box<ExStatement>),
}
impl From<Statement> for ExStatement {
fn from(s: Statement) -> Self {
match s {
Statement::L => ExStatement::L,
Statement::R => ExStatement::R,
Statement::Inc => ExStatement::Inc,
Statement::Dec => ExStatement::Dec,
Statement::In => ExStatement::In,
Statement::Out => ExStatement::Out,
Statement::Loop(v) => ExStatement::Loop(
v.into_iter().map(ExStatement::from).collect()
),
Statement::DOut => ExStatement::DOut
}
}
}
#[derive(Debug)]
pub struct BfErr {
msg: &'static str,
}
impl BfErr {
pub fn new(msg: &'static str) -> BfErr {
BfErr { msg }
}
}
impl Display for BfErr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Error interpreting brainfuck code: {}", self.msg)
}
}
impl Error for BfErr {}
pub enum PrintMode {
ToString,
DirectPrint,
}
pub fn run(pgm: &str, print_mode: PrintMode) -> Result<String, BfErr> {
let pgm = minify(pgm);
if pgm.is_empty() { return Err(BfErr::new("no program found")); };
let pgm = parse(pgm.chars(), print_mode);
let pgm = optimize(&pgm);
let out = interpret(&pgm);
Ok(out)
}
fn optimize(code: &[Statement]) -> Vec<ExStatement> {
let code = o_set_null(code);
o_repeat(code)
}
fn o_set_null(code: &[Statement]) -> Vec<ExStatement> {
code.iter().map(|s| {
match s {
Statement::Loop(v) => {
if let [Statement::Dec] = v[..] {
ExStatement::SetNull
} else {
ExStatement::Loop(optimize(v))
}
}
Statement::Inc => ExStatement::Inc,
Statement::Dec => ExStatement::Dec,
Statement::R => ExStatement::R,
Statement::L => ExStatement::L,
Statement::Out => ExStatement::Out,
Statement::DOut => ExStatement::DOut,
Statement::In => ExStatement::In,
}
}).collect()
}
fn o_repeat(code: Vec<ExStatement>) -> Vec<ExStatement> {
let mut amount = 0;
let mut result: Vec<ExStatement> = vec![];
for i in 0..code.len() {
if code.get(i) == code.get(i + 1) {
amount += 1;
} else if amount == 0 {
result.push(code[i].clone())
} else {
amount += 1;
result.push(ExStatement::Repeat(Box::new(code[i].clone()), amount as usize));
amount = 0;
}
}
result
}
fn interpret(pgm: &[ExStatement]) -> String {
let mut out = String::new();
let mut pointer: usize = 0;
let mut mem: [u8; MEM_SIZE] = [0; MEM_SIZE];
for s in pgm {
execute(s, &mut mem, &mut pointer, &mut out)
}
out
}
fn execute(statement: &ExStatement, mem: &mut Memory, pointer: &mut usize, out: &mut String) {
match statement {
ExStatement::R => if *pointer == MEM_SIZE - 1 { *pointer = 0 } else { *pointer += 1 },
ExStatement::L => if *pointer == 0 { *pointer = MEM_SIZE - 1 } else { *pointer -= 1 },
ExStatement::Inc => mem[*pointer] = mem[*pointer].wrapping_add(1),
ExStatement::Dec => mem[*pointer] = mem[*pointer].wrapping_sub(1),
ExStatement::SetNull => mem[*pointer] = 0,
ExStatement::Out => out.push(mem[*pointer] as u8 as char),
ExStatement::DOut => {
print!("{}", mem[*pointer] as u8 as char);
std::io::stdout().flush().unwrap();
}
ExStatement::In => {
let mut in_buffer = [0, 1];
stdin().read_exact(&mut in_buffer).unwrap();
mem[*pointer] = in_buffer[0] as u8;
}
ExStatement::Loop(vec) => {
while mem[*pointer] != 0 {
for s in vec {
execute(&s, mem, pointer, out);
}
}
}
ExStatement::Repeat(statement, amount) => {
match statement.deref() {
ExStatement::R => {
*pointer += amount;
if *pointer > MEM_SIZE {
*pointer %= MEM_SIZE
}
}
ExStatement::L => *pointer = (*pointer).wrapping_sub(*amount),
ExStatement::Inc => mem[*pointer] = mem[*pointer].wrapping_add(*amount as u8),
ExStatement::Dec => mem[*pointer] = mem[*pointer].wrapping_sub(*amount as u8),
ExStatement::Loop(v) => {
for _ in 0..*amount {
execute(&ExStatement::Loop(v.clone()), mem, pointer, out)
}
}
s => {
for _ in 0..*amount {
execute(s, mem, pointer, out)
}
}
}
}
ExStatement::_ForLoop(offset, statement) => {
*pointer += offset;
while mem[*pointer - offset] != 0 {
execute(statement, mem, pointer, out);
}
}
};
}
#[cfg(test)]
mod test {
use crate::interpreter::optimized::{run, o_repeat};
use crate::interpreter::optimized::ExStatement::{Inc, Repeat, R, L, Dec};
#[test]
fn run_loop() {
let program = "++++++++++[>++++++++++<-]>.";
let out = run(program, false).unwrap();
assert_eq!(out, String::from("d"));
}
#[test]
fn hello_world() {
let program = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
let out = run(program, false).unwrap();
assert_eq!(out, String::from("Hello World!\n"));
}
#[test]
fn o_repeat_simple() {
let code = vec![Inc, Inc, Inc, R];
let expected = vec![Repeat(Box::new(Inc), 3), R];
println!("{}", code.len());
assert_eq!(expected, o_repeat(code));
}
#[test]
fn o_repeat_long() {
let code = vec![Inc, Inc, Inc, R, L, L, L, Dec, L, L, Dec];
let expected = vec![Repeat(Box::new(Inc), 3), R, Repeat(Box::new(L), 3), Dec, Repeat(Box::new(L), 2), Dec];
assert_eq!(expected, o_repeat(code));
}
}

View file

@ -1,43 +1,43 @@
//!
//! # Patterns find and replace
//! Pattern-match ExStatements and replace them with optimizations like add, multiply etc
use crate::interpreter::optimized::ExStatement;
///
/// Replace this: `[>>x<<-]` or `[->>x<<]` with `WhileAdd(2, x)`
fn _for_loop(to_test: ExStatement) -> ExStatement {
match to_test {
ExStatement::Loop(v) => {
match v[..] {
[ExStatement::R, ExStatement::Inc, ExStatement::L, ExStatement::Dec] => {
ExStatement::_ForLoop(1, Box::from(ExStatement::Inc))
}
_ => ExStatement::Loop(v)
}
},
s => s
}
}
#[cfg(test)]
mod test {
use crate::interpreter::optimized::ExStatement::{Out, Loop, Inc, R, L, Dec, _ForLoop};
use crate::interpreter::optimized::patterns::_for_loop;
#[test]
fn for_loop_false() {
let statement = Loop(vec![Out, Inc]);
assert_eq!(statement.clone(), _for_loop(statement));
}
#[test]
fn for_loop_simplest() {
let statement = Loop(vec![R, Inc, L, Dec]);
assert_eq!(_ForLoop(1, Box::from(Inc)), _for_loop(statement));
}
//!
//! # Patterns find and replace
//! Pattern-match ExStatements and replace them with optimizations like add, multiply etc
use crate::interpreter::optimized::ExStatement;
///
/// Replace this: `[>>x<<-]` or `[->>x<<]` with `WhileAdd(2, x)`
fn _for_loop(to_test: ExStatement) -> ExStatement {
match to_test {
ExStatement::Loop(v) => {
match v[..] {
[ExStatement::R, ExStatement::Inc, ExStatement::L, ExStatement::Dec] => {
ExStatement::_ForLoop(1, Box::from(ExStatement::Inc))
}
_ => ExStatement::Loop(v)
}
},
s => s
}
}
#[cfg(test)]
mod test {
use crate::interpreter::optimized::ExStatement::{Out, Loop, Inc, R, L, Dec, _ForLoop};
use crate::interpreter::optimized::patterns::_for_loop;
#[test]
fn for_loop_false() {
let statement = Loop(vec![Out, Inc]);
assert_eq!(statement.clone(), _for_loop(statement));
}
#[test]
fn for_loop_simplest() {
let statement = Loop(vec![R, Inc, L, Dec]);
assert_eq!(_ForLoop(1, Box::from(Inc)), _for_loop(statement));
}
}

View file

@ -1,122 +1,122 @@
//!
//! # optimization time
//!
//! first parse the bf so that it can be executed faster
//! most importantly: loop jumps should be immediate
#![allow(dead_code)]
use std::io::{Read, stdin, Write};
use crate::interpreter::{MEM_SIZE, Memory, minify, parse, Statement};
use crate::interpreter::optimized::PrintMode;
use crate::repl::BrainfuckState;
pub fn run(pgm: &str) -> String {
let pgm = minify(pgm);
let pgm = parse(pgm.chars(), PrintMode::ToString);
interpret(&pgm)
}
fn interpret(pgm: &[Statement]) -> String {
let mut out = String::new();
let mut pointer: usize = 0;
let mut mem: [u8; MEM_SIZE] = [0; MEM_SIZE];
for s in pgm {
execute(s, &mut mem, &mut pointer, &mut out)
}
out
}
pub fn interpret_with_state(pgm: &[Statement], state: &mut BrainfuckState) {
for s in pgm {
execute(s, &mut state.memory, &mut state.pointer, &mut String::new())
}
}
fn execute(statement: &Statement, mem: &mut Memory, pointer: &mut usize, out: &mut String) {
match statement {
Statement::R => if *pointer == MEM_SIZE - 1 { *pointer = 0 } else { *pointer += 1 },
Statement::L => if *pointer == 0 { *pointer = MEM_SIZE - 1 } else { *pointer -= 1 },
Statement::Inc => mem[*pointer] = mem[*pointer].wrapping_add(1),
Statement::Dec => mem[*pointer] = mem[*pointer].wrapping_sub(1),
Statement::Out => out.push(mem[*pointer] as u8 as char),
Statement::In => {
let mut in_buffer = [0, 1];
stdin().read_exact(&mut in_buffer).unwrap();
mem[*pointer] = in_buffer[0] as u8;
}
Statement::Loop(vec) => {
while mem[*pointer] != 0 {
for s in vec {
execute(&s, mem, pointer, out);
}
}
}
Statement::DOut => {
print!("{}", mem[*pointer] as u8 as char);
std::io::stdout().flush().unwrap();
}
}
}
#[cfg(test)]
mod test {
use crate::interpreter::parsed::{execute, run, Statement};
#[test]
fn execute_simple() {
let mut pointer: usize = 0;
let mut mem: [u8; 65535] = [0; 65535];
let mut out = String::new();
execute(&Statement::R, &mut mem, &mut pointer, &mut out);
assert_eq!(pointer, 1);
execute(&Statement::L, &mut mem, &mut pointer, &mut out);
assert_eq!(pointer, 0);
execute(&Statement::Inc, &mut mem, &mut pointer, &mut out);
assert_eq!(mem[pointer], 1);
execute(&Statement::Dec, &mut mem, &mut pointer, &mut out);
assert_eq!(mem[pointer], 0);
}
#[test]
fn execute_false_loop() {
let statement = Statement::Loop(vec![Statement::Inc, Statement::Inc, Statement::R]);
let mut pointer: usize = 0;
let mut mem: [u8; 65535] = [0; 65535];
execute(&statement, &mut mem, &mut pointer, &mut String::new());
assert_eq!(mem[0], 0);
assert_eq!(mem[1], 0);
}
#[test]
fn execute_loop() {
let statement = Statement::Loop(vec![Statement::Inc, Statement::Inc, Statement::R]);
let mut pointer: usize = 0;
let mut mem: [u8; 65535] = [0; 65535];
mem[0] = 1;
execute(&statement, &mut mem, &mut pointer, &mut String::new());
assert_eq!(mem[0], 3);
assert_eq!(mem[1], 0);
}
#[test]
fn run_loop() {
let program = "++++++++++[>++++++++++<-]>.";
let out = run(program);
assert_eq!(out, String::from("d"));
}
#[test]
fn hello_world() {
let program = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
let out = run(program);
assert_eq!(out, String::from("Hello World!\n"));
}
//!
//! # optimization time
//!
//! first parse the bf so that it can be executed faster
//! most importantly: loop jumps should be immediate
#![allow(dead_code)]
use std::io::{Read, stdin, Write};
use crate::interpreter::{MEM_SIZE, Memory, minify, parse, Statement};
use crate::interpreter::optimized::PrintMode;
use crate::repl::BrainfuckState;
pub fn run(pgm: &str) -> String {
let pgm = minify(pgm);
let pgm = parse(pgm.chars(), PrintMode::ToString);
interpret(&pgm)
}
fn interpret(pgm: &[Statement]) -> String {
let mut out = String::new();
let mut pointer: usize = 0;
let mut mem: [u8; MEM_SIZE] = [0; MEM_SIZE];
for s in pgm {
execute(s, &mut mem, &mut pointer, &mut out)
}
out
}
pub fn interpret_with_state(pgm: &[Statement], state: &mut BrainfuckState) {
for s in pgm {
execute(s, &mut state.memory, &mut state.pointer, &mut String::new())
}
}
fn execute(statement: &Statement, mem: &mut Memory, pointer: &mut usize, out: &mut String) {
match statement {
Statement::R => if *pointer == MEM_SIZE - 1 { *pointer = 0 } else { *pointer += 1 },
Statement::L => if *pointer == 0 { *pointer = MEM_SIZE - 1 } else { *pointer -= 1 },
Statement::Inc => mem[*pointer] = mem[*pointer].wrapping_add(1),
Statement::Dec => mem[*pointer] = mem[*pointer].wrapping_sub(1),
Statement::Out => out.push(mem[*pointer] as u8 as char),
Statement::In => {
let mut in_buffer = [0, 1];
stdin().read_exact(&mut in_buffer).unwrap();
mem[*pointer] = in_buffer[0] as u8;
}
Statement::Loop(vec) => {
while mem[*pointer] != 0 {
for s in vec {
execute(&s, mem, pointer, out);
}
}
}
Statement::DOut => {
print!("{}", mem[*pointer] as u8 as char);
std::io::stdout().flush().unwrap();
}
}
}
#[cfg(test)]
mod test {
use crate::interpreter::parsed::{execute, run, Statement};
#[test]
fn execute_simple() {
let mut pointer: usize = 0;
let mut mem: [u8; 65535] = [0; 65535];
let mut out = String::new();
execute(&Statement::R, &mut mem, &mut pointer, &mut out);
assert_eq!(pointer, 1);
execute(&Statement::L, &mut mem, &mut pointer, &mut out);
assert_eq!(pointer, 0);
execute(&Statement::Inc, &mut mem, &mut pointer, &mut out);
assert_eq!(mem[pointer], 1);
execute(&Statement::Dec, &mut mem, &mut pointer, &mut out);
assert_eq!(mem[pointer], 0);
}
#[test]
fn execute_false_loop() {
let statement = Statement::Loop(vec![Statement::Inc, Statement::Inc, Statement::R]);
let mut pointer: usize = 0;
let mut mem: [u8; 65535] = [0; 65535];
execute(&statement, &mut mem, &mut pointer, &mut String::new());
assert_eq!(mem[0], 0);
assert_eq!(mem[1], 0);
}
#[test]
fn execute_loop() {
let statement = Statement::Loop(vec![Statement::Inc, Statement::Inc, Statement::R]);
let mut pointer: usize = 0;
let mut mem: [u8; 65535] = [0; 65535];
mem[0] = 1;
execute(&statement, &mut mem, &mut pointer, &mut String::new());
assert_eq!(mem[0], 3);
assert_eq!(mem[1], 0);
}
#[test]
fn run_loop() {
let program = "++++++++++[>++++++++++<-]>.";
let out = run(program);
assert_eq!(out, String::from("d"));
}
#[test]
fn hello_world() {
let program = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
let out = run(program);
assert_eq!(out, String::from("Hello World!\n"));
}
}

View file

@ -1,71 +1,71 @@
//!
//! The very basic interpreter without any optimizations
#![allow(dead_code)]
use crate::interpreter::{MEM_SIZE, minify};
use std::io::{stdin, Read};
pub fn run(program: &str) -> String{
let program = minify(program);
let out = interpret(program.chars().collect());
out
}
fn interpret(pgm: Vec<char>) -> String {
let mut out = String::new();
let mut pointer: usize = 0;
let mut mem: [u8; MEM_SIZE] = [0; MEM_SIZE];
let mut in_buffer = [0; 1];
let mut pc = 0;
let len = pgm.len();
while pc < len {
match pgm[pc] {
'>' => if pointer == MEM_SIZE - 1 { pointer = 0 } else { pointer += 1 },
'<' => if pointer == 0 { pointer = MEM_SIZE - 1 } else { pointer -= 1 },
'+' => mem[pointer] = mem[pointer].wrapping_add(1),
'-' => mem[pointer] = mem[pointer].wrapping_sub(1),
'.' => out.push(mem[pointer] as u8 as char),
',' => {
stdin().read_exact(&mut in_buffer).unwrap();
mem[pointer] = in_buffer[0] as u8;
}
'[' => {
//jump to corresponding ]
if mem[pointer] == 0 {
let mut level = 0;
while pgm[pc] != ']' || level > -1 {
pc += 1;
match pgm[pc] {
'[' => {
level += 1
}
']' => {
level -= 1
}
_ => (),
}
}
}
}
']' => {
if mem[pointer] != 0 {
//jump to corresponding [
let mut level = 0;
while pgm[pc] != '[' || level > -1 {
pc -= 1;
match pgm[pc] {
'[' => level -= 1,
']' => level += 1,
_ => (),
}
}
}
}
_ => (),
}
pc += 1;
}
out
//!
//! The very basic interpreter without any optimizations
#![allow(dead_code)]
use crate::interpreter::{MEM_SIZE, minify};
use std::io::{stdin, Read};
pub fn run(program: &str) -> String{
let program = minify(program);
let out = interpret(program.chars().collect());
out
}
fn interpret(pgm: Vec<char>) -> String {
let mut out = String::new();
let mut pointer: usize = 0;
let mut mem: [u8; MEM_SIZE] = [0; MEM_SIZE];
let mut in_buffer = [0; 1];
let mut pc = 0;
let len = pgm.len();
while pc < len {
match pgm[pc] {
'>' => if pointer == MEM_SIZE - 1 { pointer = 0 } else { pointer += 1 },
'<' => if pointer == 0 { pointer = MEM_SIZE - 1 } else { pointer -= 1 },
'+' => mem[pointer] = mem[pointer].wrapping_add(1),
'-' => mem[pointer] = mem[pointer].wrapping_sub(1),
'.' => out.push(mem[pointer] as u8 as char),
',' => {
stdin().read_exact(&mut in_buffer).unwrap();
mem[pointer] = in_buffer[0] as u8;
}
'[' => {
//jump to corresponding ]
if mem[pointer] == 0 {
let mut level = 0;
while pgm[pc] != ']' || level > -1 {
pc += 1;
match pgm[pc] {
'[' => {
level += 1
}
']' => {
level -= 1
}
_ => (),
}
}
}
}
']' => {
if mem[pointer] != 0 {
//jump to corresponding [
let mut level = 0;
while pgm[pc] != '[' || level > -1 {
pc -= 1;
match pgm[pc] {
'[' => level -= 1,
']' => level += 1,
_ => (),
}
}
}
}
_ => (),
}
pc += 1;
}
out
}

View file

@ -1,37 +1,37 @@
mod interpreter;
mod repl;
use std::{env, fs};
use std::time::SystemTime;
use crate::repl::start_repl;
use crate::interpreter::optimized::{PrintMode};
use std::error::Error;
fn main() {
let path = env::args().nth(1);
match path {
Some(p) => {
if let Err(why) = run_program(p) {
eprintln!("An error occurred in the program: {}", why)
}
},
None => start_repl()
};
}
fn run_program(path: String) -> Result<(), Box<dyn Error>> {
let program = match fs::read_to_string(path) {
Ok(p) => p,
Err(e) => {
println!("Error reading file: {}", e);
return Err(Box::from(e));
}
};
let start_time = SystemTime::now();
let out = interpreter::optimized::run(&*program, PrintMode::DirectPrint)?;
let duration = start_time.elapsed()?;
println!("{}\nFinished execution. Took {}ms", out, duration.as_millis());
Ok(())
mod interpreter;
mod repl;
use std::{env, fs};
use std::time::SystemTime;
use crate::repl::start_repl;
use crate::interpreter::optimized::{PrintMode};
use std::error::Error;
fn main() {
let path = env::args().nth(1);
match path {
Some(p) => {
if let Err(why) = run_program(p) {
eprintln!("An error occurred in the program: {}", why)
}
},
None => start_repl()
};
}
fn run_program(path: String) -> Result<(), Box<dyn Error>> {
let program = match fs::read_to_string(path) {
Ok(p) => p,
Err(e) => {
println!("Error reading file: {}", e);
return Err(Box::from(e));
}
};
let start_time = SystemTime::now();
let out = interpreter::optimized::run(&*program, PrintMode::DirectPrint)?;
let duration = start_time.elapsed()?;
println!("{}\nFinished execution. Took {}ms", out, duration.as_millis());
Ok(())
}

View file

@ -1,111 +1,111 @@
use std::fmt::{Display, Formatter};
use std::fmt;
use std::io::{stdin, stdout, Write};
use crate::interpreter::{minify, parse, parsed, Memory, MEM_SIZE};
use crate::interpreter::optimized::PrintMode;
pub struct BrainfuckState {
pub memory: Memory,
pub pointer: usize,
}
impl Display for BrainfuckState {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", display_state(self))
}
}
fn display_state(state: &BrainfuckState) -> String {
let start = if state.pointer < 5 {
0
} else if state.pointer > MEM_SIZE - 10 {
MEM_SIZE - 10
} else {
state.pointer - 5
};
format!("{}-\n|{}|\n{}-\n{}|\n{}|\n{}|\n{}-\n {}^^^^",
"----------".repeat(10),
{
let mut out = String::new();
let end = start + 10;
for i in start..end {
out.push_str(&*format!(" {: >5} ", i));
}
out
},
"----------".repeat(10),
"| ".repeat(10),
{
let mut out = String::new();
let end = start + 10;
for i in start..end {
out.push_str(&*format!("| {: >3} ", state.memory[i]));
}
out
},
"| ".repeat(10),
"----------".repeat(10),
" ".repeat(state.pointer - start))
}
pub fn start_repl() {
println!("Brainfuck REPL");
let mut state = BrainfuckState {
memory: [0; MEM_SIZE],
pointer: 0,
};
println!("Enter Brainfuck programs and they will be executed immediatly.");
println!("State is kept.");
println!("{}", state);
loop {
print!(">> ");
stdout().flush().unwrap();
match read_line() {
Ok(s) => {
match &*s {
":q" => break,
":?" | "help" | "?" => print_help(),
":r" => {
reset(&mut state);
println!("{}", state);
},
_ => {
print!("Output: ");
println!();
parse_input(s, &mut state);
println!("{}", state);
}
}
}
Err(why) => println!("Error reading input: {}\nPlease try again.", why)
}
}
}
fn reset(state: &mut BrainfuckState) {
state.pointer = 0;
state.memory = [0; MEM_SIZE];
}
fn print_help() {
println!("Brainfuck REPL help
:q => quit
:? => help
:r => reset state");
}
fn parse_input(pgm: String, state: &mut BrainfuckState) {
let pgm = minify(&*pgm);
let pgm = parse(pgm.chars(), PrintMode::DirectPrint);
parsed::interpret_with_state(&*pgm, state);
}
pub fn read_line() -> Result<String, std::io::Error> {
let mut buf = String::new();
stdin().read_line(&mut buf)?;
buf.pop();
Ok(buf)
use std::fmt::{Display, Formatter};
use std::fmt;
use std::io::{stdin, stdout, Write};
use crate::interpreter::{minify, parse, parsed, Memory, MEM_SIZE};
use crate::interpreter::optimized::PrintMode;
pub struct BrainfuckState {
pub memory: Memory,
pub pointer: usize,
}
impl Display for BrainfuckState {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", display_state(self))
}
}
fn display_state(state: &BrainfuckState) -> String {
let start = if state.pointer < 5 {
0
} else if state.pointer > MEM_SIZE - 10 {
MEM_SIZE - 10
} else {
state.pointer - 5
};
format!("{}-\n|{}|\n{}-\n{}|\n{}|\n{}|\n{}-\n {}^^^^",
"----------".repeat(10),
{
let mut out = String::new();
let end = start + 10;
for i in start..end {
out.push_str(&*format!(" {: >5} ", i));
}
out
},
"----------".repeat(10),
"| ".repeat(10),
{
let mut out = String::new();
let end = start + 10;
for i in start..end {
out.push_str(&*format!("| {: >3} ", state.memory[i]));
}
out
},
"| ".repeat(10),
"----------".repeat(10),
" ".repeat(state.pointer - start))
}
pub fn start_repl() {
println!("Brainfuck REPL");
let mut state = BrainfuckState {
memory: [0; MEM_SIZE],
pointer: 0,
};
println!("Enter Brainfuck programs and they will be executed immediatly.");
println!("State is kept.");
println!("{}", state);
loop {
print!(">> ");
stdout().flush().unwrap();
match read_line() {
Ok(s) => {
match &*s {
":q" => break,
":?" | "help" | "?" => print_help(),
":r" => {
reset(&mut state);
println!("{}", state);
},
_ => {
print!("Output: ");
println!();
parse_input(s, &mut state);
println!("{}", state);
}
}
}
Err(why) => println!("Error reading input: {}\nPlease try again.", why)
}
}
}
fn reset(state: &mut BrainfuckState) {
state.pointer = 0;
state.memory = [0; MEM_SIZE];
}
fn print_help() {
println!("Brainfuck REPL help
:q => quit
:? => help
:r => reset state");
}
fn parse_input(pgm: String, state: &mut BrainfuckState) {
let pgm = minify(&*pgm);
let pgm = parse(pgm.chars(), PrintMode::DirectPrint);
parsed::interpret_with_state(&*pgm, state);
}
pub fn read_line() -> Result<String, std::io::Error> {
let mut buf = String::new();
stdin().read_line(&mut buf)?;
buf.pop();
Ok(buf)
}

23
ibfi-ts/.gitignore vendored Normal file
View file

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

70
ibfi-ts/README.md Normal file
View file

@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `yarn build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

38
ibfi-ts/package.json Normal file
View file

@ -0,0 +1,38 @@
{
"name": "ibfi-ts",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
ibfi-ts/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

43
ibfi-ts/public/index.html Normal file
View file

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
ibfi-ts/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
ibfi-ts/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View file

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View file

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

38
ibfi-ts/src/App.css Normal file
View file

@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

25
ibfi-ts/src/App.js Normal file
View file

@ -0,0 +1,25 @@
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;

8
ibfi-ts/src/App.test.js Normal file
View file

@ -0,0 +1,8 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

13
ibfi-ts/src/index.css Normal file
View file

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

17
ibfi-ts/src/index.js Normal file
View file

@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

1
ibfi-ts/src/logo.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View file

@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View file

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

11407
ibfi-ts/yarn.lock Normal file

File diff suppressed because it is too large Load diff