def evaluateMacro(stringToEvaluate, returnParameterNames=False):
	if(stringToEvaluate.startswith("exec(")):
		exec(stringToEvaluate)
		return ""
	#print("Macro to evaluate: " + str(stringToEvaluate))
	if(returnParameterNames == False):
		#print(getParameterNames(stringToEvaluate))
		pass
	global thingsToEvaluate
	if (thingsToEvaluate == []):
		thingsToEvaluate = theThingsToEvaluate()
		#print(thingsToEvaluate)
		addThingsToEvaluate = [
		removeParentheses("(foo = (bar [ baz ]))"),
		[["(unless foo bar)", "(foo unless bar)"], "(if (not foo) then bar)"],
		[["(foo squared)"], "(foo to the power of 2)"],
		[["(foo cubed)"], "(foo to the power of 3)"],
		[["(square root of foo)"], "(foo to the power of -2)"],
		[["(foo += bar)"], "(foo = (foo + bar))"],
		[["(foo *= bar)"], "(foo = (foo * bar))"],
		[["(foo -= bar)"], "(foo = (foo - bar))"],
		[["(foo /= bar)"], "(foo = (foo / bar))"],
		[["(foo ++)"], "(foo += 1)"],
		[["(foo != bar)"], "(not (foo == bar))"],
		[["(foo = foo + bar)"], "(foo += bar)"],
		[["(foo = foo - bar)"], "(foo -= bar)"],
		[["(foo = foo * bar)"], "(foo *= bar)"],
		[["(foo if bar unless baz)"], "(foo if (bar and (not baz)))"],
		[["(print the type of foofoo)"], "(print (the type of foofoo)))"],
		[["(foo percent of bar)"], "(foo * 0.01 * bar)"],
		]
		for current in addThingsToEvaluate:
			print(thingsToEvaluate[len(thingsToEvaluate)-1])
			thingsToEvaluate += [[current[0], getParameterNames(current[1]), evaluateMacro(current[1])]]
	stringToEvaluate = addParentheses(stringToEvaluate)	
	#print("String to evaluate with added parentheses:\n" + stringToEvaluate)
	#stringToEvaluate = addOpeningAndClosingParentheses(stringToEvaluate)
	#print("Evaluate the macro " + stringToEvaluate)
	#print(splitMacroWithWhitespace(stringToEvaluate))
	theArr = printMatches(replaceParenthesesWithSymbols(stringToEvaluate));
	#theData = OneOrMore(nestedExpr()).parseString(stringToEvaluate)
	#print(theData)
	whitespaceSplitString = splitMacroWithWhitespace(stringToEvaluate);
	#print("The string split with whitespace is " + str(whitespaceSplitString))
	separatorCharacter = whitespaceSplitString[1]
	if(everyOtherIsTheSame(whitespaceSplitString)):
		#print("Every other character in " + str(whitespaceSplitString) + " is " + str(separatorCharacter))
		
		nonSeparatorParts = getNonSeparatorParts(stringToEvaluate)
		
		if returnParameterNames == True:
			thingToReturn = {}
			for idx,current in enumerate(nonSeparatorParts):
				thingToReturn[idx] = current
			return thingToReturn
		
		#print("The non-separator parts are " + str(nonSeparatorParts))
		
		
		for idx, current in enumerate(nonSeparatorParts):
			if(current.startswith("(")):
				print(current)
				nonSeparatorParts[idx] = evaluateMacro(current)
		if(separatorCharacter in ["+", "plus"]):
			return "add([" + ", ".join(nonSeparatorParts) + "])"
		elif(separatorCharacter in ["-", "minus"]):
			return "subtract([" + ", ".join(nonSeparatorParts) + "])"
		elif(separatorCharacter in ["*", "times"]):
			return "multiply([" + ", ".join(nonSeparatorParts) + "])" 
		elif(separatorCharacter in ["||", "or", "|"]):
			return "Or([" + ", ".join(nonSeparatorParts) + "])"
		elif(separatorCharacter in ["and", "&&", "&"]):
			return "And([" + ", ".join(nonSeparatorParts) + "])"
		elif(separatorCharacter in [","]):
			return "[" + ", ".join(nonSeparatorParts) + "]" 
		elif(separatorCharacter in [";"]):
			return "seriesOfStatements([" + ", ".join(nonSeparatorParts) + "])"
		
	#print("String to evaluate: " + stringToEvaluate)
	#print(getMatchingRegex(stringToEvaluate))
	
	
	
	#This code does not do
	#if returnParameterNames == False:
		#if(getMatchingRegex("(foo has the same meaning as bar)") == getMatchingRegex(stringToEvaluate)):
			#print("The input is a syntax definition: " + stringToEvaluate)
			#thingToChange = evaluateMacro(stringToEvaluate, returnParameterNames=True);
			#print(thingToChange)
			#print(thingToChange['foo'])
			#print(thingToChange['bar'])
			#thingsToEvaluate += [[thingToChange['foo'], getParameterNames(thingToChange['bar']), evaluateMacro(thingToChange['bar'])]]
			#print(thingsToEvaluate)
	
	
	#else:
		#print(str(whitespaceSplitString) + " is not an arithmetic expression.")
	
	for current in thingsToEvaluate:
		for currentInputString in current[0]:
			if returnParameterNames == True:
				theResult = evaluateMacroWithSpecificString(inputString=stringToEvaluate,stringThatMatchesRegex=currentInputString,variableNames=current[1],stringToReturn=current[2], returnParameters = True)
			else:
				theResult = evaluateMacroWithSpecificString(stringToEvaluate, currentInputString, current[1], current[2])
			if(theResult != None):
				if(type(theResult) == str and theResult.startswith("exec(")):
					exec(theResult)
					return ""
				else:
					return theResult
			
	if(len(theArr) == 1):
		matchingRegex = theArr[0]["matchingRegex"]
		'''
		paramArray = splitMacroWithParentheses(stringToEvaluate)
		
		#Evaluate these before the macro has been evaluated:
		if matchingRegex == getMatchingRegex("(foo and bar are equal)"):
			return evaluateMacro("(" + paramArray[0] + " equals " + paramArray[2] + ")")
		elif matchingRegex == getMatchingRegex("(shuffle foo randomly)"):
			return evaluateMacro("(randomly shuffle " + paramArray[1] + ")")
		#Evaluate these after the macro has been evaluated
		for idx, current in enumerate(paramArray):
			if(current.startswith("(") and current.endswith(")")):
				paramArray[idx] = evaluateMacro(current)
		"(foo is divisible by bar)"
			"(foo % bar == 0)"
		"(randomly shuffle foo)"
			"my_shuffle(foo)"
		"(foo in reverse order)"
			"foo[::-1]"
		"(sort foo in alphabetical order)"
			"sorted(foo)"
		"(the type of foo)"
			"type(foo)"
		"(sort foo from largest to smallest)"
			"sorted(foo)"
		"(sort foo from smallest to largest)"
			"sorted(foo).reverse()"
		"(foo is an integer)"
			"(type(foo) == int)"
		"(all locations of foo in bar)"
			"[i for i, x in enumerate(bar) if x == foo]"
		"(pick random from foo)"
			"choice(foo)"
		"(dimensions of foo)"
			"arrayDimensions(foo)"
		"(print foo)"
			"(puts(foo))"
		"(foo from bar to baz)"
			"(substring of foo between bar and baz)"
		"(foo and bar)"
			"(foo and bar)"
		"(sum of each number in foo)"):
			"sumOfAllNums(foo)"
		"(return foo)"
			"Return(foo),"
		if(toReturn != ""
			#print(stringToEvaluate + " becomes (" + toReturn + ") which evaluates to " + str(eval(toReturn)))
			#stringToReturn = str(eval(toReturn))
			#print(stringToEvaluate + " becomes \n     " + toReturn + "\n")
			return toReturn
		else:
		'''
		raise Exception(stringToEvaluate + " matches " + matchingRegex.pattern + ", but the output is not yet defined in evaluateMacro")
		
	elif(len(theArr) == 0):
		raise Exception(replaceParenthesesWithSymbols(stringToEvaluate) + " does not match any regular expression.")
	else:
		print(stringToEvaluate) + " matches more than one regular expression!"
Beispiel #2
0
def evaluateMacro(stringToEvaluate, returnParameterNames=False):
    if (stringToEvaluate.startswith("exec(")):
        exec(stringToEvaluate)
        return ""
    #print("Macro to evaluate: " + str(stringToEvaluate))
    if (returnParameterNames == False):
        #print(getParameterNames(stringToEvaluate))
        pass
    global thingsToEvaluate
    if (thingsToEvaluate == []):
        thingsToEvaluate = theThingsToEvaluate()
        #print(thingsToEvaluate)
        addThingsToEvaluate = [
            removeParentheses("(foo = (bar [ baz ]))"),
            [["(unless foo bar)", "(foo unless bar)"],
             "(if (not foo) then bar)"],
            [["(foo squared)"], "(foo to the power of 2)"],
            [["(foo cubed)"], "(foo to the power of 3)"],
            [["(square root of foo)"], "(foo to the power of -2)"],
            [["(foo += bar)"], "(foo = (foo + bar))"],
            [["(foo *= bar)"], "(foo = (foo * bar))"],
            [["(foo -= bar)"], "(foo = (foo - bar))"],
            [["(foo /= bar)"], "(foo = (foo / bar))"],
            [["(foo ++)"], "(foo += 1)"],
            [["(foo != bar)"], "(not (foo == bar))"],
            [["(foo = foo + bar)"], "(foo += bar)"],
            [["(foo = foo - bar)"], "(foo -= bar)"],
            [["(foo = foo * bar)"], "(foo *= bar)"],
            [["(foo if bar unless baz)"], "(foo if (bar and (not baz)))"],
            [["(print the type of foofoo)"], "(print (the type of foofoo)))"],
            [["(foo percent of bar)"], "(foo * 0.01 * bar)"],
        ]
        for current in addThingsToEvaluate:
            print(thingsToEvaluate[len(thingsToEvaluate) - 1])
            thingsToEvaluate += [[
                current[0],
                getParameterNames(current[1]),
                evaluateMacro(current[1])
            ]]
    stringToEvaluate = addParentheses(stringToEvaluate)
    #print("String to evaluate with added parentheses:\n" + stringToEvaluate)
    #stringToEvaluate = addOpeningAndClosingParentheses(stringToEvaluate)
    #print("Evaluate the macro " + stringToEvaluate)
    #print(splitMacroWithWhitespace(stringToEvaluate))
    theArr = printMatches(replaceParenthesesWithSymbols(stringToEvaluate))
    #theData = OneOrMore(nestedExpr()).parseString(stringToEvaluate)
    #print(theData)
    whitespaceSplitString = splitMacroWithWhitespace(stringToEvaluate)
    #print("The string split with whitespace is " + str(whitespaceSplitString))
    separatorCharacter = whitespaceSplitString[1]
    if (everyOtherIsTheSame(whitespaceSplitString)):
        #print("Every other character in " + str(whitespaceSplitString) + " is " + str(separatorCharacter))

        nonSeparatorParts = getNonSeparatorParts(stringToEvaluate)

        if returnParameterNames == True:
            thingToReturn = {}
            for idx, current in enumerate(nonSeparatorParts):
                thingToReturn[idx] = current
            return thingToReturn

        #print("The non-separator parts are " + str(nonSeparatorParts))

        for idx, current in enumerate(nonSeparatorParts):
            if (current.startswith("(")):
                print(current)
                nonSeparatorParts[idx] = evaluateMacro(current)
        if (separatorCharacter in ["+", "plus"]):
            return "add([" + ", ".join(nonSeparatorParts) + "])"
        elif (separatorCharacter in ["-", "minus"]):
            return "subtract([" + ", ".join(nonSeparatorParts) + "])"
        elif (separatorCharacter in ["*", "times"]):
            return "multiply([" + ", ".join(nonSeparatorParts) + "])"
        elif (separatorCharacter in ["||", "or", "|"]):
            return "Or([" + ", ".join(nonSeparatorParts) + "])"
        elif (separatorCharacter in ["and", "&&", "&"]):
            return "And([" + ", ".join(nonSeparatorParts) + "])"
        elif (separatorCharacter in [","]):
            return "[" + ", ".join(nonSeparatorParts) + "]"
        elif (separatorCharacter in [";"]):
            return "seriesOfStatements([" + ", ".join(nonSeparatorParts) + "])"

    #print("String to evaluate: " + stringToEvaluate)
    #print(getMatchingRegex(stringToEvaluate))

    #This code does not do
    #if returnParameterNames == False:
    #if(getMatchingRegex("(foo has the same meaning as bar)") == getMatchingRegex(stringToEvaluate)):
    #print("The input is a syntax definition: " + stringToEvaluate)
    #thingToChange = evaluateMacro(stringToEvaluate, returnParameterNames=True);
    #print(thingToChange)
    #print(thingToChange['foo'])
    #print(thingToChange['bar'])
    #thingsToEvaluate += [[thingToChange['foo'], getParameterNames(thingToChange['bar']), evaluateMacro(thingToChange['bar'])]]
    #print(thingsToEvaluate)

    #else:
    #print(str(whitespaceSplitString) + " is not an arithmetic expression.")

    for current in thingsToEvaluate:
        for currentInputString in current[0]:
            if returnParameterNames == True:
                theResult = evaluateMacroWithSpecificString(
                    inputString=stringToEvaluate,
                    stringThatMatchesRegex=currentInputString,
                    variableNames=current[1],
                    stringToReturn=current[2],
                    returnParameters=True)
            else:
                theResult = evaluateMacroWithSpecificString(
                    stringToEvaluate, currentInputString, current[1],
                    current[2])
            if (theResult != None):
                if (type(theResult) == str and theResult.startswith("exec(")):
                    exec(theResult)
                    return ""
                else:
                    return theResult

    if (len(theArr) == 1):
        matchingRegex = theArr[0]["matchingRegex"]
        '''
		paramArray = splitMacroWithParentheses(stringToEvaluate)
		
		#Evaluate these before the macro has been evaluated:
		if matchingRegex == getMatchingRegex("(foo and bar are equal)"):
			return evaluateMacro("(" + paramArray[0] + " equals " + paramArray[2] + ")")
		elif matchingRegex == getMatchingRegex("(shuffle foo randomly)"):
			return evaluateMacro("(randomly shuffle " + paramArray[1] + ")")
		#Evaluate these after the macro has been evaluated
		for idx, current in enumerate(paramArray):
			if(current.startswith("(") and current.endswith(")")):
				paramArray[idx] = evaluateMacro(current)
		"(foo is divisible by bar)"
			"(foo % bar == 0)"
		"(randomly shuffle foo)"
			"my_shuffle(foo)"
		"(foo in reverse order)"
			"foo[::-1]"
		"(sort foo in alphabetical order)"
			"sorted(foo)"
		"(the type of foo)"
			"type(foo)"
		"(sort foo from largest to smallest)"
			"sorted(foo)"
		"(sort foo from smallest to largest)"
			"sorted(foo).reverse()"
		"(foo is an integer)"
			"(type(foo) == int)"
		"(all locations of foo in bar)"
			"[i for i, x in enumerate(bar) if x == foo]"
		"(pick random from foo)"
			"choice(foo)"
		"(dimensions of foo)"
			"arrayDimensions(foo)"
		"(print foo)"
			"(puts(foo))"
		"(foo from bar to baz)"
			"(substring of foo between bar and baz)"
		"(foo and bar)"
			"(foo and bar)"
		"(sum of each number in foo)"):
			"sumOfAllNums(foo)"
		"(return foo)"
			"Return(foo),"
		if(toReturn != ""
			#print(stringToEvaluate + " becomes (" + toReturn + ") which evaluates to " + str(eval(toReturn)))
			#stringToReturn = str(eval(toReturn))
			#print(stringToEvaluate + " becomes \n     " + toReturn + "\n")
			return toReturn
		else:
		'''
        raise Exception(stringToEvaluate + " matches " +
                        matchingRegex.pattern +
                        ", but the output is not yet defined in evaluateMacro")

    elif (len(theArr) == 0):
        raise Exception(
            replaceParenthesesWithSymbols(stringToEvaluate) +
            " does not match any regular expression.")
    else:
        print(stringToEvaluate) + " matches more than one regular expression!"
def getStringOutput(toTest, reallyNewInfoArray):
    #print(toTest)
    toTest = "(" + addParentheses(toTest) + ")"
    #print("With added parentheses:")
    #print(toTest)
    return evaluateMacro(stringToSyntaxTree(toTest), reallyNewInfoArray)
Beispiel #4
0
def getStringOutput(toTest, reallyNewInfoArray):
    #print(toTest)
    toTest = "(" + addParentheses(toTest) + ")"
    #print(toTest)
    return evaluateMacro(stringToSyntaxTree(toTest), reallyNewInfoArray)