Jacob_DiDiodato

Easy As Py Compiler

Feb 23rd, 2017
365
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.61 KB | None | 0 0
  1. #! python 2.7
  2. """
  3. V: 0.0.1 Test Build
  4. Easy As Py
  5. easyPyCompiler.py
  6. Last edit was: Sunday, December 11, 2016
  7. Jacob DiDiodato
  8. A python-based interpreter for very novice programmers
  9. Probably pretty slow and error-prone
  10. Should write to a temporary python file and run it with syntax error checking
  11. A very space-minded language
  12.  
  13. My apologies about not much commenting. I think a lot of this is fairly self-explainatory. If people want it then I'll add it later
  14.  
  15. My attempt at writing a compiler without an AST (just text verification)
  16. """
  17.  
  18. #Includes pygame and random natively! Thats fun!
  19. import pygame
  20. from random import *
  21. import os,sys
  22.  
  23. dQuote = '"'
  24. sQuote = "'"
  25.  
  26. #Words and symbols you can't use in var names
  27. keyWords = ["print", "set", "to", "random", "add", "False", "None", "True", "and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield"]
  28. keyChars = ['~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '+', '=', '{', '[', '}', ']',
  29.             ':', ';', dQuote, sQuote, '<', ',', '>', '.', '?', '/', '|', '\\']
  30.            
  31. def generateRandom(commands):
  32.     exclusive = False
  33.     try:
  34.         commands[3]
  35.     except IndexError:
  36.         exclusive = True
  37.     else:
  38.         if (commands[3] == "e"):
  39.             exclusive = True
  40.     return "randint(" + str(commands[0]) + ", " + str(commands[2]) + " - " + str(int(exclusive)) + ")"
  41.  
  42. def checkRandomNum(commands, lineNo, globalVars):
  43.     if (commands[1] == "to"):
  44.         if (globalVars.get(commands[0]) != None):
  45.             commands[0] = globalVars.get(commands[0])
  46.         if (globalVars.get(commands[2]) != None):
  47.             commands[2] = globalVars.get(commands[2])
  48.         try:
  49.             int(commands[0])
  50.             int(commands[2])
  51.         except ValueError:
  52.             print "Line " + str(lineNo + 1) + "\nValueError: [easyPyError #4] One of the numbers you have entered cannot be converted to an integer."
  53.             return -1
  54.         else:
  55.             if (int(commands[2]) < int(commands[0])):
  56.                 print "Line " + str(lineNo + 1) + "\nRandomError: [easyPyError #5] Your second number in range is larger than your first number in range.\nConsider switching them."
  57.                 return -1
  58.             else:
  59.                 return generateRandom(commands)
  60.     else:
  61.         print "Line " + str(lineNo + 1) + "\nFormattingError: [easyPyError #3] Missing word 'to'.\nFormat random number like: 'random num1 to num2 (i/e)'."
  62.         return -1
  63.        
  64. def addition(commands):
  65.     return str(commands[0]) + "+" + str(commands[2])
  66.  
  67. def checkAddNum(commands, lineNo, globalVars):
  68.     if (commands[1] == "to"):
  69.         if (globalVars.get(commands[0]) != None):
  70.             commands[0] = globalVars.get(commands[0])
  71.         if (globalVars.get(commands[2]) != None):
  72.             commands[2] = globalVars.get(commands[2])
  73.         try:
  74.             int(commands[0])
  75.             int(commands[2])
  76.         except ValueError:
  77.             print "Line " + str(lineNo + 1) + "\nValueError: [easyPyError #4] One of the numbers you have entered cannot be converted to an integer."
  78.             return -1
  79.         else:
  80.             return addition(commands)
  81.     else:
  82.         print "Line " + str(lineNo + 1) + "\nFormattingError: [easyPyError #3] Missing word 'to'.\nFormat addition like: 'add num1 to num2'."
  83.         return -1
  84.        
  85. def subtract(commands):
  86.     return str(commands[0]) + "-" + str(commands[2])
  87.  
  88. def checkSubNum(commands, lineNo, globalVars):
  89.     if (commands[1] == "from"):
  90.         if (globalVars.get(commands[0]) != None):
  91.             commands[0] = globalVars.get(commands[0])
  92.         if (globalVars.get(commands[2]) != None):
  93.             commands[2] = globalVars.get(commands[2])
  94.         try:
  95.             int(commands[0])
  96.             int(commands[2])
  97.         except ValueError:
  98.             print "Line " + str(lineNo + 1) + "\nValueError: [easyPyError #4] One of the numbers you have entered cannot be converted to an integer."
  99.             return -1
  100.         else:
  101.             return subtract(commands)
  102.     else:
  103.         print "Line " + str(lineNo + 1) + "\nFormattingError: [easyPyError #3] Missing word 'from'.\nFormat subtraction like: 'subtract num1 from num2'."
  104.         return -1
  105.  
  106. def interpret(srcText):
  107.     #the container for all global variables in the code
  108.     globalVars = {}
  109.     runningTab = ""
  110.     open("pySource.py", "w").close()
  111.     pySource = open("pySource.py", "a")
  112.     pySource.write("#! python2.7\n#Compiled with the Easy As Py Compiler\n\nimport pygame\nfrom random import *\n\n")
  113.     line = len(srcText)
  114.     for i in range(line):
  115.         commands = srcText[i].split(" ")
  116.         #To print a string/variable
  117.         if (commands[0] == "print"):
  118.             pySource.write("print ")
  119.             #If i am printing a variable check if that variable exists
  120.             #If it does then i print it but if it doesnt then i just print the word instead
  121.             if (globalVars.get(commands[1]) != None):
  122.                 pySource.write(runningTab + commands[1] + "\n")
  123.             elif (commands[1] == "random"):
  124.                 if (checkRandomNum(commands[2:], i, globalVars) != -1):
  125.                     pySource.write(runningTab + checkRandomNum(commands[2:], i, globalVars) + "\n")
  126.                 else:
  127.                     break
  128.             elif (commands[1] == "add"):
  129.                 if (checkAddNum(commands[2:], i, globalVars) != -1):
  130.                     pySource.write(runningTab + checkAddNum(commands[2:], i, globalVars) + "\n")
  131.                 else:
  132.                     break
  133.             elif (commands[1] == "subtract"):
  134.                 if (checkSubNum(commands[2:], i, globalVars) != -1):
  135.                     pySource.write(runningTab + checkSubNum(commands[2:], i, globalVars) + "\n")
  136.                 else:
  137.                     break
  138.             #If i am printing a string
  139.             else:
  140.                 #Print the contents of the string
  141.                 pySource.write(runningTab + dQuote + " ".join(commands[1:]) + dQuote + "\n")
  142.         #To set a variable
  143.         elif (commands[0] == "set"):
  144.             #Checking syntax
  145.             if (commands[2] == "to"):
  146.                 badVar = False
  147.                 for j in range(len(keyChars)):
  148.                     for k in range(len(commands[1])):
  149.                         if (commands[1][k] == keyChars[j]):
  150.                             print(commands[1][k])
  151.                             print "Line " + str(i + 1) + "\nVariableNameError: [easyPyError #6] Invalid variable name.\nThe character '" + keyChars[j] + "' can't be used in a variable name."
  152.                             badVar = True
  153.                            
  154.                 for j in range(len(keyWords)):
  155.                     if (commands[1] == keyWords[j]):
  156.                         print "Line " + str(i + 1) + "\nVariableNameError: [easyPyError #6] Invalid variable name.\nThe word '" + keyWords[j] + "' is special and can't be used in a variable name."
  157.                         badVar = True
  158.                        
  159.                 if (badVar == True):
  160.                     break
  161.                    
  162.                 #Set our variable internally in a sort of RAM
  163.                 #I use a dictionary to specify an arbitrarily large amount of RAM
  164.                 #Write it into python code
  165.                 if (commands[3] == "random"):
  166.                     if (checkRandomNum(commands[4:], i, globalVars) != -1):
  167.                         exclusive = False
  168.                         try:
  169.                             commands[7]
  170.                         except IndexError:
  171.                             exclusive = True
  172.                         else:
  173.                             if (commands[7] == "e"):
  174.                                 exclusive = True
  175.                         if (globalVars.get(commands[4]) != None):
  176.                             commands[4] = globalVars.get(commands[4])
  177.                         if (globalVars.get(commands[6]) != None):
  178.                             commands[6] = globalVars.get(commands[6])
  179.                         randVar = randint(int(commands[4]), int(commands[6]) - int(exclusive))
  180.                         globalVars[commands[1]] = randVar
  181.                         pySource.write(runningTab + commands[1] + "=" + str(globalVars[commands[1]]) + "\n")
  182.                     else:
  183.                         break
  184.                 elif (commands[3] == "add"):
  185.                     if (checkAddNum(commands[4:], i, globalVars) != -1):
  186.                         globalVars[commands[1]] = int(commands[4]) + int(commands[6])
  187.                         pySource.write(runningTab + commands[1] + "=" + str(checkAddNum(commands[4:], i, globalVars)) + "\n")
  188.                     else:
  189.                         break
  190.                 elif (commands[3] == "subtract"):
  191.                     if (checkSubNum(commands[4:], i, globalVars) != -1):
  192.                         globalVars[commands[1]] = int(commands[4]) - int(commands[6])
  193.                         pySource.write(runningTab + commands[1] + "=" + str(checkSubNum(commands[4:], i, globalVars)) + "\n")
  194.                     else:
  195.                         break
  196.                 else:
  197.                     try:
  198.                         globalVars[commands[1]] = int(commands[3]);
  199.                         pySource.write(runningTab + commands[1] + "=" + str(globalVars[commands[1]]) + "\n")
  200.                     except ValueError:
  201.                         globalVars[commands[1]] = commands[3];
  202.                         pySource.write(runningTab + commands[1] + "=" + dQuote + globalVars[commands[1]] + dQuote + "\n")
  203.             else:
  204.                 #If we are missing some syntax
  205.                 print "Line " + str(i + 1) + "\nFormattingError: [easyPyError #3] Missing word 'to'.\nFormat varible setting like: 'set varName to value'."
  206.                 break
  207.         elif (commands[0] == "random"):
  208.             pySource.write(runningTab + checkRandomNum(commands[1:], i, globalVars))
  209.         elif (commands[0] == "add"):
  210.             pySource.write(runningTab + checkAddNum(commands[1:], i, globalVars))
  211.         elif (commands[0] == "subtract"):
  212.             pySource.write(runningTab + checkSubNum(commands[1:], i, globalVars))
  213.         elif (commands[0] == "!"):
  214.             pySource.write("#" + " ".join(commands[1:]) + "\n")
  215.         elif (commands[0] == ""):
  216.             pass
  217.         #If the first token is not recognized by the compiler
  218.         else:
  219.             print "Line " + str(i + 1) + "\nSyntaxError: [easyPyError #2] Token or function '" + str(commands[0] + "' does not exist.\nTake a look at the first word of line " + str(i + 1) + " to see if thats what you meant to type.")
  220.             pySource.close()
  221.             os.remove("pySource.py")
  222.             return -1
  223.     pySource.close()
  224.     os.system("python pySource.py")
  225.     #Keep the following line in the release build
  226.     #os.remove("pySource.py")
  227.     return 0
  228.  
  229. def openFile():
  230.     #Get the filename from the command line arguments
  231.     filename = str(sys.argv[1])
  232.  
  233.     #Check to see if the file exists
  234.     try:
  235.         #Open the file
  236.         src = open(filename, "r")
  237.     except IOError:
  238.         #Give a very English defintion of the error
  239.         print "Line 0\nFileNameError: [easyPyError #1] That file does not exist.\nTry naming the file something like: '" + str(sys.argv[1].split(".")[0]) + ".easyPy'"
  240.     else:
  241.         srcText = src.read().split("\n")
  242.         interpret(srcText)
  243.    
  244. def main():
  245.     openFile()
  246.    
  247. main()
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment