]> git.phdru.name Git - phdru.name/cgi-bin/blog-ru/search-tags.git/blobdiff - parser/parser.py
Version 0.6: Use parsley instead of parsimonious
[phdru.name/cgi-bin/blog-ru/search-tags.git] / parser / parser.py
old mode 100644 (file)
new mode 100755 (executable)
index dc562dd..3f51d3f
@@ -1,5 +1,7 @@
+#! /usr/bin/env python
+
 import os
-from parsimonious import Grammar, NodeVisitor
+from parsley import makeGrammar
 
 
 # cache
@@ -11,44 +13,21 @@ def load_grammar():
     parser_dir = os.path.dirname(__file__)
     with open(os.path.join(parser_dir, 'grammar.ebnf'), 'rt') as grammar_file:
         grammar_text = grammar_file.read()
-    _grammar = Grammar(grammar_text)
+    _grammar = makeGrammar(grammar_text, {}, 'Tags')
 
 
 def parse(input):
     if _grammar is None:
         load_grammar()
-    return _grammar.parse(input)
-
-
-def cleanup_children(visited_children):
-    children = [c for c in visited_children if c]
-    if len(children) == 1:
-        return children[0]
-    else:
-        return children
-
-
-class Compiler(NodeVisitor):
-    def generic_visit(self, node, visited_children):
-        return cleanup_children(visited_children)
-
-    def visit_or_expression(self, node, visited_children):
-        return ('OR', visited_children[0], visited_children[2])
-
-    def visit_and_expression(self, node, visited_children):
-        return ('AND', visited_children[0], visited_children[2])
-
-    def visit_not_expression(self, node, visited_children):
-        return ('NOT', visited_children[2])
-
-    def visit_parens_expression(self, node, visited_children):
-        return ('PARENS', visited_children[2])
-
-    def visit_name(self, node, visited_children):
-        return ('NAME', node.text)
-
-
-def compile(tree):
-    if isinstance(tree, str):
-        tree = parse(tree)
-    return Compiler().visit(tree)
+    return _grammar(input).expression()
+
+
+if __name__ == '__main__':
+    print parse('test')
+    print parse('!test')
+    print parse('not test')
+    print parse('foo or bar')
+    print parse('foo && bar')
+    print parse('(test)')
+    print parse('(foo || bar)')
+    print parse('(foo and !bar)')