From c2285922c63384d1f0b840dc23e3a077bed5d6a0 Mon Sep 17 00:00:00 2001 From: Zbigniew Jędrzejewski-Szmek Date: Aug 12 2018 14:02:02 +0000 Subject: First attempt --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c894537 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/.pytest_cache/ +*~ +*.py[co] diff --git a/rustcfg/__init__.py b/rustcfg/__init__.py new file mode 100644 index 0000000..dbdcd74 --- /dev/null +++ b/rustcfg/__init__.py @@ -0,0 +1,23 @@ +import string +import pyparsing as pp +from functools import lru_cache + +def paren_exp(keyword, contents): + return pp.Keyword(keyword)('op') + pp.Suppress('(') + contents('args') + pp.Suppress(')') + +@lru_cache() +def cfg_grammar(): + word = pp.Word(pp.alphanums + '_-') + exp = pp.Forward() + + any_exp = paren_exp('any', pp.Group(pp.delimitedList(exp, delim=','))) + all_exp = paren_exp('all', pp.Group(pp.delimitedList(exp, delim=','))) + not_exp = paren_exp('not', exp) + + exp << (any_exp | all_exp | not_exp | word) + exp.setName('expression') + + cfg_exp = paren_exp('cfg', exp) + + grammar = cfg_exp + pp.stringEnd() + return grammar diff --git a/rustcfg/test/__init__.py b/rustcfg/test/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/rustcfg/test/__init__.py diff --git a/rustcfg/test/test_expressions.py b/rustcfg/test/test_expressions.py new file mode 100644 index 0000000..06800ed --- /dev/null +++ b/rustcfg/test/test_expressions.py @@ -0,0 +1,37 @@ +import pytest +import rustcfg + +""" +"cfg(ok)", "cfg( ok )".parse::().unwrap().to_string()); +"foo-bar-baz", "foo-bar-baz".parse::().unwrap().to_string()); +"foo-bar-baz-quz", " foo-bar-baz-quz ".parse::().unwrap().to_string()); +"cfg(foo)", &Cfg::Is("foo".to_string()).to_string()); +"cfg(not(foo))", &Cfg::Not(Box::new(Cfg::Is("foo".to_string()))).to_string()); +"cfg(not(any(foo, bar))) +""" + +testdata = [ + ('cfg(ok)', True), + ('cfg( ok )', True), + ('cfg(foo-bar-bar)', True), + (' foo-bar-bar ', False), + (' cfg(not(foo))', True), + (' cfg(not(foo foo))', False), + ('cfg(any(asdf, asdf))', True), + ('cfg(all(asdf, asdf))', True), + ('cfg(any())', False), + ('cfg(all())', False), + ('cfg(all(not(asdf)))', True), + ('cfg(all(not(any(all(asdf)))))', True), +] + +@pytest.mark.parametrize("expression,ok", testdata) +def test_parsing(expression, ok): + g = rustcfg.cfg_grammar() + try: + t = g.parseString(expression) + except Exception: + good = False + else: + good = True + assert good == ok