|
| 1 | +from os import PathLike |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import jinja2 |
| 5 | +from modflow_devtools.dfn import Dfn |
| 6 | + |
| 7 | +from .filters import get_block_variables, get_blocks, get_variables, is_recarray_block |
| 8 | + |
| 9 | + |
| 10 | +def _get_template_env(): |
| 11 | + loader = jinja2.FileSystemLoader(Path(__file__).parent / "templates") |
| 12 | + env = jinja2.Environment( |
| 13 | + loader=loader, |
| 14 | + trim_blocks=True, |
| 15 | + lstrip_blocks=True, |
| 16 | + keep_trailing_newline=True, |
| 17 | + ) |
| 18 | + env.filters["is_recarray_block"] = is_recarray_block |
| 19 | + env.filters["get_block_variables"] = get_block_variables |
| 20 | + return env |
| 21 | + |
| 22 | + |
| 23 | +_TEMPLATE_ENV = _get_template_env() |
| 24 | + |
| 25 | + |
| 26 | +def make_grammar(dfn: Dfn, outdir: PathLike): |
| 27 | + """Generate a Lark grammar file for a single component.""" |
| 28 | + outdir = Path(outdir).expanduser().resolve().absolute() |
| 29 | + template = _TEMPLATE_ENV.get_template("component.lark.j2") |
| 30 | + blocks = get_blocks(dfn) |
| 31 | + variables = get_variables(dfn) |
| 32 | + target_path = outdir / f"{dfn['name'].replace('-', '')}.lark" |
| 33 | + with open(target_path, "w") as f: |
| 34 | + f.write(template.render(component=dfn["name"], blocks=blocks, variables=variables)) |
| 35 | + |
| 36 | + |
| 37 | +def make_all_grammars(dfns: dict[str, Dfn], outdir: PathLike): |
| 38 | + """Generate grammars for all components.""" |
| 39 | + outdir = Path(outdir).expanduser().resolve().absolute() |
| 40 | + outdir.mkdir(parents=True, exist_ok=True) |
| 41 | + for dfn in dfns.values(): |
| 42 | + make_grammar(dfn, outdir) |
0 commit comments