Coverage for phml\nodes\AST.py: 100%

25 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2022-12-08 13:16 -0600

1# pylint: disable=invalid-name 

2"""Basic node that holds a root node and has basic utilties. 

3 

4You can check the size of the tree, iterate over the tree, and directly access 

5the children of the root node. 

6""" 

7 

8from __future__ import annotations 

9 

10from functools import cached_property 

11from typing import Iterator 

12 

13__all__ = ["AST"] 

14 

15 

16class AST: 

17 """PHML ast. 

18 

19 Contains utility functions that can manipulate the ast. 

20 """ 

21 

22 def __init__(self, tree): 

23 if tree is not None and hasattr(tree, "type") and tree.type in ["root", "element"]: 

24 self.tree = tree 

25 else: 

26 raise TypeError("The given tree/root node for AST must be of type `Root` or `Element`") 

27 

28 def __iter__(self) -> Iterator: 

29 from phml import walk # pylint: disable=import-outside-toplevel 

30 

31 return walk(self.tree) 

32 

33 def __eq__(self, obj) -> bool: 

34 if isinstance(obj, self.__class__): 

35 if self.tree == obj.tree: 

36 return True 

37 return False 

38 

39 @cached_property 

40 def size(self) -> int: 

41 """Get the number of nodes in the ast tree.""" 

42 from phml import size # pylint: disable=import-outside-toplevel 

43 

44 return size(self.tree) 

45 

46 @property 

47 def children(self) -> list: 

48 """Get access to the ast roots children. 

49 Is none if there is no root. 

50 """ 

51 return self.tree.children if self.tree is not None else None