Coverage for src/renaissance/syntax_tree/ast_factory.py: 100%
16 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-16 16:04 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-16 16:04 +0000
1# Copyright (C) 2024-2026 TNO
2#
3# Licensed under the terms specified in the LICENSE file in the root directory
4# of this repository, also available at:
5# https://github.com/TNO/Renaissance.Py/blob/main/LICENSE
7"""AI: Factory for creating instances of ASTNode."""
9from collections.abc import Sequence
10from pathlib import Path
12from renaissance.syntax_tree.ast_node import ASTNode
15class ASTFactory:
16 """A factory class for creating instances of ASTNode.
18 Attributes:
19 clazz (type[ASTNode]): The class type of the AST nodes to be created.
20 extra_args (Optional[Sequence[str]]): Additional arguments to be passed during the creation of AST nodes.
21 #TODO working_dir
23 """
25 def __init__(
26 self,
27 clazz: type[ASTNode],
28 extra_args: Sequence[str] | None = None,
29 working_dir: Path | None = None,
30 ) -> None:
31 """AI: Configure a factory that creates AST nodes of the given node-implementation type."""
32 # TODO(FrancescoPezzella): Make ASTFactory generic over the node class (clazz: type[NodeT], returning NodeT) so callers get the
33 # concrete node type instead of ASTNode[Unknown, Unknown]. The bound must also accept PythonRstNode, which is not an ASTNode.
34 # https://github.com/TNO/Renaissance.Py/issues/149
35 self.clazz = clazz
36 self.extra_args: Sequence[str] = extra_args if isinstance(extra_args, Sequence) else []
37 # TODO: Why not
38 # self.extra_args: Sequence[str] = [] if extra_args is None else extra_args or
39 # self.extra_args: Sequence[str] = extra_args if extra_args else [] ?
40 # As the logic is about providing a value when none is provided.
41 # In other words, the type of the optional argument is not relevant for the logic.
42 self.working_dir = working_dir or Path.cwd()
44 def create(self, file_path: Path) -> ASTNode:
45 """AI: Parse the source file at file_path into an ASTNode using the configured node type."""
46 atu = self.clazz.load(
47 file_path=file_path,
48 extra_args=self.extra_args,
49 working_dir=self.working_dir,
50 )
51 assert isinstance(atu, self.clazz), "The loaded AST node is not an instance of the expected type"
52 return atu
54 def create_from_text(self, text: str, file_name: str) -> ASTNode:
55 """AI: Parse source text (attributed to file_name) into an ASTNode using the configured node type."""
56 atu = self.clazz.load_from_text(text, file_name, extra_args=self.extra_args, working_dir=self.working_dir)
57 assert isinstance(atu, self.clazz), "The loaded AST node is not an instance of the expected type"
58 return atu