Coverage for src/renaissance/syntax_tree/ast_factory.py: 94%

18 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-02 13:12 +0000

1"""AI: Factory for creating instances of ASTNode.""" 

2 

3from collections.abc import Sequence 

4from pathlib import Path 

5 

6from .ast_node import ASTNode 

7 

8 

9class ASTFactory: 

10 """A factory class for creating instances of ASTNode. 

11 

12 Attributes: 

13 clazz (type[ASTNode]): The class type of the AST nodes to be created. 

14 extra_args (Optional[Sequence[str]]): Additional arguments to be passed during the creation of AST nodes. 

15 #TODO working_dir 

16 

17 """ 

18 

19 def __init__( 

20 self, 

21 clazz: type[ASTNode], 

22 extra_args: Sequence[str] | None = None, 

23 working_dir: Path | None = None, 

24 ) -> None: 

25 """AI: Configure a factory that creates AST nodes of the given node-implementation type.""" 

26 self.clazz = clazz 

27 self.extra_args: Sequence[str] = extra_args if isinstance(extra_args, Sequence) else [] 

28 # TODO: Why not 

29 # self.extra_args: Sequence[str] = [] if extra_args is None else extra_args or 

30 # self.extra_args: Sequence[str] = extra_args if extra_args else [] ? 

31 # As the logic is about providing a value when none is provided. 

32 # In other words, the type of the optional argument is not relevant for the logic. 

33 self.working_dir = working_dir or Path.cwd() 

34 

35 def create(self, file_path: Path) -> ASTNode: 

36 """AI: Parse the source file at file_path into an ASTNode using the configured node type.""" 

37 atu = self.clazz.load( 

38 file_path=file_path, 

39 extra_args=self.extra_args, 

40 working_dir=self.working_dir, 

41 ) 

42 assert isinstance(atu, self.clazz), "The loaded AST node is not an instance of the expected type" 

43 return atu 

44 

45 def create_from_text(self, text: str, file_name: str) -> ASTNode: 

46 """AI: Parse source text (attributed to file_name) into an ASTNode using the configured node type.""" 

47 atu = self.clazz.load_from_text(text, file_name, extra_args=self.extra_args, working_dir=self.working_dir) 

48 assert isinstance(atu, self.clazz), "The loaded AST node is not an instance of the expected type" 

49 return atu 

50 

51 

52if __name__ == "__main__": 

53 pass