Commits

Ronny Pfannschmidt committed d2ab98b

add some example, beginnings of the parser

  • Participants
  • Parent commits 8fc2283

Comments (0)

Files changed (6)

 README.html
+targetrunner-c

examples/fib.when

+1 again (1) defer (3 || N(1)<=N(2) || N(7)>99) 2#N(1),3,7;
+2 again (2) defer (3 || N(2)<=N(1) || N(7)>99) 1#N(2),3,7;
+3 defer (5) print(N(1)+N(2));
+4 defer (5) print("1");
+5 4,-3,7;
+6 defer (4) 3;
+7 7;
+8 defer (N(7)<100) -1#N(1),-2#N(2),-7#100,-3;
+9 defer (3 || 6) 1,3;
+
+from whenever import parse, Runner
+
+def target(*args):
+    return main, None
+
+def main(args):
+    if len(args) < 2:
+        print 'missing arg'
+        return 1
+
+    cmd = args[1]
+    try:
+        statements = parse(cmd)
+    except OSError, e:
+        print 'cant parse:', cmd, 'os error', e.errno
+        return 1
+    runner = Runner(statements)
+    runner.run()
+
+    return 0
+
+
+if __name__ == '__main__':
+    import sys
+    main(sys.argv)
+

testing/__init__.py

Empty file added.

testing/test_parse_examples.py

+import py
+from whenever import parse
+
+def test_parse_example():
+    file = py.path.local(__file__).join('../../examples/fib.when')
+    parse(str(file))

whenever/__init__.py

+from pypy.rlib.streamio import open_file_as_stream
+
+from pypy.rlib.parsing.ebnfparse import parse_ebnf, make_parse_function
+
+
+
+def parse(filename):
+    result = {}
+
+    fp = open_file_as_stream(filename)
+    while True:
+        line = fp.readline()
+        number, commands = parseline(line)
+        assert number not in result
+        result[number] = commands
+
+
+
+def parseline(line):
+    number_str, commands = line.split(' ', 1)
+    print commands
+    try:
+        return int(number_str), parse_command(commands[:-1])
+    except Exception, e:
+        print e.args[0], e.nice_error_message()
+        print commands
+        raise
+
+regexs, rules, ToAST = parse_ebnf(
+"""
+IGNORE: " ";
+DECIMAL: "0|[1-9][0-9]*";
+
+command:  op ";";
+op: action+ statements | statements | action+;
+
+
+number: DECIMAL;
+math: number;
+
+compare: ">" | ">=" | "<" | "<=";
+bool: math "||" math | math compare math;
+function: "N" "(" expr ")";
+expr: bool | math | function;
+
+statement: expr "#" expr | expr;
+statements: (statement ",")* statement;
+
+action_name: "print" | "defer" | "again" | "forget";
+action: action_name "(" expr ")";
+
+""")
+
+parse_command = make_parse_function(regexs, rules)
+
+
+class Command(object):
+    def __init__(self, tree):
+        self.tree = tree
+
+
+class Runner(object):
+    def __init__(self, statements):
+        self.statements = statements
+    def run(self):
+        pass