Coverage for phml\core\parser\json.py: 82%
34 statements
« prev ^ index » next coverage.py v6.5.0, created at 2022-11-30 09:38 -0600
« prev ^ index » next coverage.py v6.5.0, created at 2022-11-30 09:38 -0600
1from phml.nodes import Comment, DocType, Element, Point, Position, Root, Text
4def json_to_ast(json_obj: dict):
5 """Convert a json object to a string."""
7 def construct_node_type(t: str):
8 if t == "root":
9 return Root()
10 elif t == "element":
11 return Element()
12 elif t == "doctype":
13 return DocType()
14 elif t == "text":
15 return Text()
16 elif t == "comment":
17 return Comment()
18 else:
19 return None
21 def recurse(obj: dict):
22 """Recursivly construct ast from json."""
23 if 'type' in obj:
24 val = construct_node_type(obj['type'])
25 if val is not None:
26 for key in obj:
27 if key not in ["children", "type", "position"] and hasattr(val, key):
28 setattr(val, key, obj[key])
29 if 'children' in obj and hasattr(val, "children"):
30 for child in obj["children"]:
31 new_child = recurse(child)
32 new_child.parent = val
33 val.children.append(new_child)
34 if 'position' in obj and hasattr(val, 'position') and obj["position"] is not None:
35 # start, end, indent
36 # line, column, offset
37 start = obj["position"]["start"]
38 end = obj["position"]["end"]
39 val.position = Position(
40 Point(start["line"], start["col"], start["offset"]),
41 Point(end["line"], end["col"], end["offset"]),
42 obj["position"]["indent"],
43 )
44 return val
45 else:
46 raise Exception(f"Unkown node type <{obj['type']}>")
47 else:
48 raise Exception(
49 'Invalid json for phml. Every node must have a type. Nodes may only have the types; root, element, doctype, text, or comment'
50 )
52 return recurse(json_obj)