Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # author: imlach
- # file: parser.py
- import drawFunctions, sys
- from string import *
- fns = drawFunctions.draw()
- ##
- # Prompt the user for a filename, if not supplied as the first
- # command line arg.
- def filePrompt(args=[]):
- if len(args) > 1:
- fName = args[1]
- else:
- fName = raw_input("Please enter your filename: ")
- try:
- lstFile = open(fName,"r")
- return lstFile,fName
- except IOError:
- print "Error opening file "+fName+"..."
- return filePrompt(),fName
- ##
- # Defines what commands are recognised, and how to handle them.
- # returns a pair of vals, used for different things
- def execFn(fnStr, args, defs):
- ## Little 'hack' to check if parameters are numerical.
- for arg in args[1:]:
- try:
- float(arg)
- except ValueError:
- return "valErr",arg
- ## Begin working things out
- if fnStr == "position":
- fns.pos(args[1],args[2])
- return fnStr,True
- elif fnStr == "move":
- fns.mov(args[1],args[2])
- return fnStr,True
- elif fnStr == "line":
- fns.line(args[1],args[2])
- return fnStr,True
- elif fnStr == "circle":
- fns.circ(args[1])
- return fnStr,True
- elif fnStr == "define":
- defs[args[1]] = []
- curDef = args[1]
- return fnStr,args[1]
- elif fnStr == "end":
- return fnStr,""
- elif fnStr in defs.keys():
- ## Execute function call
- for line in defs[fnStr]:
- execFn(line[0],line,defs)
- return fnStr,True
- elif fnStr == "" or fnStr[0] == "#":
- #Ignore comments or blank lines
- pass
- return "",""
- else:
- return "error",False
- ##
- # Runs through the file returned by filePrompt, and goes through
- # each line.
- def parse(listing,fName):
- ## Set up vars and objects.
- defs = {}
- lines = []
- curDef = ""
- i = 0
- loops = 0
- backTo = 0
- for line in listing:
- line = split(line[:-1]," ")
- lines += [line]
- while i < len(lines):
- line = lines[i]
- if line[0] == "loop":
- ## If in loop mode, store the number of loops and which line
- # to return to.
- loops = int(line[1])-1
- backTo = i
- elif curDef != "" and line[0] != "end":
- ## Add line to def if in define mode
- defs[curDef] += [line]
- else:
- ## Execute current line
- rtVal = execFn(line[0],line,defs)
- if rtVal[0] == "define":
- # Enter define mode
- curDef = rtVal[1]
- elif rtVal[0] == "end":
- if loops == 0:
- # If not in loop mode, exit define mode
- curDef = rtVal[1]
- else:
- # Decrement loop counter, and return to the line i,
- # so it gets incremented so to be on the correct
- # line in the next loop.
- loops -= 1
- i = backTo
- ## Handle errors nicely
- elif rtVal[0] == "error":
- print "Syntax error on line "+str(i+1)+" of "+fName+": '"+line[0]+"'"
- return False
- elif rtVal[0] == "valErr":
- print "Value error on line "+str(i+1)+" of "+fName+": '"+rtVal[1]+"'"
- return False
- i += 1
- fns.complete()
- return True
- lst = filePrompt(sys.argv)
- parse(lst[0],lst[1])
Advertisement
Add Comment
Please, Sign In to add comment