#!/usr/bin/python
from sys import argv
from os import system
def help():
print(
"Usages: ./bf <options> <file>",
"Available Options:",
"-i: Intractive/REPL mode",
"-i <file>: Interprete the file",
"-c <file>: Compile the file",
"-o <code> -o <compiled>: Write compiled file in <compiled>",
"-h, --help: Shows this menu",
)
def getch():
return ord(input()[0])
def putch(char):
print(chr(char), end="", flush=True)
def interpete(code):
global array
global p
i = 0
while i < len(code):
c = code[i]
if not c in "+-<>,.[]":
i += 1
continue
if c == "+":
array[p] += 1
if c == "-":
array[p] -= 1
if c == "<":
p -= 1
if c == ">":
p += 1
if c == ",":
array[p] = getch()
if c == ".":
putch(array[p])
if c == "]":
if array[p] > 0:
b = 1
while b:
i -= 1
if code[i] == "[":
b -= 1
if code[i] == "]":
b += 1
i += 1
def intractive():
array = [0]*30000
p = 0
output = ""
while True:
code = input(">>> ")
while code.count("[") != code.count("]"):
code += input("... ")
interpete(code)
if "." in code:
print("")
def bf2c(code):
c_code = """
#include<stdio.h>
int main(){
char a[30000];
char *p = a;
"""
i = 0
while i < len(code):
c = code[i]
if not c in "+-<>,.[]":
i += 1
continue
if c == "+":
c_code += "*p++;"
#array[p] += 1
if c == "-":
c_code += "*p--;"
array[p] -= 1
if c == "<":
c_code += "p--;"
#p -= 1
if c == ">":
c_code += "p++;"
#p += 1
if c == ",":
c_code += "*p=getchar();"
#array[p] = getch()
if c == ".":
c_code += "putchar(*p);"
if c == "[":
c_code += "while(*p){"
if c == "]":
c_code += "}"
i += 1
c_code += "return 0;}"
return c_code
global array, p
array = [0]*30000
p = 0
args = len(argv)
if args == 1:
print("No input files run with -h or --help for help menu")
quit()
elif args == 2:
if argv[1][0] != "-":
code_file = argv[1]
if argv[1] == "-h":
help()
if argv[1] == "-i":
intractive()
elif args == 3:
mode = argv[1]
code_file = argv[2]
if mode == "-c":
output_file = code_file[:code_file.find(".")]
c_code = bf2c(open(code_file).read())
with open(output_file + ".c", "w") as f:
f.write(c_code)
system("gcc " + output_file + ".c -o " + output_file)
#system("rm "+output_file + ".c")
if mode == "-i":
interpete(open(code_file).read())
elif args == 5:
mode = argv[1]
code_file = argv[2]
if argv[3] == "-o":
output_file = argv[4]
if __name__ == "__main__":
pass