diff --git a/autotest/test_codec.py b/autotest/test_codec.py new file mode 100644 index 00000000..1a04959a --- /dev/null +++ b/autotest/test_codec.py @@ -0,0 +1,19 @@ +from pprint import pprint + +import pytest + +import modflow_devtools.models as models +from modflow_devtools.codec import make_parser + +MODELS = [name for name in models.get_models().keys() if name.startswith("mf6/")] +PARSER = make_parser() + + +@pytest.mark.parametrize("model_name", MODELS) +def test_parser(model_name, function_tmpdir): + workspace = models.copy_to(function_tmpdir, model_name) + nam_path = next(iter(workspace.glob("*.nam"))) + text = nam_path.open().read() + pprint(text) + tree = PARSER.parse(text) + print(tree.pretty()) diff --git a/docs/md/codec.md b/docs/md/codec.md new file mode 100644 index 00000000..e69de29b diff --git a/modflow_devtools/codec.py b/modflow_devtools/codec.py new file mode 100644 index 00000000..9506fcb3 --- /dev/null +++ b/modflow_devtools/codec.py @@ -0,0 +1,5 @@ +from lark import Lark + + +def make_parser(**kwargs) -> Lark: + return Lark.open("mf6.lark", parser="lalr", rel_to=__file__, **kwargs) diff --git a/modflow_devtools/mf6.lark b/modflow_devtools/mf6.lark new file mode 100644 index 00000000..cd64e2bb --- /dev/null +++ b/modflow_devtools/mf6.lark @@ -0,0 +1,19 @@ +start: [WS] [_NL*] (block [[WS] _NL*])+ [WS] +block: "begin"i CNAME [_block_index] _NL _content "end"i CNAME [_block_index] _NL+ +_block_index: INT +_content: line* [WS] +line: [WS] item* _NL+ +item: word | NUMBER +word: /[a-zA-Z0-9._'~,-\\(\\)]+/ + +%import common.NEWLINE -> _NL +%import common.WS +%import common.WS_INLINE +%import common.CNAME +%import common.WORD +%import common.NUMBER +%import common.INT +%import common.SH_COMMENT +%import common._STRING_INNER +%ignore WS_INLINE +%ignore SH_COMMENT \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index e8f637ae..b0c81a9f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -81,6 +81,9 @@ models = [ "tomli", "tomli-w" ] +codec = [ + "lark" +] dev = ["modflow-devtools[lint,test,docs,dfn,models]"] [dependency-groups] @@ -126,6 +129,9 @@ models = [ "tomli", "tomli-w" ] +codec = [ + "lark" +] dev = [ {include-group = "build"}, {include-group = "lint"}, @@ -133,6 +139,7 @@ dev = [ {include-group = "docs"}, {include-group = "dfn"}, {include-group = "models"}, + {include-group = "codec"}, ] [project.urls]