Jacob_DiDiodato

Brainf**k Interpreter [V0.6]

Nov 14th, 2017
329
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.16 KB | None | 0 0
  1. #! python 2.7
  2. """
  3. V: 0.6
  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.6 PATCHNOTES----------------
  17. Uses a counter to add cells or increment without a loop
  18. Added a character to set the value of a cell halfway
  19.  
  20. Program execution has been increased by ~11 times since version 0.5***
  21.  
  22. Brainf**k 0.5 programs will NOT work correctly with this new version.
  23. -----------------------------------------------
  24.  
  25. 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
  26.  
  27. My apologies if I forgot to censor a f**k, I checked through this document a few times and it is written uncensored.
  28.  
  29. --SYMBOLS IN BRAINF**K--
  30. > - Move the tape pointer over 1 cell towards positive direction
  31. < - Move the tape pointer over 1 cell towards negative direction
  32. + - Increments the current unit of tape by 1
  33. - - Decrements the current unit of tape by 1
  34. . - Prints the value of the current tape
  35. , - Takes an input from stdio and reads the decimal value into the current cell
  36. [ - If the cell under the tape pointer is pointing to zero (or less?) then jump to (and pass) the matching square bracket
  37. ] - Jump back to the matching square bracket unless the cell that the tape pointer is pointing to is zero (or less?)
  38. ------------------------
  39.  
  40. -----EXTRA  SYMBOLS-----
  41. / - Clears the current unit of tape (i.e sets it to zero)
  42. * - Sets the current unit of tape to 255
  43. | - Sets the current unit of tape to 128
  44. { - If the cell that the tape pointer is pointing to is zero (or less?) then jump to (and pass) the matching curly bracket
  45. } - Required to end the conditional block
  46. ------------------------
  47.  
  48. ***Program execution time was tested against the ascii mandelbrot fractal renderer found here: https://pastebin.com/vJwTX3QH
  49. """
  50.  
  51. import os, sys
  52.  
  53. def checkClosed(srcText):
  54.     stack = []
  55.     i = 0
  56.     numInstructions = len(srcText)
  57.     while i < numInstructions:
  58.         try:
  59.             if (srcText[i] == "[" or srcText[i] == "{"):
  60.                 stack.append(srcText[i])
  61.             elif (srcText[i] == "]" or srcText[i] == "}") and srcText[i] == chr(ord(stack.pop())):
  62.                 return -1
  63.         except IndexError:
  64.             print "Error: Forgot to open loop or conditional."
  65.             return -1
  66.         i += 1
  67.     return 0
  68.  
  69. def interpret(srcText):
  70.     runningTab = ""
  71.     repeat = 1
  72.     i = 0
  73.    
  74.     open("pySrc.py", "w").close()
  75.     pySrc = open("pySrc.py", "a")
  76.     pySrc.write("#! python 2.7\nfrom __future__ import print_function\n\ntape = [0] * 30000\ncurrentCell = 15000\n\n")
  77.     numInstructions = len(srcText)
  78.     while i < numInstructions:
  79.         if srcText[i] == ">":
  80.             try:
  81.                 while srcText[i + 1] == ">":
  82.                     repeat += 1
  83.                     i += 1
  84.             except IndexError:
  85.                 pass
  86.             pySrc.write(runningTab + "if (currentCell + " + str(repeat) + " <= 29999):\n")
  87.             pySrc.write(runningTab + "\tcurrentCell += " + str(repeat) + "\n")
  88.         elif srcText[i] == "<":
  89.             try:
  90.                 while srcText[i + 1] == "<":
  91.                     repeat += 1
  92.                     i += 1
  93.             except IndexError:
  94.                 pass
  95.             pySrc.write(runningTab + "if (currentCell - " + str(repeat) + " >= 0):\n")
  96.             pySrc.write(runningTab + "\tcurrentCell -= " + str(repeat) + "\n")
  97.         elif srcText[i] == "+":
  98.             try:
  99.                 while srcText[i + 1] == "+":
  100.                     repeat += 1
  101.                     i += 1
  102.             except IndexError:
  103.                 pass
  104.             pySrc.write(runningTab + "tape[currentCell] += " + str(repeat) + "\n")
  105.         elif srcText[i] == "-":
  106.             try:
  107.                 while srcText[i + 1] == "-":
  108.                     repeat += 1
  109.                     i += 1
  110.             except IndexError:
  111.                 pass
  112.             pySrc.write(runningTab + "tape[currentCell] -= " + str(repeat) + "\n")
  113.         elif srcText[i] == ".":
  114.             pySrc.write(runningTab + "print(chr(tape[currentCell]), end = '')\n")
  115.         elif srcText[i] == ",":
  116.             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")
  117.         elif srcText[i] == "[":
  118.             pySrc.write(runningTab + "while tape[currentCell] > 0:\n")
  119.             runningTab += "\t"
  120.             try:
  121.                 if srcText[i + 1] == "]":
  122.                     pySrc.write(runningTab + "pass\n")
  123.             except IndexError:
  124.                 print "Error: Forgot to close loop."
  125.                 pySrc.close()
  126.                 os.remove("pySrc.py")
  127.                 raise SystemExit
  128.         elif srcText[i] == "]":
  129.             runningTab = runningTab[0:len(runningTab) - 1]
  130.         elif srcText[i] == "{":
  131.             pySrc.write(runningTab + "if tape[currentCell] > 0:\n")
  132.             runningTab += "\t"
  133.             try:
  134.                 if srcText[i + 1] == "}":
  135.                     pySrc.write(runningTab + "pass\n")
  136.             except IndexError:
  137.                 print "Error: Forgot to close conditional."
  138.                 pySrc.close()
  139.                 os.remove("pySrc.py")
  140.                 raise SystemExit
  141.         elif srcText[i] == "}":
  142.             runningTab = runningTab[0:len(runningTab) - 1]
  143.         elif srcText[i] == "/":
  144.             pySrc.write(runningTab + "tape[currentCell] = 0\n")
  145.         elif srcText[i] == "*":
  146.             pySrc.write(runningTab + "tape[currentCell] = 255\n")
  147.         elif srcText[i] == "|":
  148.             pySrc.write(runningTab + "tape[currentCell] = 128\n")
  149.         repeat = 1
  150.         i += 1
  151.     pySrc.close()
  152.     os.system("python pySrc.py")
  153.     os.remove("pySrc.py")
  154.  
  155. def main():
  156.     #Get the filename from the cmd arguments
  157.     try:
  158.         filename = str(sys.argv[1])
  159.     except:
  160.         print "Usage: python " + sys.argv[0] + " <filename>"
  161.     else:
  162.         #check if the file exists
  163.         try:
  164.             #Open the file
  165.             src = open(filename, "r")
  166.         except IOError:
  167.             #Give an English definition of the error
  168.             print "The file \"" + filename + "\" does not exist."
  169.         else:
  170.             retval = checkClosed(src.read())
  171.             if (retval == 0):
  172.                 src.seek(0)
  173.                 interpret(src.read())
  174.        
  175. if __name__ == "__main__":
  176.     main()
  177. My apologies if I forgot to censor a f**k, I checked through this document a few times and it is written uncensored.
  178.  
  179. --SYMBOLS IN BRAINF**K--
  180. > - Move the tape pointer over 1 cell towards positive direction
  181. < - Move the tape pointer over 1 cell towards negative direction
  182. + - Increments the current unit of tape by 1
  183. - - Decrements the current unit of tape by 1
  184. . - Prints the value of the current tape
  185. , - Takes an input from stdio and reads the decimal value into the current cell
  186. [ - If the cell under the tape pointer is pointing to zero (or less?) then jump to (and pass) the matching square bracket
  187. ] - Jump back to the matching square bracket unless the cell that the tape pointer is pointing to is zero (or less?)
  188. ------------------------
  189.  
  190. -----EXTRA  SYMBOLS-----
  191. / - Clears the current unit of tape (i.e sets it to zero)
  192. * - Sets the current unit of tape to 255
  193. | - Sets the current unit of tape to 128
  194. { - If the cell that the tape pointer is pointing to is zero (or less?) then jump to (and pass) the matching curly bracket
  195. } - Required to end the conditional block
  196. ------------------------
  197.  
  198. ***Program execution time was tested against the ascii mandelbrot fractal renderer found here: https://pastebin.com/vJwTX3QH
  199. """
  200.  
  201. import os, sys
  202.  
  203. def checkClosed(srcText):
  204.     stack = []
  205.     i = 0
  206.     numInstructions = len(srcText)
  207.     while i < numInstructions:
  208.         try:
  209.             if (srcText[i] == "[" or srcText[i] == "{"):
  210.                 stack.append(srcText[i])
  211.             elif (srcText[i] == "]" or srcText[i] == "}") and srcText[i] == chr(ord(stack.pop())):
  212.                 return -1
  213.         except IndexError:
  214.             print "Error: Forgot to open loop or conditional."
  215.             return -1
  216.         i += 1
  217.     return 0
  218.  
  219. def interpret(srcText):
  220.     runningTab = ""
  221.     repeat = 1
  222.     i = 0
  223.    
  224.     open("pySrc.py", "w").close()
  225.     pySrc = open("pySrc.py", "a")
  226.     pySrc.write("#! python 2.7\nfrom __future__ import print_function\n\ntape = [0] * 30000\ncurrentCell = 15000\n\n")
  227.     numInstructions = len(srcText)
  228.     while i < numInstructions:
  229.         if srcText[i] == ">":
  230.             try:
  231.                 while srcText[i + 1] == ">":
  232.                     repeat += 1
  233.                     i += 1
  234.             except IndexError:
  235.                 pass
  236.             pySrc.write(runningTab + "if (currentCell + " + str(repeat) + " <= 29999):\n")
  237.             pySrc.write(runningTab + "\tcurrentCell += " + str(repeat) + "\n")
  238.         elif srcText[i] == "<":
  239.             try:
  240.                 while srcText[i + 1] == "<":
  241.                     repeat += 1
  242.                     i += 1
  243.             except IndexError:
  244.                 pass
  245.             pySrc.write(runningTab + "if (currentCell - " + str(repeat) + " >= 0):\n")
  246.             pySrc.write(runningTab + "\tcurrentCell -= " + str(repeat) + "\n")
  247.         elif srcText[i] == "+":
  248.             try:
  249.                 while srcText[i + 1] == "+":
  250.                     repeat += 1
  251.                     i += 1
  252.             except IndexError:
  253.                 pass
  254.             pySrc.write(runningTab + "tape[currentCell] += " + str(repeat) + "\n")
  255.         elif srcText[i] == "-":
  256.             try:
  257.                 while srcText[i + 1] == "-":
  258.                     repeat += 1
  259.                     i += 1
  260.             except IndexError:
  261.                 pass
  262.             pySrc.write(runningTab + "tape[currentCell] -= " + str(repeat) + "\n")
  263.         elif srcText[i] == ".":
  264.             pySrc.write(runningTab + "print(chr(tape[currentCell]), end = '')\n")
  265.         elif srcText[i] == ",":
  266.             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")
  267.         elif srcText[i] == "[":
  268.             pySrc.write(runningTab + "while tape[currentCell] > 0:\n")
  269.             runningTab += "\t"
  270.             try:
  271.                 if srcText[i + 1] == "]":
  272.                     pySrc.write(runningTab + "pass\n")
  273.             except IndexError:
  274.                 print "Error: Forgot to close loop."
  275.                 pySrc.close()
  276.                 os.remove("pySrc.py")
  277.                 raise SystemExit
  278.         elif srcText[i] == "]":
  279.             runningTab = runningTab[0:len(runningTab) - 1]
  280.         elif srcText[i] == "{":
  281.             pySrc.write(runningTab + "if tape[currentCell] > 0:\n")
  282.             runningTab += "\t"
  283.             try:
  284.                 if srcText[i + 1] == "}":
  285.                     pySrc.write(runningTab + "pass\n")
  286.             except IndexError:
  287.                 print "Error: Forgot to close conditional."
  288.                 pySrc.close()
  289.                 os.remove("pySrc.py")
  290.                 raise SystemExit
  291.         elif srcText[i] == "}":
  292.             runningTab = runningTab[0:len(runningTab) - 1]
  293.         elif srcText[i] == "/":
  294.             pySrc.write(runningTab + "tape[currentCell] = 0\n")
  295.         elif srcText[i] == "*":
  296.             pySrc.write(runningTab + "tape[currentCell] = 255\n")
  297.         elif srcText[i] == "|":
  298.             pySrc.write(runningTab + "tape[currentCell] = 128\n")
  299.         repeat = 1
  300.         i += 1
  301.     pySrc.close()
  302.     os.system("python pySrc.py")
  303.     os.remove("pySrc.py")
  304.  
  305. def main():
  306.     #Get the filename from the cmd arguments
  307.     try:
  308.         filename = str(sys.argv[1])
  309.     except:
  310.         print "Usage: python " + sys.argv[0] + " <filename>"
  311.     else:
  312.         #check if the file exists
  313.         try:
  314.             #Open the file
  315.             src = open(filename, "r")
  316.         except IOError:
  317.             #Give an English definition of the error
  318.             print "The file \"" + filename + "\" does not exist."
  319.         else:
  320.             retval = checkClosed(src.read())
  321.             if (retval == 0):
  322.                 src.seek(0)
  323.                 interpret(src.read())
  324.        
  325. if __name__ == "__main__":
  326.     main()
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment