Jacob_DiDiodato

Brainf**k Interpreter [V0.7]

Nov 15th, 2017
288
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.18 KB | None | 0 0
  1. #! python 2.7
  2. """
  3. V: 0.7
  4. Brainf**k Compiler
  5. bfInterpreter06.py
  6. Last edit was Tuesday, November 14th, 2017
  7. Jacob DiDiodato
  8. An interpreter for the brainf**k language written by Urban Muller
  9. Supports the basic instructions for brainf**k as well as a few instructions I have implemented
  10.  
  11. Program size has been reduced by ~12 times from version 0.0
  12. This interpreter should not be used when time is tight as it does take a long time to execute most instructions
  13.  
  14. If you find any bugs with this interpreter please PM me with the error message and steps to recreate the problem
  15.  
  16. ----------------V0.7 PATCHNOTES----------------
  17. Made the program slightly more efficient by precalculating upper and lower bounds on tape increments.
  18. -> Takes slightly more time to compile
  19.  
  20. Ascii mandelbrot fractal took 286.495 seconds as opposed to 294.403 that it took with the last version
  21. -----------------------------------------------
  22.  
  23. Note: This program relies on you having and using Python 2.7. It is almost certain that this won't work on Python 3.X. If you are using Python 3.X and refuse/don't understand how to change Python versions then consider using 2to3 which is a Python program that will change the Python 2.X semantics to Python 3.X, also be aware that is is UB in terms of my program so I can't guarantee that will work either. Just change to Python 2.7 :P
  24.  
  25. My apologies if I forgot to censor a f**k, I checked through this document a few times and it is written uncensored.
  26.  
  27. --SYMBOLS IN BRAINF**K--
  28. > - Move the tape pointer over 1 cell towards positive direction
  29. < - Move the tape pointer over 1 cell towards negative direction
  30. + - Increments the current unit of tape by 1
  31. - - Decrements the current unit of tape by 1
  32. . - Prints the value of the current tape
  33. , - Takes an input from stdio and reads the decimal value into the current cell
  34. [ - If the cell under the tape pointer is pointing to zero (or less?) then jump to (and pass) the matching square bracket
  35. ] - Jump back to the matching square bracket unless the cell that the tape pointer is pointing to is zero (or less?)
  36. ------------------------
  37.  
  38. -----EXTRA  SYMBOLS-----
  39. / - Clears the current unit of tape (i.e sets it to zero)
  40. * - Sets the current unit of tape to 255
  41. | - Sets the current unit of tape to 128
  42. { - If the cell that the tape pointer is pointing to is zero (or less?) then jump to (and pass) the matching curly bracket
  43. } - Required to end the conditional block
  44. ------------------------
  45. """
  46.  
  47. import os, sys
  48.  
  49. def checkClosed(srcText):
  50.     stack = []
  51.     i = 0
  52.     numInstructions = len(srcText)
  53.     while i < numInstructions:
  54.         try:
  55.             if (srcText[i] == "[" or srcText[i] == "{"):
  56.                 stack.append(srcText[i])
  57.             elif (srcText[i] == "]" or srcText[i] == "}") and srcText[i] == chr(ord(stack.pop())):
  58.                 return -1
  59.         except IndexError:
  60.             print "Error: Forgot to open loop or conditional."
  61.             return -1
  62.         i += 1
  63.     return 0
  64.  
  65. def interpret(srcText):
  66.     runningTab = ""
  67.     repeat = 1
  68.     i = 0
  69.    
  70.     open("pySrc.py", "w").close()
  71.     pySrc = open("pySrc.py", "a")
  72.     pySrc.write("#! python 2.7\nfrom __future__ import print_function\n\ntape = [0] * 30000\ncurrentCell = 15000\n\n")
  73.     numInstructions = len(srcText)
  74.     while i < numInstructions:
  75.         if srcText[i] == ">":
  76.             try:
  77.                 while srcText[i + 1] == ">":
  78.                     repeat += 1
  79.                     i += 1
  80.             except IndexError:
  81.                 pass
  82.             upperBound = 29999 - repeat
  83.             pySrc.write(runningTab + "if (currentCell <= " + str(upperBound) + "):\n")
  84.             pySrc.write(runningTab + "\tcurrentCell += " + str(repeat) + "\n")
  85.         elif srcText[i] == "<":
  86.             try:
  87.                 while srcText[i + 1] == "<":
  88.                     repeat += 1
  89.                     i += 1
  90.             except IndexError:
  91.                 pass
  92.             lowerBound = 0 + repeat
  93.             pySrc.write(runningTab + "if (currentCell >= " + str(lowerBound) + "):\n")
  94.             pySrc.write(runningTab + "\tcurrentCell -= " + str(repeat) + "\n")
  95.         elif srcText[i] == "+":
  96.             try:
  97.                 while srcText[i + 1] == "+":
  98.                     repeat += 1
  99.                     i += 1
  100.             except IndexError:
  101.                 pass
  102.             pySrc.write(runningTab + "tape[currentCell] += " + str(repeat) + "\n")
  103.         elif srcText[i] == "-":
  104.             try:
  105.                 while srcText[i + 1] == "-":
  106.                     repeat += 1
  107.                     i += 1
  108.             except IndexError:
  109.                 pass
  110.             pySrc.write(runningTab + "tape[currentCell] -= " + str(repeat) + "\n")
  111.         elif srcText[i] == ".":
  112.             pySrc.write(runningTab + "print(chr(tape[currentCell]), end = '')\n")
  113.         elif srcText[i] == ",":
  114.             pySrc.write(runningTab + "userInput = raw_input('')\n" + runningTab + "for i in range(len(userInput)):\n" + runningTab + "\ttape[currentCell] = ord(userInput[i])\n" + runningTab + "\tcurrentCell += 1\n")
  115.         elif srcText[i] == "[":
  116.             pySrc.write(runningTab + "while tape[currentCell] > 0:\n")
  117.             runningTab += "\t"
  118.             try:
  119.                 if srcText[i + 1] == "]":
  120.                     pySrc.write(runningTab + "pass\n")
  121.             except IndexError:
  122.                 print "Error: Forgot to close loop."
  123.                 pySrc.close()
  124.                 os.remove("pySrc.py")
  125.                 raise SystemExit
  126.         elif srcText[i] == "]":
  127.             runningTab = runningTab[0:len(runningTab) - 1]
  128.         elif srcText[i] == "{":
  129.             pySrc.write(runningTab + "if tape[currentCell] > 0:\n")
  130.             runningTab += "\t"
  131.             try:
  132.                 if srcText[i + 1] == "}":
  133.                     pySrc.write(runningTab + "pass\n")
  134.             except IndexError:
  135.                 print "Error: Forgot to close conditional."
  136.                 pySrc.close()
  137.                 os.remove("pySrc.py")
  138.                 raise SystemExit
  139.         elif srcText[i] == "}":
  140.             runningTab = runningTab[0:len(runningTab) - 1]
  141.         elif srcText[i] == "/":
  142.             pySrc.write(runningTab + "tape[currentCell] = 0\n")
  143.         elif srcText[i] == "*":
  144.             pySrc.write(runningTab + "tape[currentCell] = 255\n")
  145.         elif srcText[i] == "|":
  146.             pySrc.write(runningTab + "tape[currentCell] = 128\n")
  147.         repeat = 1
  148.         i += 1
  149.     pySrc.close()
  150.     os.system("python pySrc.py")
  151.     os.remove("pySrc.py")
  152.  
  153. def main():
  154.     #Get the filename from the cmd arguments
  155.     try:
  156.         filename = str(sys.argv[1])
  157.     except:
  158.         print "Usage: python " + sys.argv[0] + " <filename>"
  159.     else:
  160.         #check if the file exists
  161.         try:
  162.             #Open the file
  163.             src = open(filename, "r")
  164.         except IOError:
  165.             #Give an English definition of the error
  166.             print "The file \"" + filename + "\" does not exist."
  167.         else:
  168.             retval = checkClosed(src.read())
  169.             if (retval == 0):
  170.                 src.seek(0)
  171.                 interpret(src.read())
  172.        
  173. if __name__ == "__main__":
  174.     main()
Comments
  • User was banned
Add Comment
Please, Sign In to add comment