Commits

Martin Vejnár  committed 9df79d6

Finished the DocParser (no documentation yet).

  • Participants
  • Parent commits 48dc4c6

Comments (0)

Files changed (1)

File docparser.py

+"""
+>>> class Test:
+...     def p_root(self, minus, int_digits, float_digits):
+...         ''' float = ["-"], { "1" }, '.', { "1" }; '''
+...         return (minus, int_digits, float_digits)
+>>> p = DocParser(Test)
+>>> print p.parse('-111.11')
+('-', ['1', '1', '1'], ['1', '1'])
+>>> print p.parse('111.11')
+(None, ['1', '1', '1'], ['1', '1'])
+"""
+
 from ebnf_grammar import ebnf_parse
 from grammar import Grammar
 from lrparser import Parser
 
-class Test:
-    def p_root(self, minus, int_digits, float_digits):
-        """ float = ["-"], { "1" }, '.', { "1" }; """
-        return (minus, int_digits, float_digits)
-
 class DocParser:
-    def __init__(self, cls):
+    def __init__(self, cls, k=1):
         rules = []
+        root_rules = None
+        counter = 0
+        class_rules, counter = ebnf_parse(cls.__doc__, counter=counter) if cls.__doc__ else ([], 0)
+        
         for name in dir(cls):
             if name[:2] != 'p_':
                 continue
             action = getattr(cls, name)
             grammar = action.__doc__
-            print grammar
             if not grammar:
                 continue
-            rules.extend(ebnf_parse(grammar, action))
+            if name == 'p_root':
+                root_rules, counter = ebnf_parse(grammar, action, counter=counter)
+            else:
+                new_rules, counter = ebnf_parse(grammar, action, counter=counter)
+                rules.extend(new_rules)
+                
         self.cls = cls
-        self.grammar = Grammar(*rules)
-        self.parser = Parser(self.grammar)
+        root_rules.extend(rules)
+        root_rules.extend(class_rules)
+        self.grammar = Grammar(*root_rules)
+        self.parser = Parser(self.grammar, k)
         
     def parse(self, input, context=None):
         return self.parser.parse(input, context=context or self.cls())
 
 if __name__ == '__main__':
-    p = DocParser(Test)
-    print p.grammar
-    print p.parse('-111.11')
-    print p.parse('111.11')
+    import doctest
+    doctest.testmod()