Skip to content

Instantly share code, notes, and snippets.

@Lokno
Last active July 19, 2016 21:23
Show Gist options
  • Save Lokno/049b6a8f43cceb621a718f28859ce08e to your computer and use it in GitHub Desktop.
Save Lokno/049b6a8f43cceb621a718f28859ce08e to your computer and use it in GitHub Desktop.
A basic Java interpretor
# Provides a basic command line interpretor for Java
#
# Recognizes import statements and places them accordingly
# All other statements are placed in the body of a main method
# To execute and print a result type "print <statement>"
# Type q/e/quit/exit/close to exit interpretor
import subprocess,re
def writeJava( filename, classname, imports, state, cmdstr ):
oneIndent = " " * 4
twoIndent = oneIndent * 2
fileStr = "import static java.lang.Math.*;\n" + '\n'.join(imports) + "\nclass " + classname
fileStr += " {\n" + oneIndent + "public static void main(String[] args) {\n" + twoIndent
fileStr += ("\n" + twoIndent).join(state) + "\n" + twoIndent + cmdstr + "\n" + oneIndent + "}\n}"
with open(filename, "w") as f:
f.write(fileStr)
def compileJava( filename ):
result = ""
try:
result = subprocess.check_output("javac " + filename, shell=True)
except subprocess.CalledProcessError:
result = "ERROR\n"
return result
def executeJava( filename, classname ):
result = ""
try:
result = subprocess.check_output("java -cp . Test", shell=True)
except subprocess.CalledProcessError:
result = "ERROR\n"
return result
imports = []
state = []
quitStatements = ["q","e","quit","exit","close"]
importRE = re.compile("^import .*")
printRE = re.compile("^print (.*)")
filename = "temp.java"
classname = "Test"
line = raw_input(">> ")
while line.lower() not in quitStatements:
if line != "":
entryType = "UNKNOWN"
cmdstr = ""
if importRE.match(line):
entryType = "IMPORT"
imports.append(line)
else:
m = printRE.match(line)
if m:
entryType = "CMD"
cmdstr = "System.out.println(%s);" % m.group(1)
else:
entryType = "STATE"
state.append(line)
writeJava( filename, classname, imports, state, cmdstr )
compilerResponse = compileJava( filename )
if compilerResponse == "":
if entryType == "CMD":
print executeJava( filename, classname ),
else:
# remove invalid statement from list
if entryType == "IMPORT":
imports = imports[:-1]
elif entryType == "STATE":
state = state[:-1]
line = raw_input(">> ")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment