예제 #1
0
def repl(input_: str = ''):
    print("""
        ______           _        __            _                  
        | ___ \         (_)      / _|          | |                 
        | |_/ /_ __ __ _ _ _ __ | |_ _   _  ___| | __  _ __  _   _ 
        | ___ \ '__/ _` | | '_ \|  _| | | |/ __| |/ / | '_ \| | | |
        | |_/ / | | (_| | | | | | | | |_| | (__|   < _| |_) | |_| |
        \____/|_|  \__,_|_|_| |_|_|  \__,_|\___|_|\_(_) .__/ \__, |
                                                      | |     __/ |
                                                      |_|    |___/ 

        Welcome to the Brainfuck interpreter :)
        Written in Python 3 by @franciscocid (on Github!)
        Repo: https://github.com/franciscocid/brainfuckpy

    """)
    while True:
        try:
            repl_code = input('Input: ')
            brain = Brainfuck()
            result = brain.run(repl_code, input_)
            print('Output:', result)
        except (EOFError, KeyboardInterrupt):
            print("...Exiting...")
            exit(0)
        except Exception as e:
            print(e)
            raise e
 def __init__(self, mutationRate, crossoverRate, generationCnt, basePop,
              baseLen):
     self.mutationRate = mutationRate
     self.crossoverRate = crossoverRate
     self.generations = generationCnt
     self.bf = Brainfuck()
     self.symbols = ['+', '-', '>', '<', '.', '[', ']']
     self.desiredOutput = "Hello Me!"
     self.sampleInput = []
     self.basePop = basePop
     self.baseLen = baseLen
예제 #3
0
	def fitness(self, individual): #Override our fitness function
		if hasattr(individual, 'fitness'):
			pass
		else:
			individual.fitness = 0
		brainfuck = Brainfuck()
		self.idxs = {i : x for i, x in enumerate(symbols)}
		code = ''.join([self.idxs[c] for c in individual.chromosomes])
		try:
			brainfuck.evaluate(code)
			res = brainfuck.output
			for n in list(res):
				if n in string.printable:
					individual.fitness += 1
				else:
					individual.fitness -= 2
			if individual.fitness >= 20:
				self.log("STRONG", individual)
				self.log("OUTPUT of %s" % id(individual), res)
		except Exception as e:
			print e

		return individual.fitness
예제 #4
0
class TestInterpreter(TestCase):

    def setUp(self):
        self.bf = Brainfuck()

    def test_multiple_programs_and_their_outputs(self):
        with open('test/res/lorem_ipsun.txt', 'r') as f:
            lorem_ipsun = f.read()
        cases = [
            ('print_input.b', 'hello world', 'hello world'),
            ('test.b', '', 'i\'m a test'),
            ('not_really_long.b', '', 'Well, that\'s a really and really long and massive bit of text, well, not much actually, but it\'s a nice way to see if things are going as they should.'),
            ('lorem_ipsun.b', '', lorem_ipsun),
        ]

        for file, args, output in cases:
            path: str = os.path.join('test', 'programs', file)
            with open(path, 'r') as code_file:
                code: str = code_file.read()
                self.assertEqual(self.bf.run(code, args), output)
예제 #5
0
import sys
import re
from brainfuck import Brainfuck


if __name__ == '__main__':

    argvs = sys.argv
    argc = len(argvs)

    if (argc != 2):
        print 'Usage: $ %s filename' % argvs[0]
        quit()


    f = open(argvs[1], 'r')
    lines = f.readlines()

    context = Brainfuck()
    for line in lines:
        if re.match(r'^#!', line):
            continue

        context.readScript(line)

    context.exe()

    print ""
    quit()

예제 #6
0
    def fetch(self, var):
        """ Fetch a variable by copying it to two locations
        on the stack, then poping one back and saving it in memory.
        """
        return self._sp() + \
               self._set_zero() + \
               var + \
               '[-' + self._sp() + '+' + '>+' + var + ']' + \
               self._sp() + \
               self._widen() + \
               self._widen() + \
               self.store(var)

    def store(self, var):
        """ Store the value currently on the stack to some var.
        """
        return self._squeeze() + \
               var + \
               self._set_zero() + \
               self._sp() + \
               '[-' + var + '+' + self._sp() + ']'

s = Stack()
code = s.push_const(2) + s.push_const(6) + s.subtract()
compiled = cmpl(code)
print code
print compiled
b = Brainfuck(compiled)
b.run(print_state=True, sleep_time=0.01)
class GeneticAlg(object):
    def __init__(self, mutationRate, crossoverRate, generationCnt, basePop,
                 baseLen):
        self.mutationRate = mutationRate
        self.crossoverRate = crossoverRate
        self.generations = generationCnt
        self.bf = Brainfuck()
        self.symbols = ['+', '-', '>', '<', '.', '[', ']']
        self.desiredOutput = "Hello Me!"
        self.sampleInput = []
        self.basePop = basePop
        self.baseLen = baseLen

    # def setVars(self, out, in):
    # 	self.desiredOutput = out
    # 	self.sampleInput = []

    def initGen(self):
        out = []
        for _ in range(self.basePop * 4):
            curr = []
            for i in range(self.baseLen):
                curr.append(random.choice(self.symbols))
            out.append("".join(curr))
        return out

    def crossover(self, code1, code2):
        return self.two_point_crossover(code1, code2)

    def one_point_crossover(self, code1, code2):
        split_point = random.randint(0, min(len(code1), len(code2)))
        # if isinstance(code1, tuple):
        # 	print(code1)
        # if isinstance(code2, tuple):
        # 	print(code2)
        return code1[:split_point] + code2[
            split_point:], code2[:split_point] + code1[split_point:]

    def two_point_crossover(self, code1, code2):
        split_point1 = random.randint(0, min(len(code1), len(code2)))
        split_point2 = random.randint(0, min(len(code1), len(code2)))
        while split_point1 == split_point2:
            split_point2 = random.randint(0, min(len(code1), len(code2)))

        c1 = code1[:split_point1] + code2[split_point1:split_point2] + code1[
            split_point2:]
        c2 = code2[:split_point1] + code1[split_point1:split_point2] + code2[
            split_point1:]

        return c1, c2

    def in_mutate(self, code):
        rand = random.randint(0, len(code))
        return code[:rand] + random.choice(self.symbols) + code[rand:]

    def sub_mutate(self, code):
        w = list(code)
        w[random.randint(0, len(code) - 1)] = random.choice(self.symbols)
        return "".join(w)

    def del_mutate(self, code):
        rand = random.randint(0, len(code))
        return code[:rand] + code[rand + 1:]

    def fitness(self, output):
        if not output:
            return float("-inf")
        fitness = 0
        # if len(output) < len(self.desiredOutput):
        # 	output += "\x01"*(len(self.desiredOutput) - len(output))
        for i in range(min(len(output), len(self.desiredOutput))):
            fitness += 256 - (abs(ord(output[i]) - ord(self.desiredOutput[i])))
        fitness -= .05 * abs(len(output) - len(self.desiredOutput))
        # if len(output) < len(self.desiredOutput):
        # 	fitness -= sum(ord(w) for w in "\x01"*(len(self.desiredOutput) - len(output)))
        # if len(output) > len(self.desiredOutput):
        # 	fitness -= sum([ord(x) for x in output[len(self.desiredOutput):]][50:])
        return fitness

    # def weighted_choice(self, choices):
    # 	total = sum(w for c, w in choices)
    # 	r = random.uniform(0, total)
    # 	upto = 0
    # 	for c, w in choices:
    # 		if upto + w >= r:
    # 			return c
    # 		upto += w
    # choice = random.choice(choices)
    # while random.random() > (choice[1]/total):
    # 	choice = random.choice(choices)
    # return choice

    # def rank_selection(self, size):
    # 	 w = random.randint(0, size-1)
    # 	 i = 1
    # 	 while i <= w

    def pickOne(self, len, totalF):
        randNum = random.random() * totalF
        i = 1
        while i <= len:
            randNum -= i
            if randNum <= 0:
                return i - 1
            i += 1
        return len - 1

    def runOne(self, pop):
        pop = [(c, w) for c, w in pop if w > float("-inf")]

        nextPop = [pop[-1][0]]
        totalF = (self.basePop * (self.basePop + 1)) / 2

        output_hash = {}
        output_set = set()

        while len(nextPop) < self.basePop:  #len(pop):
            gene1 = pop[self.pickOne(len(pop), totalF)][0]
            gene2 = pop[self.pickOne(len(pop), totalF)][0]
            while gene1 == gene2:
                gene2 = pop[self.pickOne(len(pop), totalF)][0]

            if random.random() < self.crossoverRate:
                gene1, gene2 = self.crossover(gene1, gene2)

            for fn in [self.in_mutate, self.sub_mutate, self.del_mutate]:
                if random.random() < self.mutationRate:
                    gene1 = fn(gene1)
                if random.random() < self.mutationRate:
                    gene2 = fn(gene2)

            to_add = []
            for gene in [gene1, gene2]:
                g_out = self.bf.runProgram(gene, self.sampleInput)
                if g_out and g_out[:len(self.desiredOutput)] not in output_set:
                    g_out = g_out[:len(self.desiredOutput)]
                    output_set.add(g_out)
                    output_hash[gene] = g_out
                    to_add.append(gene)

            nextPop.extend(to_add)


#			nextPop.extend([gene1, gene2])

        return sorted([(c, self.fitness(output_hash[c])) for c in nextPop],
                      key=lambda x: x[1])

    def run(self):
        pop = [(c, self.fitness(c)) for c in self.initGen() + [
            "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
        ]]
        best_code = max(pop, key=lambda x: x[1])[0]
        print(pop)
        i = 0
        while self.bf.runProgram(
                best_code) != self.desiredOutput and i < self.generations:
            #pdb.set_trace()
            pop = self.runOne(pop)
            best_code, w = pop[-1]  #max(pop, key=lambda x: x[1])
            print("-------------------------")
            print(pop)
            print(best_code)
            print(w)
            #			print(self.bf.runProgram(best_code))
            print("-------------------------")
            i += 1

        return best_code
예제 #8
0
 def __init__(self, source, strict_parsing = False):
     """At this point strict parsing does not work!  AVOID AVOID AVOID"""
     self.strict_parsing = strict_parsing
     Brainfuck.__init__(self, self.__convert(source))
예제 #9
0
 def setUp(self):
     self.bf = Brainfuck()
예제 #10
0
파일: main.py 프로젝트: hugolundin/pybf
    if args.log:
        if args.log == LOG_TO_STDOUT:
            logging.basicConfig(stream=sys.stdout,
                                format='%(asctime)s: %(message)s',
                                datefmt='%Y-%m-%d %H:%M:%S',
                                level=logging.INFO)
        else:
            logging.basicConfig(filename='{}'.format(args.log),
                                filemode='w',
                                format='%(asctime)s: %(message)s',
                                datefmt='%Y-%m-%d %H:%M:%S',
                                level=logging.INFO)

    if not args.file:
        brainfuck = Brainfuck()

        while True:
            instructions = input('> ')
            brainfuck.interpret(instructions)
            print(brainfuck.memory)

    if args.file:
        brainfuck = Brainfuck(
            "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>123+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
        )
        try:
            brainfuck.run()
        except KeyboardInterrupt:
            pass
예제 #11
0
from brainfuck import Brainfuck
from util.logger import setup_logs
from repl import repl
import argparse, logging

arg_parser = argparse.ArgumentParser(prog='bf', description='Brainfuck VM')
arg_parser.add_argument('source', nargs='?', help='Source file')
arg_parser.add_argument('--input', nargs='*', help='Input text')
arg_parser.add_argument('--log',
                        action='store_true',
                        help='Display logs on stdout')
args = arg_parser.parse_args()

if args.log:
    setup_logs()

input_: str = ' '.join(args.input) if args.input else ''

if args.source:
    logging.info('Loading from source: ' + args.source)

    brain = Brainfuck()
    with open(args.source, 'r') as f:
        result = brain.run(f.read(), input_=input_)
        print(result)
else:
    logging.info('Setting up REPL...')
    repl(input_=input_)
예제 #12
0
from brainfuck import Brainfuck

t1_code = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."

print('-' * 125)
print("Test 1: Hello World Program")
print("Code:", t1_code)
print("Result: ", end='')

Brainfuck(t1_code)
print('-' * 125)