Jacob_DiDiodato

Brainf**k Interpreter [V0.5]

Mar 14th, 2017
372
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.56 KB | None | 0 0
  1. #! python 2.7
  2. """
  3. V: 0.5
  4. Brainf**k Compiler
  5. bfInterpreter.py
  6. Last edit was Tuesday, March 15th 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 ~10 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.5 PATCHNOTES----------------
  17. 1. The symbol that sets the current unit of tape to 255 has been changed from '\' to '*' to follow my set of conventions
  18.   -> brainf**k V0.4 code WILL NOT WORK AS EXPECTED WITH THE V0.5 INTERPRETER
  19. 2. Added conditional symbols
  20.   -> brainf**k V0.5 now does a double pass on your source code to ensure that all opened conditionals and loops are also closed
  21.      -> Pass 1 uses a stack to ensure that all opened brackets are closed
  22.       -> Pass 2 converts your Brainf**k code to Python source code and then runs that, pass 2 does exactly what V0.4 did
  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. { - If the cell that the tape pointer is pointing to is zero (or less?) then jump to (and pass) the matching curly bracket
  44. } - Required to end the conditional block
  45. ------------------------
  46. """
  47.  
  48. import os, sys
  49.  
  50. def checkClosed(srcText):
  51.     stack = []
  52.     i = 0
  53.     numInstructions = len(srcText)
  54.     while i < numInstructions:
  55.         try:
  56.             if (srcText[i] == "[" or srcText[i] == "{"):
  57.                 stack.append(srcText[i])
  58.             elif (srcText[i] == "]" or srcText[i] == "}") and srcText[i] == chr(ord(stack.pop())):
  59.                 return -1
  60.         except IndexError:
  61.             print "Error: Forgot to open loop or conditional."
  62.             return -1
  63.         i += 1
  64.     return 0
  65.  
  66. def interpret(srcText):
  67.     runningTab = ""
  68.     repeat = 1
  69.     i = 0
  70.    
  71.     open("pySrc.py", "w").close()
  72.     pySrc = open("pySrc.py", "a")
  73.     pySrc.write("#! python 2.7\nfrom __future__ import print_function\n\ntape = [0] * 30000\ncurrentCell = 0\n\ndef checkTape(x):\n\tif (currentCell == 30000 and x == 1) or (currentCell == 0 and x == -1):\n\t\tprint(\"Error: Tape has reached it's end\", end = '')\n\t\traise SystemExit\n\treturn x\n\n")
  74.     numInstructions = len(srcText)
  75.     while i < numInstructions:
  76.         if srcText[i] == ">":
  77.             try:
  78.                 while srcText[i + 1] == ">":
  79.                     repeat += 1
  80.                     i += 1
  81.             except IndexError:
  82.                 pass
  83.             pySrc.write(runningTab + "for i in range(0, " + str(repeat) + "):\n")
  84.             pySrc.write(runningTab + "\tcurrentCell += checkTape(1)\n")
  85.         elif srcText[i] == "<":
  86.             try:
  87.                 while srcText[i + 1] == "<":
  88.                     repeat += 1
  89.                     i += 1
  90.             except IndexError:
  91.                 pass
  92.             pySrc.write(runningTab + "for i in range(0, " + str(repeat) + "):\n")
  93.             pySrc.write(runningTab + "\tcurrentCell += checkTape(-1)\n")
  94.         elif srcText[i] == "+":
  95.             try:
  96.                 while srcText[i + 1] == "+":
  97.                     repeat += 1
  98.                     i += 1
  99.             except IndexError:
  100.                 pass
  101.             pySrc.write(runningTab + "for i in range(0, " + str(repeat) + "):\n")
  102.             pySrc.write(runningTab + "\ttape[currentCell] += 1\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 + "for i in range(0, " + str(repeat) + "):\n")
  111.             pySrc.write(runningTab + "\ttape[currentCell] -= 1\n")
  112.         elif srcText[i] == ".":
  113.             pySrc.write(runningTab + "print(chr(tape[currentCell]), end = '')\n")
  114.         elif srcText[i] == ",":
  115.             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")
  116.         elif srcText[i] == "[":
  117.             pySrc.write(runningTab + "while tape[currentCell] > 0:\n")
  118.             runningTab += "\t"
  119.             try:
  120.                 if srcText[i + 1] == "]":
  121.                     pySrc.write(runningTab + "pass\n")
  122.             except IndexError:
  123.                 print "Error: Forgot to close loop."
  124.                 pySrc.close()
  125.                 os.remove("pySrc.py")
  126.                 raise SystemExit
  127.         elif srcText[i] == "]":
  128.             runningTab = runningTab[0:len(runningTab) - 1]
  129.         elif srcText[i] == "{":
  130.             pySrc.write(runningTab + "if tape[currentCell] > 0:\n")
  131.             runningTab += "\t"
  132.             try:
  133.                 if srcText[i + 1] == "}":
  134.                     pySrc.write(runningTab + "pass\n")
  135.             except IndexError:
  136.                 print "Error: Forgot to close conditional."
  137.                 pySrc.close()
  138.                 os.remove("pySrc.py")
  139.                 raise SystemExit
  140.         elif srcText[i] == "}":
  141.             runningTab = runningTab[0:len(runningTab) - 1]
  142.         elif srcText[i] == "/":
  143.             pySrc.write(runningTab + "tape[currentCell] = 0\n")
  144.         elif srcText[i] == "*":
  145.             pySrc.write(runningTab + "tape[currentCell] = 255\n")
  146.         repeat = 1
  147.         i += 1
  148.     pySrc.close()
  149.     os.system("python pySrc.py")
  150.     os.remove("pySrc.py")
  151.  
  152. def main():
  153.     #Get the filename from the cmd arguments
  154.     try:
  155.         filename = str(sys.argv[1])
  156.     except:
  157.         print "Usage: python " + sys.argv[0] + " <filename>"
  158.     else:
  159.         #check if the file exists
  160.         try:
  161.             #Open the file
  162.             src = open(filename, "r")
  163.         except IOError:
  164.             #Give an English definition of the error
  165.             print "The file \"" + filename + "\" does not exist."
  166.         else:
  167.             retval = checkClosed(src.read())
  168.             if (retval == 0):
  169.                 src.seek(0)
  170.                 interpret(src.read())
  171.        
  172. if __name__ == "__main__":
  173.     main()
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment