class Statement(object): def __init__(self, tokens): self.t = TokenHandler(tokens) def createStatement(self, tokens): currenttoken = self.t.getCurrentToken() if currenttoken == "begin": s = CompoundStatement(tokens) return s elif self.t.isVariable(currenttoken): a = Assignment(tokens) return a elif currenttoken == "print": p = Print(tokens) return p elif currenttoken == "if": i = IF(tokens) return i elif currenttoken == "while": w = While(tokens) return w else: raise ParserException('\';\' expected. Got \'' + currenttoken + '\' instead.') def execute(self, skip): raise NotImplementedError("Subclass must implement abstract method")
class Assignment(Statement): def __init__(self, tokens): self.t = TokenHandler(tokens) def execute(self, skip): currenttoken = self.t.getCurrentToken() if not self.t.isVariable(currenttoken): raise VariableException("Not a variable: " + currenttoken) variablebeingassigned = currenttoken self.t.match(currenttoken, self.t.tokens) self.t.match(":=", self.t.tokens) currenttoken = self.t.getCurrentToken() variablevalue = None if not skip: variablevalue = self.t.readTokenValue(currenttoken) TokenHandler.variables[variablebeingassigned] = variablevalue self.t.match(currenttoken, self.t.tokens) currenttoken = self.t.getCurrentToken() while(self.t.isMathOperator(currenttoken)): if currenttoken == "+": self.t.match("+", self.t.tokens) currenttoken = self.t.getCurrentToken() if not skip: operand = self.t.readTokenValue(currenttoken) variablevalue += operand TokenHandler.variables[variablebeingassigned] = variablevalue self.t.match(currenttoken, self.t.tokens) elif currenttoken == "-": self.t.match("-", self.t.tokens) currenttoken = self.t.getCurrentToken() if not skip: operand = self.t.readTokenValue(currenttoken) variablevalue -= operand TokenHandler.variables[variablebeingassigned] = variablevalue self.t.match(currenttoken, self.t.tokens) elif currenttoken == "*": self.t.match("*", self.t.tokens) currenttoken = self.t.getCurrentToken() if not skip: operand = self.t.readTokenValue(currenttoken) variablevalue *= operand TokenHandler.variables[variablebeingassigned] = variablevalue self.t.match(currenttoken, self.t.tokens) elif currenttoken == "/": self.t.match("/", self.t.tokens) currenttoken = self.t.getCurrentToken() if not skip: operand = self.t.readTokenValue(currenttoken) if operand == 0: raise ParserException("Can't divide by zero.") variablevalue /= operand TokenHandler.variables[variablebeingassigned] = variablevalue self.t.match(currenttoken, self.t.tokens) currenttoken = self.t.getCurrentToken() return self.t.resetTokens()