Beispiel #1
0
def parse_expr(s):
    iend, tree = ep.tokenTree(s, 0, len(s), 0)
    print tree
    #print "::::: ", ep.tokenTree2string(s,tree, 0)
    print ep.tokenTree2string(s, tree, 0, indent=True)
    ep.walkTree_2(s, tree, 0, checkVar, empty, checkFunc)
    exit()
    def test_validate_parentheses(self):
        # true cases
        with self.subTest():
            self.assertTrue(EP.validate_parentheses(
                ('(', 'p', ')'))[0])
        with self.subTest():
            self.assertTrue(EP.validate_parentheses(
                ('(', '(', 'p', ')', ')'))[0])
        with self.subTest():
            self.assertTrue(EP.validate_parentheses(
                ('(', 'p', ')', '+', '(', 'q', ')'))[0])
        with self.subTest():
            self.assertTrue(EP.validate_parentheses(
                ('(', '(', 'p', ')', '+', '(', 'q', ')', ')'))[0])
        with self.subTest():
            self.assertTrue(EP.validate_parentheses(
                ('p', '+', 'q'))[0])

        # false cases
        with self.subTest():
            self.assertFalse(EP.validate_parentheses(
                ('(', 'p'))[0])
        with self.subTest():
            self.assertFalse(EP.validate_parentheses(
                ('p', ')'))[0])
        with self.subTest():
            self.assertFalse(EP.validate_parentheses(
                ('(', '(', 'p', ')'))[0])
        with self.subTest():
            self.assertFalse(EP.validate_parentheses(
                ('(', 'p', ')', '+', 'q', ')'))[0])
Beispiel #3
0
    def generate_table(self, show_message):
        # convert the entered string into a standard format
        expression = self.entry.get()
        print("Expression: {}".format(expression))

        # validate that the expression is consistant with the rules
        try:
            expression = EP.format_expression(expression)
            EP.validate(expression)
            # generate table
            # draw table
        except EP.InvalidExpressionException as ex:
            if show_message:
                messagebox.showinfo('Error', ex)
        except Exception as ex:
            print('Unexpected exception! Exception message: {}'.format(
                ex.message))
 def test_get_unique_variables(self):
     # basic case
     with self.subTest():
         self.assertEqual(EP.get_unique_variables(
             ('p', '+', 'q')),
             ['p', 'q'])
     # with repetition
     with self.subTest():
         self.assertEqual(EP.get_unique_variables(
             ('p', '+', '~', 'p')),
             ['p'])
     with self.subTest():
         self.assertEqual(EP.get_unique_variables(
             ('p', '+', 'q', '*', 'p')),
             ['p', 'q'])
     # with only constants
     with self.subTest():
         self.assertEqual(EP.get_unique_variables(
             ('false', '+', 'true')),
             [])
     # complex expression
     with self.subTest():
         self.assertEqual(EP.get_unique_variables(
             ('p', '+', 'q', '*', 'r', '>', 's', '=', 't', '=', '~', 'u',
              '=', '(', 'p', '+', 'q', ')')),
             ['p', 'q', 'r', 's', 't', 'u'])
     # mulitchar variables
     with self.subTest():
         self.assertEqual(EP.get_unique_variables(
             ('first', '+', 'last')),
             ['first', 'last'])
Beispiel #5
0
	def __init__(self, fn):
		self.currentOp = None
		self.filename = fn
		self.bs = BScanner(self.filename)
		self.exp = ExpressionParser(self.bs)
		self.forwardReferences = []
		self.loopStatus = Status.CONTINUE
		self.nextLocation = 1
		self.nextOp = None
		self.operand = None
		self.scope = SymbolScope.GLOBAL
		self.structureStack = []
		self.suppressAdvance = False
		self.jvm = self.exp.jvm
		self.AC = ActionTable(self)
		self.advances = 0
 def test_not_replacement(self):
     with self.subTest():
         self.assertEqual(EP.standardize_string('a not b'), 'a ~ b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('not b'), '~ b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('testnot'), 'testnot')
     with self.subTest():
         self.assertEqual(EP.standardize_string('nottest'), 'nottest')
     with self.subTest():
         self.assertEqual(EP.standardize_string('!b'), '~ b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('! b'), '~ b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('~'), '~')
 def test_has_invalid_chars(self):
     with self.subTest():
         self.assertEqual(EP.has_invalid_chars('&'), '&')
     with self.subTest():
         self.assertIsNone(EP.has_invalid_chars('a + b'))
     with self.subTest():
         self.assertIsNone(EP.has_invalid_chars('a * b'))
     with self.subTest():
         self.assertIsNone(EP.has_invalid_chars('a > b'))
     with self.subTest():
         self.assertIsNone(EP.has_invalid_chars('a = b'))
     with self.subTest():
         self.assertIsNone(EP.has_invalid_chars('~ b'))
     with self.subTest():
         self.assertIsNone(EP.has_invalid_chars('( b )'))
 def test_if_replacement(self):
     with self.subTest():
         self.assertEqual(EP.standardize_string('a if b'), 'a > b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('testif'), 'testif')
     with self.subTest():
         self.assertEqual(EP.standardize_string('iftest'), 'iftest')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a -> b'), 'a > b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a --> b'), 'a > b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('>'), '>')
 def test_or_replacement(self):
     with self.subTest():
         self.assertEqual(EP.standardize_string('a or b'), 'a + b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('testor'), 'testor')
     with self.subTest():
         self.assertEqual(EP.standardize_string('ortest'), 'ortest')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a\\/b'), 'a + b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a \\/ b'), 'a + b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('+'), '+')
 def test_and_replacement(self):
     with self.subTest():
         self.assertEqual(EP.standardize_string('a and b'), 'a * b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('testand'), 'testand')
     with self.subTest():
         self.assertEqual(EP.standardize_string('andtest'), 'andtest')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a/\\b'), 'a * b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a /\\ b'), 'a * b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('*'), '*')
import sys

sys.path.append("../")

from ExpressionParser import *

exp = ExpressionParser()

exp.testExpression("check/e2.b")
 def test_var_to_placeholder(self):
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('+'), '+')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('*'), '*')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('~'), '~')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('>'), '>')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('='), '=')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('('), '(')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder(')'), ')')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('true'), 'true')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('false'), 'false')
     with self.subTest():
         self.assertIsNone(EP.var_to_placeholder(None))
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('p'), 'VAR')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('q'), 'VAR')
     with self.subTest():
         self.assertEqual(EP.var_to_placeholder('andorvar'), 'VAR')
 def test_trailing_spaces_replacement(self):
     self.assertEqual(EP.standardize_string(' a '), 'a')
 def test_complex_expression_no_spaces(self):
     self.assertEqual(EP.standardize_string('a/\\b\\/c-->d<->e!f'),
                      'a * b + c > d = e ~ f')
 def test_complex_expression(self):
     self.assertEqual(EP.standardize_string(
         'a and b or c if d iff e not f'),
         'a * b + c > d = e ~ f')
    def test_validate_neighbors(self):
        # cases with none
        with self.subTest():
            self.assertTrue(EP.validate_neighbors(None, 'p', '+')[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors(None, '~', 'p')[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors(None, '~', '(')[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors(None, '(', 'p')[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('*', 'p', None)[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('~', 'p', None)[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('p', ')', None)[0])

        # basic valid cases
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('p', '+', 'q')[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('p', '*', 'q')[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('p', '>', 'q')[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('p', '=', 'q')[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('~', 'p', '+')[0])
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('(', 'p', ')')[0])

        # double negation is valid
        with self.subTest():
            self.assertTrue(EP.validate_neighbors('~', '~', 'p')[0])

        # invalid cases
        # double vars
        with self.subTest():
            self.assertFalse(EP.validate_neighbors('p', 'q', '+')[0])
        with self.subTest():
            self.assertFalse(EP.validate_neighbors('+', 'p', 'q')[0])

        # double binary ops
        with self.subTest():
            self.assertFalse(EP.validate_neighbors('+', '>', 'q')[0])
        with self.subTest():
            self.assertFalse(EP.validate_neighbors('p', '=', '+')[0])

        # invalid parens
        with self.subTest():
            self.assertFalse(EP.validate_neighbors(')', '(', 'p')[0])
        with self.subTest():  # empty parens is bad
            self.assertFalse(EP.validate_neighbors('(', ')', 'p')[0])
        with self.subTest():
            self.assertFalse(EP.validate_neighbors('p', '(', ')')[0])
        with self.subTest():
            self.assertFalse(EP.validate_neighbors('p', ')', '(')[0])
        with self.subTest():
            self.assertFalse(EP.validate_neighbors(')', '~', 'p')[0])
        with self.subTest():
            self.assertFalse(EP.validate_neighbors('(', '>', 'p')[0])

        # unlcosed parens
        with self.subTest():
            self.assertFalse(EP.validate_neighbors('~', '(', None)[0])
        with self.subTest():
            self.assertFalse(EP.validate_neighbors(None, ')', '*')[0])
Beispiel #17
0
#bexp.py

import sys
from ExpressionParser import *

if len(sys.argv) == 1 or len(sys.argv) > 3 or not ".txt" in sys.argv[1]:
	#print "\nUsage: bexp <filename>\n"

fileName = sys.argv[len(sys.argv) - 1]
if sys.argv[1] == "-d":
	Compiler.debugOn()

exp = ExpressionParser()
exp.testExpression(fileName)
#print "done"
Beispiel #18
0
class BParser(ParserBase):
	#public
	def __init__(self, fn):
		self.currentOp = None
		self.filename = fn
		self.bs = BScanner(self.filename)
		self.exp = ExpressionParser(self.bs)
		self.forwardReferences = []
		self.loopStatus = Status.CONTINUE
		self.nextLocation = 1
		self.nextOp = None
		self.operand = None
		self.scope = SymbolScope.GLOBAL
		self.structureStack = []
		self.suppressAdvance = False
		self.jvm = self.exp.jvm
		self.AC = ActionTable(self)
		self.advances = 0
		
		#print self.currentOp, self.operand, self.nextOp, "1"
	
	#def compile(self, filename):
	#	self.bs = BScanner(filename)
	#	self.bs.debugOn()
	#	while self.nextOp.getTokenType() != TokenType.END_FILE:
	#		self.advance()
	def compile(self):
		#self.bs.debugOn()
		#try:
			main = Symbol("Main", SymbolType.FORWARD_FUNCTION, SymbolScope.GLOBAL)
			self.bs._symbols.insert(main)
			
			write = Symbol("write", SymbolType.DEFINED_FUNCTION, SymbolScope.GLOBAL)
			self.bs._symbols.insert(write)
			if self.bs.debugging():
				self.bs._symbols.dump()
			self.nextOp = self.bs.nextToken()
			print self.nextOp
			if self.nextOp.toString() == "void":
				sym = self.bs._symbols.get("Main")
				self.saveForwardReference(sym, self.jvm.getPC())
				self.jvm.emit3byte(Opcode.GOTO, 0)
			elif self.nextOp.toString() != "int":
				self.setError("Invalid program. Illegal first token.")
				return
			while self.loopStatus != Status.EXIT:
				print ".",
				self.advance()
				self._generate(self.currentOp, self.nextOp)
			self.fillForwardReferences()
			self.jvm.finish()
		#except:
			#self._debugFile.close()
			#pass
    
    
    
    
	
	def advance(self):
		#if self.suppressAdvance ? self.supressAdvance = False : pass
		
	  	if self.suppressAdvance == True:
	  		self.suppressAdvance = False
			return
		
		if self.operand != None:
			self.operand = None
		
		self.currentOp = self.nextOp
		try:
			nt = self.bs.nextToken()
		except:
			nt = Token(TokenType.END_FILE, 'EOF')
		#print self.currentOp, self.currentOp.toString(), nt, nt.toString()
		if nt == "":
			return
		if nt.getTokenType() == TokenType.END_FILE:
			self.nextOp = nt
			return
		elif nt.getTokenType() == TokenType.SYMBOL or nt.getTokenType() == TokenType.LITERAL:
			self.operand = nt
			print "OPERAND SET", self.operand.toString()
			try:
				nt = self.bs.nextToken()
			except:
				nt = Token(TokenType.END_FILE, 'EOF')
		 	
		self.nextOp = nt
		
		print hex(self.jvm.getPC()), "(", self.advances ,")", self.currentOp.toString(), self.operand, self.nextOp.toString()
		self.advances += 1
	  #try:	
	  #	if self.bs.debugging():
	  #		msg = self.currentOp.toString() + " "
	  #		msg += self.operand.toString() + " "
	  #		msg += self.nextOp.toString() + " "
	  #		self.bs.showMessage(msg)
	  #except:
	  #	self.bs.showMessage("")
	
	def compileExpression(self):
		print "compiling expression"
		self.nextOp = self.exp.compileExpression()
		
	def fillAddress(self, referenceLoc, targetLoc):
		targetLoc = targetLoc - referenceLoc
		self.jvm.emitFFR(referenceLoc + 1, targetLoc)
		
	def saveForwardReference(self, symbol, address):
		fr = ForwardRef(symbol, address)
		print fr.reference.toString(), " SAVE FR:::"
		self.forwardReferences.append(fr)
		
   	def fillForwardReferences(self):
		while len(self.forwardReferences) != 0:
			ref = self.forwardReferences.pop()
			if self.bs._symbols.defined(ref.reference.toString()) == False:
				raise CompilerException("Function not defined, " + ref.reference.toString() + self.bs.fln())
			else:
				sym = self.bs._symbols.get(ref.reference.toString())
				self.fillAddress(ref.instrLocation, sym.getAddress())	
	#private
	def _compileCondition(self):
		self.compileExpression()
		relop = self.nextOp
		self.compileExpression()
		relstr = relop.toString()
		print "RELOP!!!1 :", relop
		print "RELSTRING!!!", relstr
		if relstr == "<":
			self.jvm.emit3byte(Opcode.IF_ICMPGE, 0)	#do you just emit the i_cmp opcode? (what about the offset)
		if relstr == ">":
			self.jvm.emit3byte(Opcode.IF_ICMPLE, 0)
		if relstr == "<=":
			self.jvm.emit3byte(Opcode.IF_ICMPGT, 0)		
		if relstr == ">=":
			self.jvm.emit3byte(Opcode.IF_ICMPLT, 0)
		if relstr == "==":
			self.jvm.emit3byte(Opcode.IF_ICMPNE, 0)
		if relstr == "!=":
			self.jvm.emit3byte(Opcode.IF_ICMPEQ, 0)
		

			
	def _generate(self, cOp, nOp):
		cOpTT = cOp.getTokenType()
		nOpTT = nOp.getTokenType()
		if  cOpTT >= TokenType.END_FILE or nOpTT >= TokenType.END_FILE:
			self._xx()
		else:
			self.AC.cono[cOpTT][nOpTT]()
	
	# code generators
	# ASsignment
	def _AS(self):
		print "AS()"
		print self.nextOp.toString(), "ASSIGNMENT&*&*&"
		if self.nextOp.getTokenType() == TokenType.L_BRACKET:
			sym = self.bs._symbols.get(self.operand.toString())
			if sym.getSymbolType() != SymbolType.ARRAY:
				raise CompilerException("Assignment Error, "+ sym.toString() +" is not an array. " + self.bs.fln())
			self.jvm.chooseOp(Opcode.ALOAD, Opcode.ALOAD_0, sym.getAddress())
			self.compileExpression()
			self.advance()
			self.compileExpression()
			self.jvm.emit1byte(Opcode.IASTORE)

		else:
			sym = self.bs._symbols.get(self.operand.toString())
			val = self.compileExpression()
			print self.currentOp.toString(), self.operand.toString(), self.nextOp.toString()
			self.jvm.chooseOp(Opcode.ISTORE, Opcode.ISTORE_0, sym.getAddress())

	
	# CAll function		
	def _CA(self):
		print "CA()"
		print "calling a function: ", self.currentOp.toString(), self.operand.toString(), self.nextOp.toString()
		if self.operand.toString() == "write":
			print "calling the write function"
			self.jvm.emit3byte(Opcode.GETSTATIC, 6)
			self.compileExpression()
			self.jvm.emit3byte(Opcode.INVOKEVIRTUAL, 7)
		else:
			if self.bs._symbols.defined(self.operand.toString()) == False:
				print "function not defined"
				sym = Symbol(self.operand.toString(), SymbolType.FORWARD_FUNCTION, self.scope)
				self.bs._symbols.insert(sym)
			
			sym = self.bs._symbols.get(self.operand.toString())
			if sym.getSymbolType() == SymbolType.FORWARD_FUNCTION:
				self.saveForwardReference(sym, self.jvm.getPC())
				self.jvm.emit3byte(Opcode.JSR, 0) #jsr
			elif sym.getSymbolType() == SymbolType.DEFINED_FUNCTION:
				self.jvm.emit3byte(Opcode.JSR, sym.getAddress() - self.jvm.getPC()) #jsr
			else:
				raise CompilerException("Error, call to "+sym.toString()+" does not reference a function, "+self.bs.fln())
		
	# COndition
	def _CO(self):
		print "CO()"
		if self.currentOp.toString() == "if":
			struc = Structure(StructureType.IF)
			self._compileCondition()
			struc.jumpLoc = self.jvm.getPC() - 3
			self.structureStack.append(struc)
			print "Pushed IF Structure"
		elif self.currentOp.toString() == "while":
			struc = Structure(StructureType.WHILE)
			struc.conditionLoc = self.jvm.getPC()
			self._compileCondition()
			struc.jumpLoc = self.jvm.getPC() - 3
			self.structureStack.append(struc)	
			print "Pushed WHILE structure"		
		
		pass #save position of conditional jump at end of the cond as jumpLoc (pc - 3)
	
	# DEclaration
	def _DE(self):
		print "DE()"
		#self.suppressAdvance = True
		print "declaring a variable...", self.currentOp.toString(), self.operand.toString(), self.nextOp.toString()
		if self.bs._symbols.defined(self.operand.toString()):
			self.setError("Error: Multiple Declaration")
			raise CompilerException("Multiple Declaration of variable "+ self.operand.toString() + self.bs.fln())
		#if self.nextOp.toString() == ";":
		#	print "default declaration"
		#	sym = Symbol(self.operand.toString(), SymbolType.VARIABLE, self.scope)
		#	sym.setAddress(self.nextLocation)
		#	self.nexLocation += 1
		#	self.pushConstantInt(0)
		#	self.jvm.chooseOp(Opcode.ISTORE, Opcode.ISTORE_0, sym.getAddress())
		#	self.advance()
		#	self.bs._symbols.insert(sym)
		#	return
		#	
		#while self.nextOp.toString() != ";":
		#	print self.operand.toString(), "SYMBOL!!!"
		#	self.advance()
		#	sym.setAddress(self.nextLocation)
		#	if self.nextOp.toString() == "[":
		#		sym.setSymbolType(SymbolType.ARRAY)
		#		self.advance() # co = '[', no = ']'
		#		self.pushConstant(self.operand)
		#		size = self.operand.toString()
		#		self.jvm.emit2byte(Opcode.NEWARRAY, 10)
		#		sym.setAddress(self.nextLocation)
		#		self.jvm.chooseOp(Opcode.ASTORE, Opcode.ASTORE_0, sym.getAddress())
		#		self.advance() # co = ']', no = ('=' | ';')
		#		if self.nextOp.toString() == "=":
		#			self.advance() # co = '=', no = '{'
		#			if self.nextOp.toString() != "{":
		#				self.setError("Syntax Error: Missing { after = ");
		#			
		#			self.advance() #co = '{', no = ','
		#			arr = []
		#			while self.nextOp.toString() != ";":
		#				print "Array Declaration :", self.operand.toString()
		#				arr.append(self.operand)
		#				self.advance() 
		#			if len(arr) > size:
		#				self.setError("Syntax Error: Array Subscript exceeded")
		#			else:
		#				i = 0
		#				for val in arr:
		#					self.jvm.chooseOp(Opcode.ALOAD, Opcode.ALOAD_0, sym.getAddress())
		#					self.pushConstantInt(i)
		#					self.pushConstant(val)
		#					self.jvm.emit1byte(Opcode.IASTORE)
		#					i += 1							
		#					
		#	else: #if not an array
		#		sym.setSymbolType(SymbolType.VARIABLE)
		#		#sym.setAddress(self.nextLocation)
		#		if self.nextOp.toString() == "=":
		#			self.advance()
		#			self.pushConstant(self.operand)
		#			self.jvm.chooseOp(Opcode.ISTORE, Opcode.ISTORE_0, sym.getAddress())
		#		
		#		print "declared a variable"
		#		
		#		#do variable declaration things
		#	self.bs._symbols.insert(sym)
		#	self.nextLocation += 1
		self.done = False
		while self.done is False:
			#if self.currentOp.toString() == "int":
			#	self.advance()
			if self.nextOp.toString() == ";":
				#declare an uninitialzed variable, then end
				sym = Symbol(self.operand.toString(), SymbolType.VARIABLE, self.scope)
				sym.setAddress(self.nextLocation)
				self.nextLocation += 1
				self.pushConstantInt(0)
				self.jvm.chooseOp(Opcode.ISTORE, Opcode.ISTORE_0, sym.getAddress())
				self.advance()
				self.bs._symbols.insert(sym)
				self.done = True

			elif self.nextOp.toString() == ",":
				#declare this uninitalized variable, then go on to the next one
				if self.currentOp.toString() == "," or self.currentOp.toString() == "int":
					sym = Symbol(self.operand.toString(), SymbolType.VARIABLE, self.scope)
					sym.setAddress(self.nextLocation)
					self.nextLocation += 1
					self.pushConstantInt(0)
					self.jvm.chooseOp(Opcode.ISTORE, Opcode.ISTORE_0, sym.getAddress())
					self.advance()
					self.bs._symbols.insert(sym)
				else:
					self.advance()

			elif self.nextOp.toString() == "[":
				#declare an array, check the nextOp, and continue or end depending
				sym = Symbol(self.operand.toString(), SymbolType.ARRAY, self.scope)
				self.advance() # co = '[', no = ']'
				print self.operand.toString(), "OPERAND"
				self.pushConstant(self.operand)
				size = self.operand.toString()
				print "ARRAY SIZE", size
				self.jvm.emit2byte(Opcode.NEWARRAY, 10)
				sym.setAddress(self.nextLocation)
				self.nextLocation += 1
				self.bs._symbols.insert(sym)
				self.jvm.chooseOp(Opcode.ASTORE, Opcode.ASTORE_0, sym.getAddress())
				self.advance() # co = ']', no = ('=' | ';' | ',')
				if self.nextOp.toString() == "=":
					self.advance() # co = '=', no = '{'
					if self.nextOp.toString() != "{":
						self.setError("Syntax Error: Missing { after = ");
					
					self.advance() #co = '{', no = ','
					
					arr = []
					while self.currentOp.toString() != "}":
						print "Array Declaration :", self.operand.toString()
						arr.append(self.operand)
						self.advance() 
					print self.nextOp.toString(), "NEXT OP ========="
					print "Attempted array declaration list size", len(arr)
					if len(arr) > size:
						self.setError("Syntax Error: Array Subscript exceeded")
 						raise CompilerException("Out-of-Bounds Error, Array subscript exceeded at symbol " + sym.toString() + self.bs.fln())

					else:
						i = 0
						for val in arr:
							print "assigning value", val, "to array"
							self.jvm.chooseOp(Opcode.ALOAD, Opcode.ALOAD_0, sym.getAddress())
							self.pushConstantInt(i)
							self.pushConstant(val)
							self.jvm.emit1byte(Opcode.IASTORE)
							i += 1
				if self.nextOp.toString() == ";":
					self.done = True
				
				print "AFTER DECLARATION, NEXTOP =", self.nextOp.toString()
				
			elif self.nextOp.toString() == "=":
				print "declare an initialized variable"
				sym = Symbol(self.operand.toString(), SymbolType.VARIABLE, self.scope)
				self.advance()
				print self.operand.toString()
				sym.setAddress(self.nextLocation)
				self.nextLocation += 1
				self.pushConstant(self.operand)
				self.bs._symbols.insert(sym)
				self.jvm.chooseOp(Opcode.ISTORE, Opcode.ISTORE_0, sym.getAddress())
				if self.nextOp.toString() == ";":
					self.done = True
				pass
			else:
				#error
				self.done = True
				raise CompilerException("Invalid Assignment Sequence" + self.bs.fln())
				pass

				
		print "OUT OF LOOPS"
		try:
			if self.scope == SymbolScope.GLOBAL and self.nextOp.toString() == "void":
				print "END OF A DECLARATION STATEMENT"
				sym = self.bs._symbols.get("Main")
				self.saveForwardReference(sym, self.jvm.getPC())
				self.jvm.emit3byte(Opcode.GOTO, 0)
		except:			
			pass
	    
	# Define Function
	def _DF(self):
		print "DF()"
		self.scope = SymbolScope.LOCAL
		if self.bs._symbols.defined(self.operand.toString()):
			sym = self.bs._symbols.get(self.operand.toString())
			sym.setSymbolType(SymbolType.DEFINED_FUNCTION)
		else:
			sym = Symbol(self.operand.toString(), SymbolType.DEFINED_FUNCTION, SymbolScope.GLOBAL)
			self.bs._symbols.insert(sym)
		sym.setAddress(self.jvm.getPC())
		
		if sym.toString() == "Main":
			print "Main Function Definition"
			struct = Structure(StructureType.MAIN)
		else:
			struct = Structure(StructureType.FUNCTION)
			print "Function Definition"
		self.structureStack.append(struct)
		print self.structureStack
		print len(self.structureStack), ": structure pushed, "
	
	# End Block
	def _EB(self):
		print "EB()"
		#print "END BLOCK: ", self.currentOp.toString(), self.operand.toString(), self.nextOp.toString()
		if len(self.structureStack) == 0:
			raise CompilerException("Error, Found right brace without matching left brace" + self.bs.fln())
		
		struct = self.structureStack.pop()
		if struct.isOfType(StructureType.ELSE):
			self.fillAddress(struct.jumpLoc, self.jvm.getPC()) #not done
		elif struct.isOfType(StructureType.IF):
			if self.bs.peekToken().toString() == "else":
				pstru = Structure(StructureType.ELSE)
				pstru.jumpLoc = self.jvm.getPC()
				self.structureStack.append(pstru)
				self.jvm.emit3byte(Opcode.GOTO, 0)
	    		#emit code to jump past false part
			self.jvm.emitFFR(struct.jumpLoc + 1, self.jvm.getPC() - struct.jumpLoc)
		elif struct.isOfType(StructureType.WHILE):
			self.jvm.emit3byte(Opcode.GOTO, struct.conditionLoc - self.jvm.getPC())
			self.fillAddress(struct.jumpLoc, self.jvm.getPC())
		elif struct.isOfType(StructureType.FUNCTION):
			self.scope = SymbolScope.GLOBAL
			self.bs._symbols.clearLocalTable()
			#generate code to save the return address in loc0 and emit instruction
			#return to the calling point
			self.jvm.emit1byte(Opcode.ASTORE_0)
			self.jvm.emit2byte(Opcode.RET, 0)
			if self.bs.peekToken().getTokenType() == TokenType.END_FILE:
				self.loopStatus = Status.EXIT
		elif struct.isOfType(StructureType.MAIN):
			self.scope = SymbolScope.GLOBAL
			self.bs._symbols.clearLocalTable()
			#emit the instruction to terminate the program
			#emit return
			self.jvm.emit1byte(Opcode.RETURN)
			print self.bs.peekToken().toString(), "PEEK TOKEN^@#*&^@#*^"
			if self.bs.peekToken().getTokenType() == TokenType.END_FILE:
				self.loopStatus = Status.EXIT
				
		del struct
		#self.jvm.emit1byte(Opcode.RETURN)
		#self.loopStatus = Status.EXIT
	
	# No Op
	def _NO(self):
		print "NO()"
		pass
	
	# Error
	def _xx(self):
		print "XX()"
		#self.setError("Invalid token sequence.")
		#raise CompilerException("Invalid token sequence.")
		pass
 def test_iff_replacement(self):
     with self.subTest():
         self.assertEqual(EP.standardize_string('a iff b'), 'a = b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('testiff'), 'testiff')
     with self.subTest():
         self.assertEqual(EP.standardize_string('ifftest'), 'ifftest')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a if and only if b'),
                          'a = b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a <-> b'), 'a = b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a <> b'), 'a = b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a == b'), 'a = b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('='), '=')
     with self.subTest():
         self.assertEqual(EP.standardize_string('testif and only if b'),
                          'testif * only > b')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a if and only iftest'),
                          'a > * only iftest')
     with self.subTest():
         self.assertEqual(EP.standardize_string('a === b'), 'a = b')
Beispiel #20
0
import sys
sys.path.append("../")

from ExpressionParser import *

exp = ExpressionParser()



exp.testExpression()
 def test_space_replacement(self):
     self.assertEqual(EP.standardize_string('a       b'), 'a b')