Skip to content

Commit

Permalink
Merge pull request #27 from gerlero/dictionary
Browse files Browse the repository at this point in the history
Update parsing
  • Loading branch information
gerlero authored Mar 22, 2024
2 parents 7a19634 + 5d13247 commit 45b4e21
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 20 deletions.
26 changes: 6 additions & 20 deletions foamlib/_dictionaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,8 @@
Keyword,
Literal,
Opt,
QuotedString,
Word,
ParseException,
common,
identchars,
identbodychars,
)

FoamDimensionSet = namedtuple(
Expand Down Expand Up @@ -77,10 +74,6 @@ def __post_init__(self) -> None:

_YES = Keyword("yes").set_parse_action(lambda s, loc, tks: True)
_NO = Keyword("no").set_parse_action(lambda s, loc, tks: False)
_WORDS = Word(identchars, identbodychars + "(),")[1, ...].set_parse_action(
lambda s, loc, tks: " ".join(tks)
)
_STRING = QuotedString('"', unquote_results=False)
_VALUE = Forward()
_LIST = Opt(
Literal("List") + Literal("<") + common.identifier + Literal(">")
Expand All @@ -105,21 +98,14 @@ def __post_init__(self) -> None:
lambda s, loc, tks: FoamDimensioned(tks[0], tks[1], tks[2].as_list())
)

_VALUE << (
_FIELD
| _LIST
| _DIMENSIONED
| _DIMENSIONS
| common.number
| _YES
| _NO
| _WORDS
| _STRING
)
_VALUE << (_FIELD | _LIST | _DIMENSIONED | _DIMENSIONS | common.number | _YES | _NO)


def _parse(value: str) -> FoamValue:
return cast(FoamValue, _VALUE.parse_string(value, parse_all=True).as_list()[0])
try:
return cast(FoamValue, _VALUE.parse_string(value, parse_all=True).as_list()[0])
except ParseException:
return value


def _serialize_bool(value: Any) -> str:
Expand Down
4 changes: 4 additions & 0 deletions tests/test_dictionaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ def test_parse() -> None:
assert _parse("g [1 1 -2 0 0 0 0] (0 0 -9.81)") == FoamDimensioned(
"g", FoamDimensionSet(mass=1, length=1, time=-2), [0, 0, -9.81]
)
assert (
_parse("hex (0 1 2 3 4 5 6 7) (1 1 1) simpleGrading (1 1 1)")
== "hex (0 1 2 3 4 5 6 7) (1 1 1) simpleGrading (1 1 1)"
)


def test_write_read(tmp_path: Path) -> None:
Expand Down

0 comments on commit 45b4e21

Please sign in to comment.