| 1 | from __future__ import annotations |
| 2 | |
| 3 | import pathlib |
| 4 | import typing as ty |
| 5 | from dataclasses import dataclass |
| 6 | |
| 7 | from pint_parser import common, context, defaults, group, plain, system |
| 8 | |
| 9 | from flexparser import flexparser as fp |
| 10 | |
| 11 | |
| 12 | @dataclass(frozen=True) |
| 13 | class ImportDefinition(fp.IncludeStatement): |
| 14 | value: str |
| 15 | |
| 16 | @property |
| 17 | def target(self): |
| 18 | return self.value |
| 19 | |
| 20 | @classmethod |
| 21 | def from_string(cls, s: str) -> fp.NullableParsedResult[ImportDefinition]: |
| 22 | if s.startswith("@import"): |
| 23 | return ImportDefinition(s[len("@import") :].strip()) |
| 24 | return None |
| 25 | |
| 26 | |
| 27 | @dataclass(frozen=True) |
| 28 | class EntryBlock( |
| 29 | fp.RootBlock[ |
| 30 | ty.Union[ |
| 31 | common.Comment, |
| 32 | ImportDefinition, |
| 33 | defaults.DefaultsDefinition, |
| 34 | context.ContextDefinition, |
| 35 | group.GroupDefinition, |
| 36 | system.SystemDefinition, |
| 37 | plain.DimensionDefinition, |
| 38 | plain.PrefixDefinition, |
| 39 | plain.UnitDefinition, |
| 40 | ] |
| 41 | ] |
| 42 | ): |
| 43 | pass |
| 44 | |
| 45 | |
| 46 | cfg = common.Config() |
| 47 | p = pathlib.Path("files/default_en.txt") |
| 48 | |
| 49 | parsed = fp.parse( |
| 50 | p, |
| 51 | EntryBlock, |
| 52 | cfg, |
| 53 | delimiters={ |
| 54 | "#": ( |
| 55 | fp.DelimiterInclude.SPLIT_BEFORE, |
| 56 | fp.DelimiterAction.CAPTURE_NEXT_TIL_EOL, |
| 57 | ), |
| 58 | **fp.SPLIT_EOL, |
| 59 | }, |
| 60 | ) |
| 61 | |
| 62 | |
| 63 | def pprint(objs, indent=1): |
| 64 | TT = " " |
| 65 | print(TT * (indent - 1), objs.opening) |
| 66 | for p in objs.body: |
| 67 | if isinstance(p, fp.Block): |
| 68 | pprint(p, indent + 1) |
| 69 | else: |
| 70 | print(TT * indent, p) |
| 71 | print(TT * (indent - 1), objs.closing) |
| 72 | |
| 73 | |
| 74 | print("Keys") |
| 75 | print("----") |
| 76 | for k in parsed.keys(): |
| 77 | print(k) |
| 78 | |
| 79 | print("\n\n----\n\n") |
| 80 | for x in parsed.iter_blocks(): |
| 81 | print(x) |
| 82 | |
| 83 | print("\n") |
| 84 | print("Errors") |
| 85 | print("------") |
| 86 | for p in parsed.errors(): |
| 87 | print(p) |