minor changes to parsing process, and map file content to structure.

- Move magic marker for unparsed sections to a constant to matcha
  against.
- Add functions to flatten a heckelement tree into a python structure
This commit is contained in:
Cassowary 2024-02-10 20:59:25 -08:00
parent 9b2f9b706c
commit 277fddc699
2 changed files with 44 additions and 1 deletions

7
TODO Normal file
View File

@ -0,0 +1,7 @@
Python:
- More options for accessing a heck tree.
- automated testing
Guile, C (or D), and Haxe:
- Initial implementation

View File

@ -9,6 +9,8 @@ from .exceptions import HeckParseException
HeckValue = TypeVar("HeckElement") | str | int | float
UNPARSED_MARKER = "%%% UNPARSED %%% "
class HeckElement:
"""
Container for a tree of HECKformat elements.
@ -30,11 +32,14 @@ class HeckElement:
self.unparsed = False
def flatten(self) -> Mapping:
"""
Convert a hecktree element into a dictionary.
"""
output = {}
for elm in self.children:
elmval = []
if elm.unparsed:
nam = '%%%UNPARSED%%% '+elm.name
nam = UNPARSED_MARKER+elm.name
val = '\n'.join(elm.values)
if nam in output:
output[nam] = '\n'.join([output[nam], val])
@ -50,6 +55,37 @@ class HeckElement:
output[elm.name] = elmval
return output
def get_flat_value(self) -> Union[List, HeckValue]:
if not len(self.values):
return None
if len(self.values) > 1:
return list(self.values)
return self.values[0]
def flatten_replace(self) -> Mapping:
"""
Convert a hecktree element into a dictionary (but don't try to merge values, just pretend each key is unique)
"""
output = {}
for elm in self.children:
if elm.unparsed:
nam = UNPARSED_MARKER+elm.name
val = '\n'.join(elm.values)
output[nam] = val
else:
elmval = None
if len(elm.children):
elmval = {}
elmval['children'] = elm.flatten_replace()
elmval['value'] = elm.get_flat_value()
else:
elmval = elm.get_flat_value()
output[elm.name] = elmval
return output
def __str__(self):
k=''
if self.unparsed: