def checkForPrint(input, verbose, count): if("PRINT" in input.rstrip('\n')): splitVal = input.rstrip('\n').split()[1:] if(verbose == 1): printStatement = "executing line " + str(count) + ": " + str(' '.join(input.rstrip('\n').split()).replace("\"","")) print(printStatement) if("PRINT" in splitVal): splitVal = splitVal[1:] for (key,value), (key2,value2) in sorted(zip(printVariables().items(), declareVar().items())): if(key.lower() in splitVal): splitVal[splitVal.index(key.lower())] = value2 if(' '.join(splitVal).replace("\"","") != ' '): print(' '.join(splitVal).replace("\"",""))
def checkForAssign(input, verbose, count): if("ASSIGN" in input.rstrip('\n')): splitVal = input.rstrip('\n').split()[1:] if(verbose == 1): printStatement = "executing line " + str(count) + ": " + str(' '.join(input.rstrip('\n').split()).replace("\"","")) print(printStatement) if(len(splitVal) > 2): try: if(splitVal[0] == "" or splitVal[2] == "" or splitVal[3] == ""): raise else: pass except: raise TooFewOperands("Too few operands",splitVal[0],splitVal[2]) try: if(splitVal[0].upper() in declareVar() and splitVal[2].upper() in declareVar()): pass else: raise except: raise VarNotDefined("Variable not defined",splitVal[0],splitVal[2]) shouldCheckForVar = True try: if(splitVal[3].isdigit()): iVal = int(splitVal[3]) shouldCheckForVar = False pass except: raise InvalidValueType("Invalid value",splitVal[3]) if(shouldCheckForVar): try: if(splitVal[3].upper() in declareVar()): pass else: raise except: raise VarNotDefined("Variable not defined",splitVal[3]) try: if(splitVal[1] == '+' or splitVal[1] == '-' or splitVal[1] == '*' or splitVal[1] == '&'): pass else: print("Invalid expression") raise except: raise InvalidExpression("Invalid expression",splitVal[1]) if(splitVal[1] == '+'): tempval = 0 if(splitVal[3].upper() in declareVar()): tempval = int(declareVar().get(splitVal[2].upper())) + int(declareVar().get(splitVal[3].upper())) else: tempval = int(declareVar().get(splitVal[2].upper())) + int(splitVal[3]) elif(splitVal[1] == '*'): tempval = 0 if(splitVal[3].upper() in declareVar()): tempval = declareVar().get(splitVal[2].upper()).replace("\"","") * int(declareVar().get(splitVal[3].upper())) else: tempval = declareVar().get(splitVal[2].upper()).replace("\"","") * int(splitVal[3]) elif(splitVal[1] == '-'): tempval = 0 if(splitVal[3].upper() in declareVar()): tempval = int(declareVar().get(splitVal[2].upper())) - int(declareVar().get(splitVal[3].upper())) else: tempval = int(declareVar().get(splitVal[2].upper())) - int(splitVal[3]) elif(splitVal[1] == '&'): if(splitVal[3].upper() in declareVar()): tempval = declareVar().get(splitVal[2].upper()) + splitVal[3] else: tempval = declareVar().get(splitVal[2].upper()) + splitVal[3] declareVar().update({splitVal[0].upper():str(tempval)}) else: try: if(splitVal[0] is "" or splitVal[1] is ""): raise else: pass except: raise TooFewOperands("Too few operands",splitVal[0],splitVal[1]) try: if(splitVal[0].upper() in declareVar() and splitVal[1].upper() in declareVar()): pass else: raise except: raise VarNotDefined("Variable not defined",splitVal[0],splitVal[1]) tempval = declareVar().get(splitVal[1].upper()) declareVar().update({splitVal[0].upper():str(tempval)})
def checkForIf(input, verbose, count): if("Loop" not in input): input = "Loop " + input.rstrip('\n') if("IF" in input.rstrip('\n') or "if" in input.rstrip('\n')): splitVal = input.rstrip('\n').split()[1:] if(verbose == 1): printStatement = "executing line " + str(count) + ": " + str(' '.join(input.rstrip('\n').split()).replace("\"","")) print(printStatement) tempval = 0 try: if(splitVal[2] is "" or splitVal[3] is ""): raise else: pass except: raise TooFewOperands("Too few operands",splitVal[1],splitVal[2]) shouldCheckForVar = True try: if(splitVal[2].isdigit() and splitVal[3].upper() in declareVar()): iVal = int(splitVal[2]) shouldCheckForVar = False pass except: raise InvalidValueType("Invalid value",splitVal[2]) if(shouldCheckForVar): try: if(splitVal[2].upper() in declareVar() and splitVal[3].upper() in declareVar()): pass else: raise except: raise VarNotDefined("Variable not defined",splitVal[2],splitVal[3]) try: if(splitVal[1] == '>' or splitVal[1] == '>='): pass else: raise except: raise InvalidExpression("Invalid expression",val) try: if(splitVal[4].upper() in printLabels()): pass else: raise except: raise VarNotDefined("Label not defined",splitVal[4]) try: if(splitVal[1] == '>'): if(splitVal[2].isdigit() and splitVal[3].upper() in declareVar()): tempval = int(splitVal[2]) > int(declareVar().get(splitVal[3].upper())) elif(splitVal[2].upper() in declareVar() and splitVal[3].upper() in declareVar()): tempval = int(declareVar().get(splitVal[2].upper())) > int(declareVar().get(splitVal[3].upper())) elif(splitVal[2].isdigit() and splitVal[3].upper() in declareVar()): tempval = int(declareVar().get(splitVal[2].upper())) > int(splitVal[3]) else: tempval = int(declareVar().get(splitVal[2].upper())) > int(declareVar().get(splitVal[3].upper())) else: if(splitVal[2].isdigit() and splitVal[3].upper() in declareVar()): tempval = int(splitVal[2]) > int(declareVar().get(splitVal[3].upper())) elif(splitVal[2].upper() in declareVar() and splitVal[3].upper() in declareVar()): tempval = int(declareVar().get(splitVal[2].upper())) > int(declareVar().get(splitVal[3].upper())) elif(splitVal[2].isdigit() and splitVal[3].upper() in declareVar()): tempval = int(declareVar().get(splitVal[2].upper())) > int(splitVal[3]) else: tempval = int(declareVar().get(splitVal[2].upper())) >= int(declareVar().get(splitVal[3].upper())) return(tempval,splitVal[4]) except: raise InvalidValueType("Invalid value",splitVal[2],splitVal[3]) else: return(False,"")
def main(): varTypeD = {} # dictionary for var data type varValueD = {} # dictionary for var value labelD = {} # dictionary for labels fileL = [] # lines of file stored as entry in list lineNum = 1 # line number in file NUM_ARGS = 2 # number of args in command line if len(sys.argv) < NUM_ARGS: print("filename needed as command argmuent") sys.exit(1) elif len(sys.argv) > NUM_ARGS: #TODO use formated printing print('arguments expected : %d, arguments given: %d' % (NUM_ARGS, len(sys.argv))) sys.exit(1) # get the file name filename = sys.argv[1] if os.path.isfile(filename) == False: print("%s is not a file" % (filename)) sys.exit(1) # compile the regular expressions labelRE = re.compile(r'\s*(\w+):') varRE = re.compile(r'^VAR\s([a-zA-Z]+)\s([a-zA-Z]+)\s"?(.*?)"?$') # parse the file, store labels and variables file = open(filename, 'r') print("BEEP source code in %s:" % (filename)) while True: line = file.readline() if line == "": break labelMO = labelRE.match(line) if labelMO != None: label = labelMO.group(1).upper() value = labelD.get(label, None) if value != None: print( "***Error: label %s appears on multiple lines: %d and %d" % (label, labelD[label], lineNum)) else: labelD[label] = lineNum else: varMO = varRE.match(line) if varMO != None: declareVar(varMO, varTypeD, varValueD) fileL.append(line) # print line and line number print(lineNum, line) lineNum += 1 # print labels and variables printVariables(varTypeD, varValueD) printLabels(labelD)
if (start == 0): intro = "BEEP source code in " fileNameInput = fileinput.filename() + ':' print(intro + fileNameInput) start += 1 if (len(input.split()) != 0): splitIt = input.rstrip('\n').split()[0:1] getType(input) getLabel(splitIt, input, count) count += 1 p = str(count) + '. ' + input.rstrip('\n') print(p) print("Variables:") print(" Variable Type Value ") # prints each dictonary value and key in sorted order for (key, value), (key2, value2) in sorted( zip(printVariables().items(), declareVar().items())): p = ' '.ljust(4) + key.ljust(13) + value.ljust(10) + value2.ljust(10) print(p) print("Labels:") print(" Label Statement") for (key, value) in sorted(printLabels().items()): p = ' '.ljust(4) + key.ljust(13) + value.ljust(10) print(p) executionFunc()
def main(): varTypeD = {} varValueD = {} labelD = {} vFlag = 0 if len(sys.argv) == 3: if sys.argv[2] == "-v": vFlag = 1 infile = open(sys.argv[1], "r") input_lines = [] label_list = [] i = 1 #Traverse each line in the file for line in infile: #Print source code with subscripts print(str(i), ". ", line) #print line,len(line) if (len(line) <= 5): continue input_lines.append(line) splitted_line = line.split() #If the first word is VAR, declare it as a varible in dictionary #print len(splitted_line) if splitted_line[0] == "VAR": #if splitted_line[1] == "string": if len(splitted_line) < 4: splitted_line.append("\"NULL\"") splitted_line[3] = splitted_line[3][1:-1] #print "Splitted LINE", splitted_line declareVar(splitted_line, varTypeD, varValueD) #If the first word ends with a colon, delare as label in labelD matched = re.search(r'.*:', splitted_line[0]) splitted_line[0] = splitted_line[0][:-1].upper() #If the regex matches, then check if label has already been used if matched != None: #If label has already been used, print Error if splitted_line[0] in label_list: print("***Error: label ", splitted_line[0], "appears on multiple lines:", labelD[splitted_line[0]], "and", i) #Else add label to label_list and declare it the labeD dictionary else: label_list.append(splitted_line[0]) labelD[splitted_line[0]] = i i += 1 infile.close() printVariables(varTypeD, varValueD) printLabels(labelD) print("execution begins ...") i = 0 lines_executed = 0 #loop through lines of beep source code while (i < len(input_lines)): lines_executed += 1 if (lines_executed > 5000): print("Loop Error: Infinite Loop Likely Occured") break splitted_line = input_lines[i].split() # match for label matched = re.search(r'.*:', splitted_line[0]) if vFlag == 1: print("executing line", i, ":", input_lines[i]) #pop label and execute the rest of the statemtn if matched != None: splitted_line.pop(0) if splitted_line[0] == "ASSIGN": assignVar(splitted_line, varValueD) elif splitted_line[0] == "PRINT": printLine(splitted_line[1:], varValueD) elif splitted_line[0] == "if" or splitted_line[0] == "IF": #print(splitted_line) i = evalIf(splitted_line, varValueD, labelD, i) #print "i after if",i elif splitted_line[0] == "GOTO": i = labelD[splitted_line[1].upper()] - 2 i += 1 #print "FINAL DITCITONRY: ",varValueD #print "Fineal Labels",labelD print("execution ends", lines_executed, "lines executed")
def main(argv): varTypeD = {} # dictionary for variable types varValueD = {} # dictionary for variable values labelD = {} # dictionary for labels source = [] # source code lineNum = 1 # file line number NUM_ARGS = 2 # Minimum number of args MAX_ARGS = 3 # Maximum number of args verbose = False # Flag for -v option numArgs = len(argv) # check for correct number of arguments if numArgs < NUM_ARGS or numArgs > MAX_ARGS: print("Usage: %s <BEEP source> [-v]" % (argv[0])) sys.exit(1) # validate filename and optional command line arguments filename = argv[1] if '-v' in argv: verbose = True elif numArgs == MAX_ARGS: print("Usage: %s <BEEP source> [-v]" % (argv[0])) sys.exit(1) if os.path.isfile(filename) == False: print("Error: %s is not a file" % (filename)) sys.exit(1) # compile the regular expressions labelRE = re.compile(r'\s*(\w+):') varRE = re.compile(r'^VAR\s([\w]+)\s([\w]+)\s"?(.*?)"?$') # parse file for labels and variables and print contents file = open(filename, "r", encoding='latin-1') print('BEEP source code in %s:' % (filename)) while True: line = file.readline() if line == "": break if labelRE.match(line) != None: labelMO = labelRE.match(line) label = labelMO.group(1).upper() if labelD.get(label, None) != None: print( "***Error: label '%s' appears on multiple lines: %d and %d" % (label, labelD[label], lineNum)) else: labelD[label] = lineNum elif varRE.match(line) != None: varMO = varRE.match(line) declareVar(varMO, varTypeD, varValueD) source.append(line) # print line and line number print("%d. %s" % (lineNum, line)) lineNum += 1 # print labels and variables printVariables(varTypeD, varValueD) printLabels(labelD) executor = Executor(varTypeD, varValueD, labelD, source) # execute the source if verbose: executor.execute(source, verbose=True) else: executor.execute(source)