def test_and(self): actions = [] def and_action(parser, tokens): actions.append(tokens) return tokens hede = Word() + Word() hede.set_action(and_action) hede.parse_string({}, 'a b') self.assertEquals(actions, [['a', 'b']])
def test_infix(self): actions = [] def infix_action(parser, tokens): actions.append(tokens) return tokens var = Word() def var_action(parser, tokens): actions.extend(tokens) return tokens[0] var.set_action(var_action) hede = Infix(var, Literal("+")) hede.set_action(infix_action) hede.parse_string({}, 'a + b') self.assertEquals(actions, ['a', 'b', ['a', '+', 'b']])
def test_optional_and(self): varname = Word() actions = [] def varname_action(parser, tokens): actions.append(tokens) return tokens varname.set_action(varname_action) trailer = varname + Optional(Word()) def trailer_action(parser, tokens): actions.append(tokens) return tokens trailer.set_action(trailer_action) print trailer.parse_string({}, "var") self.assertEquals(actions, [['var'], ['var', None]]) actions = [] print trailer.parse_string({}, "var var2") print "sadasd" + str(actions)
context = self.contexts[-1] if len(self.contexts) > 1 and varname not in context: context[varname] = len(context) def get_var(self, varname): context = self.contexts[-1] if varname not in context: return -1 return context[varname] def __str__(self): return self.__repr__() word = Word() varname = Word() string = quotedString.copy() def varname_action(parser, tokens): var_index = parser.get_var(tokens[0]) if var_index != -1: parser.add_instruction("pushlocal %s" % var_index) else: index = parser.add_atom("str", tokens[0]) parser.add_instruction("pushglobal %s" % index) return tokens varname.set_action(varname_action) def string_action(parser, tokens):