X-Git-Url: https://git.phdru.name/?a=blobdiff_plain;f=parser%2Fparser.py;h=3f51d3f9c7b6ee84c597de07a81c354d1d1ee674;hb=refs%2Fheads%2Fparsley;hp=dc562dd5043783f632499d180d283591ccf46ccf;hpb=553446ee8da7062c60915a2078d1c7311e85d612;p=phdru.name%2Fcgi-bin%2Fblog-ru%2Fsearch-tags.git diff --git a/parser/parser.py b/parser/parser.py old mode 100644 new mode 100755 index dc562dd..3f51d3f --- a/parser/parser.py +++ b/parser/parser.py @@ -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)')