diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6286100 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,29 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +## 0.4.3 + +### Changed + +- Added `__all__` to the `lionweb.language`, `lionweb.model`, `lionweb.model.impl`, + `lionweb.self`, `lionweb.presentation`, `lionweb.utils`, `lionweb.serialization` + and `lionweb.generation` packages to explicitly control their public API. +- Replaced generic `RuntimeError`/`ValueError` usages with more specific exception + types where it improves clarity and lets callers handle failures precisely: + - `lionweb.serialization.classifier_resolver.UnresolvedClassifierError` is now + raised by `ClassifierResolver` when a classifier, concept, or annotation + cannot be resolved from a `MetaPointer`. + - `lionweb.utils.language_validator.InvalidLanguageError` is now raised by + `LanguageValidator.ensure_is_valid` when a `Language` fails validation, + carrying the offending language and its `ValidationResult`. +- Rewrote the `isinstance`-chain in `LanguageValidator.check_ancestors_helper` + using `match`/`case` pattern matching for clarity. +- Added Google-style docstrings (with typed `Args`/`Returns`/`Raises` sections) + to `ClassifierResolver` and `LanguageValidator`. +- Tightened type hints (e.g. `Sequence[object]`, forward-referenced `Concept`/ + `Annotation` dictionaries) in `ClassifierResolver` and `LanguageValidator`. + +### Removed + +- Removed `ROADMAP.md`; the items it tracked have been addressed. diff --git a/ROADMAP.md b/ROADMAP.md deleted file mode 100644 index f0f1c63..0000000 --- a/ROADMAP.md +++ /dev/null @@ -1,11 +0,0 @@ -## Make the code more idiomatic - -* Use more specific types from typing module (e.g., Dict, Set, Tuple) where appropriate -* Use TypeVar and Generic for better generic type support -* Implement proper __all__ lists in __init__.py files to control what gets exported -* Consider using Python 3.10+ features like pattern matching where appropriate -* Use @dataclass decorators for classes that primarily hold data -* Implement more specific exception types rather than using generic exceptions -* Add more comprehensive docstrings following Google or NumPy style -* Implement proper type hints in docstrings -* Use f-strings for string formatting diff --git a/pyproject.toml b/pyproject.toml index d3995da..43e500a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,6 +37,8 @@ dev = [ "diff-cover", "testcontainers>=4.0", "types-requests", + "types-protobuf", + "types-click", ] [tool.ruff] diff --git a/requirements.txt b/requirements.txt index b1c2bc4..5ebd9b2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,99 +1,10 @@ annotated-types==0.7.0 -anyio==4.9.0 -astor==0.8.1 -asttokens==3.0.0 -backports.tarfile==1.2.0 -black==25.1.0 -build==1.2.2.post1 -bump2version==1.0.1 -certifi==2025.1.31 -cfgv==3.4.0 -charset-normalizer==3.4.1 -click==8.1.8 -coverage==7.10.6 -decorator==5.2.1 -distlib==0.3.9 -distro==1.9.0 -docker==7.1.0 -docutils==0.21.2 -exceptiongroup==1.2.2 -executing==2.2.0 -faiss-cpu==1.10.0 -filelock==3.17.0 -h11==0.14.0 -hatch==1.14.0 -hatchling==1.27.0 -httpcore==1.0.7 -httpx==0.28.1 -hyperlink==21.0.0 -id==1.5.0 -identify==2.6.7 -idna==3.10 -importlib_metadata==8.6.1 -iniconfig==2.0.0 -ipython==8.18.1 -isort==6.0.0 -jaraco.classes==3.4.0 -jaraco.context==6.0.1 -jaraco.functools==4.1.0 -jedi==0.19.2 -jiter==0.9.0 -keyring==25.6.0 -markdown-it-py==3.0.0 -matplotlib-inline==0.1.7 -mdurl==0.1.2 -more-itertools==10.6.0 -mypy==1.15.0 -mypy-extensions==1.0.0 -mypy-protobuf==3.6.0 -nh3==0.2.20 -nodeenv==1.9.1 -numpy==2.0.2 -packaging==24.2 -parso==0.8.4 -pathspec==0.12.1 -pexpect==4.9.0 -platformdirs==4.3.6 -pluggy==1.5.0 -pre_commit==4.1.0 -prompt_toolkit==3.0.50 -protobuf==6.32.1 -ptyprocess==0.7.0 -pure_eval==0.2.3 -pydantic==2.10.6 -pydantic_core==2.27.2 -Pygments==2.19.1 -pyproject_hooks==1.2.0 -pytest==8.3.4 -python-dotenv==1.0.1 -PyYAML==6.0.2 -readme_renderer==44.0 -regex==2024.11.6 -requests==2.32.3 -requests-toolbelt==1.0.0 -rfc3986==2.0.0 -rich==13.9.4 -ruff==0.9.6 -shellingham==1.5.4 -sniffio==1.3.1 -stack-data==0.6.3 -testcontainers==4.9.2 -tiktoken==0.9.0 -tomli==2.2.1 -tomli_w==1.2.0 -tomlkit==0.13.2 -tqdm==4.67.1 -traitlets==5.14.3 -trove-classifiers==2025.3.13.13 -twine==6.1.0 -types-protobuf==6.30.2.20250822 -types-requests==2.32.0.20241016 -typing_extensions==4.12.2 -urllib3==2.3.0 -userpath==1.9.2 -uv==0.6.6 -virtualenv==20.29.2 -wcwidth==0.2.13 -wrapt==1.17.2 -zipp==3.21.0 -zstandard==0.23.0 +certifi==2026.5.20 +charset-normalizer==3.4.7 +idna==3.18 +pydantic==2.13.4 +pydantic_core==2.46.4 +requests==2.34.2 +typing-inspection==0.4.2 +typing_extensions==4.15.0 +urllib3==2.7.0 diff --git a/src/lionweb/api/composite_classifier_instance_resolver.py b/src/lionweb/api/composite_classifier_instance_resolver.py index 4475bf1..a316f56 100644 --- a/src/lionweb/api/composite_classifier_instance_resolver.py +++ b/src/lionweb/api/composite_classifier_instance_resolver.py @@ -3,6 +3,11 @@ class CompositeClassifierInstanceResolver(ClassifierInstanceResolver): + """A resolver that delegates to a sequence of resolvers, in order. + + The first resolver able to resolve a given instance ID wins. + """ + def __init__(self, *classifier_instance_resolvers: ClassifierInstanceResolver): self.classifier_instance_resolvers: list[ClassifierInstanceResolver] = list( classifier_instance_resolvers @@ -11,10 +16,27 @@ def __init__(self, *classifier_instance_resolvers: ClassifierInstanceResolver): def add( self, classifier_instance_resolver: ClassifierInstanceResolver ) -> "CompositeClassifierInstanceResolver": + """Append a resolver to the chain. + + Args: + classifier_instance_resolver: The resolver to add. + + Returns: + CompositeClassifierInstanceResolver: This instance, to allow chaining. + """ self.classifier_instance_resolvers.append(classifier_instance_resolver) return self def resolve(self, instance_id: str) -> ClassifierInstance | None: + """Resolve the instance ID using the first resolver in the chain that succeeds. + + Args: + instance_id: The ID of the classifier instance to resolve. + + Returns: + The resolved classifier instance, or None if no resolver in the chain + could resolve it. + """ for resolver in self.classifier_instance_resolvers: instance = resolver.resolve(instance_id) if instance is not None: diff --git a/src/lionweb/api/local_classifier_instance_resolver.py b/src/lionweb/api/local_classifier_instance_resolver.py index e55c7f7..5d3ab5d 100644 --- a/src/lionweb/api/local_classifier_instance_resolver.py +++ b/src/lionweb/api/local_classifier_instance_resolver.py @@ -8,23 +8,52 @@ class LocalClassifierInstanceResolver(ClassifierInstanceResolver): + """A resolver backed by an in-memory dictionary of classifier instances, keyed by ID.""" + def __init__(self, *instances: "ClassifierInstance"): self.instances: dict[str, ClassifierInstance] = { cast(str, instance.id): instance for instance in instances if instance.id } - def add(self, instance) -> "LocalClassifierInstanceResolver": - self.instances[instance.id] = instance + def add(self, instance: "ClassifierInstance") -> "LocalClassifierInstanceResolver": + """Register a single classifier instance, keyed by its ID. + + Args: + instance: The classifier instance to register. + + Returns: + LocalClassifierInstanceResolver: This instance, to allow chaining. + """ + if instance.id is not None: + self.instances[instance.id] = instance return self - def resolve(self, instance_id) -> Optional["ClassifierInstance"]: + def resolve(self, instance_id: str) -> Optional["ClassifierInstance"]: + """Look up a classifier instance by ID in the local registry. + + Args: + instance_id: The ID of the classifier instance to resolve. + + Returns: + The registered classifier instance, or None if not registered. + """ return self.instances.get(instance_id) def extend(self, instances: Iterable["ClassifierInstance"]) -> None: + """Register multiple classifier instances. + + Args: + instances: The classifier instances to register. + """ for instance in instances: self.add(instance) - def add_tree(self, root: "ClassifierInstance"): + def add_tree(self, root: "ClassifierInstance") -> None: + """Register the given instance and all of its descendants, recursively. + + Args: + root: The root of the tree of classifier instances to register. + """ self.add(root) for child in root.get_children(): self.add_tree(child) diff --git a/src/lionweb/client/bulk_import.py b/src/lionweb/client/bulk_import.py index 930bfaf..85bd250 100644 --- a/src/lionweb/client/bulk_import.py +++ b/src/lionweb/client/bulk_import.py @@ -1,3 +1,5 @@ +from dataclasses import dataclass + from lionweb import LionWebVersion from lionweb.language import Containment from lionweb.model import ClassifierInstance @@ -10,6 +12,14 @@ class BulkImport: + """Accumulates serialized nodes and attach points for a bulk-import request. + + Nodes can be added either as already-serialized `SerializedClassifierInstance` + objects, or as live `ClassifierInstance` objects (which get serialized + immediately). Attach points describe where imported subtrees should be + grafted onto an existing repository. + """ + # Cache for JsonSerialization per LionWebVersion _json_serializations: dict[LionWebVersion, JsonSerialization] = {} @@ -89,11 +99,20 @@ def __bool__(self) -> bool: # --- nested class --- + @dataclass class AttachPoint: - def __init__(self, container: str, containment: MetaPointer, root_id: str) -> None: - self.container: str = container - self.containment: MetaPointer = containment - self.root_id: str = root_id + """Describes where a set of imported nodes should be attached. + + Attributes: + container: ID of the node that will contain the imported root. + containment: The containment feature (as a MetaPointer) under which + the imported root will be attached. + root_id: ID of the root node being attached. + """ + + container: str + containment: MetaPointer + root_id: str @classmethod def from_meta( diff --git a/src/lionweb/client/client.py b/src/lionweb/client/client.py index ebdb975..e683b25 100644 --- a/src/lionweb/client/client.py +++ b/src/lionweb/client/client.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, cast import requests from pydantic import BaseModel @@ -15,6 +15,20 @@ from .bulk_import import BulkImport +class LionWebServerError(RuntimeError): + """Raised when a LionWeb repository server responds with a non-success status code. + + Attributes: + status_code: The HTTP status code returned by the server. + response_text: The raw response body returned by the server. + """ + + def __init__(self, status_code: int, response_text: str): + super().__init__(f"Error: {status_code} {response_text}") + self.status_code = status_code + self.response_text = response_text + + class RepositoryConfiguration(BaseModel): name: str lionweb_version: LionWebVersion @@ -22,11 +36,18 @@ class RepositoryConfiguration(BaseModel): class Client: + """HTTP client for interacting with a LionWeb repository server. + + Wraps the LionWeb repository REST APIs (DB admin, bulk, inspection and + additional APIs), handling serialization/deserialization of nodes via a + JsonSerialization instance. + """ + def __init__( self, - lionweb_version=LionWebVersion.current_version(), - server_url="http://localhost:3005", - client_id="lwpython", + lionweb_version: LionWebVersion = LionWebVersion.current_version(), + server_url: str = "http://localhost:3005", + client_id: str = "lwpython", repository_name: str | None = "default", serialization: JsonSerialization | None = None, unavailable_parent_policy: UnavailableNodePolicy = UnavailableNodePolicy.PROXY_NODES, @@ -39,7 +60,7 @@ def __init__( self._lionweb_version = lionweb_version self._server_url = server_url self._client_id = client_id - self._repository_name = repository_name + self._repository_name: str | None = repository_name if serialization is None: self._serialization = create_standard_json_serialization(self._lionweb_version) else: @@ -48,16 +69,18 @@ def __init__( self._serialization.unavailable_children_policy = unavailable_children_policy def serialization(self) -> JsonSerialization: + """Return the JsonSerialization used by this client.""" return self._serialization - def set_repository_name(self, repository_name): + def set_repository_name(self, repository_name: str | None) -> None: + """Change the repository this client operates against.""" self._repository_name = repository_name ##################################################### # DB Admin APIs # ##################################################### - def create_database(self): + def create_database(self) -> None: url = f"{self._server_url}/createDatabase" headers = {"Content-Type": "application/json"} query_params = { @@ -65,15 +88,15 @@ def create_database(self): } response = requests.post(url, params=query_params, headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) - def list_repositories(self): + def list_repositories(self) -> list[RepositoryConfiguration]: url = f"{self._server_url}/listRepositories" headers = {"Content-Type": "application/json"} query_params = {"clientId": self._client_id} response = requests.post(url, params=query_params, headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) return [ RepositoryConfiguration( name=r["name"], @@ -83,7 +106,7 @@ def list_repositories(self): for r in response.json()["repositories"] ] - def create_repository(self, repository_configuration: RepositoryConfiguration): + def create_repository(self, repository_configuration: RepositoryConfiguration) -> None: url = f"{self._server_url}/createRepository" headers = {"Content-Type": "application/json"} query_params = { @@ -94,21 +117,21 @@ def create_repository(self, repository_configuration: RepositoryConfiguration): } response = requests.post(url, params=query_params, headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) - def delete_repository(self, repository_name: str): + def delete_repository(self, repository_name: str) -> None: url = f"{self._server_url}/deleteRepository" headers = {"Content-Type": "application/json"} query_params = {"clientId": self._client_id, "repository": repository_name} response = requests.post(url, params=query_params, headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) ##################################################### # Bulk APIs # ##################################################### - def list_partitions(self): + def list_partitions(self) -> list: url = f"{self._server_url}/bulk/listPartitions" headers = {"Content-Type": "application/json"} query_params = { @@ -117,13 +140,13 @@ def list_partitions(self): } response = requests.post(url, params=query_params, headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) return response.json()["chunk"]["nodes"] - def create_partition(self, node: Node): + def create_partition(self, node: Node) -> None: self.create_partitions([node]) - def create_partitions(self, nodes: list["Node"]): + def create_partitions(self, nodes: list["Node"]) -> None: for n in nodes: if len(n.get_children(containment=None)) > 0: raise ValueError("Cannot store a node with children as a new partition") @@ -134,12 +157,14 @@ def create_partitions(self, nodes: list["Node"]): "repository": self._repository_name, "clientId": self._client_id, } - data = self._serialization.serialize_trees_to_json_element(nodes) - response = requests.post(url, params=query_params, json=data, headers=headers) + data = self._serialization.serialize_trees_to_json_element( + cast("list[ClassifierInstance]", nodes) + ) + response = requests.post(url, params=query_params, json=cast(Any, data), headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) - def delete_partitions(self, node_ids: list[str]): + def delete_partitions(self, node_ids: list[str]) -> None: if len(node_ids) == 0: return @@ -151,7 +176,7 @@ def delete_partitions(self, node_ids: list[str]): } response = requests.post(url, params=query_params, json=node_ids, headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) def ids(self, count: int | None = None) -> list[str]: url = f"{self._server_url}/bulk/ids" @@ -164,10 +189,10 @@ def ids(self, count: int | None = None) -> list[str]: query_params["count"] = str(count) response = requests.post(url, params=query_params, headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) return response.json()["ids"] - def store(self, nodes: list["ClassifierInstance"]): + def store(self, nodes: list["ClassifierInstance"]) -> None: url = f"{self._server_url}/bulk/store" headers = {"Content-Type": "application/json"} query_params = { @@ -175,18 +200,18 @@ def store(self, nodes: list["ClassifierInstance"]): "clientId": self._client_id, } data = self._serialization.serialize_trees_to_json_element(nodes) - response = requests.post(url, params=query_params, json=data, headers=headers) + response = requests.post(url, params=query_params, json=cast(Any, data), headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) - def retrieve(self, ids: list[str], depth_limit: int | None = None): + def retrieve(self, ids: list[str], depth_limit: int | None = None) -> list[Node]: if not self._is_list_of_strings(ids): raise ValueError(f"ids should be a list of strings, but we got {ids}") data = self._retrieve_raw(ids, depth_limit=depth_limit) nodes = self._serialization.deserialize_json_to_nodes(data["chunk"]) return nodes - def _retrieve_raw(self, ids: list[str], depth_limit: int | None = None): + def _retrieve_raw(self, ids: list[str], depth_limit: int | None = None) -> dict: if not self._is_list_of_strings(ids): raise ValueError(f"ids should be a list of strings, but we got {ids}") url = f"{self._server_url}/bulk/retrieve" @@ -205,16 +230,16 @@ def _retrieve_raw(self, ids: list[str], depth_limit: int | None = None): data = response.json() return data else: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) - def _is_list_of_strings(self, value): + def _is_list_of_strings(self, value) -> bool: return isinstance(value, list) and all(isinstance(item, str) for item in value) ##################################################### # Inspection APIs # ##################################################### - def nodes_by_classifier(self): + def nodes_by_classifier(self) -> list: url = f"{self._server_url}/inspection/nodesByClassifier" headers = {"Content-Type": "application/json"} query_params = { @@ -223,11 +248,11 @@ def nodes_by_classifier(self): } response = requests.get(url, params=query_params, headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) # return an array of language, classifier, ids, size return response.json() - def nodes_by_language(self): + def nodes_by_language(self) -> list: url = f"{self._server_url}/inspection/nodesByLanguage" headers = {"Content-Type": "application/json"} query_params = { @@ -236,7 +261,7 @@ def nodes_by_language(self): } response = requests.get(url, params=query_params, headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) # return an array of language, ids, size return response.json() @@ -244,14 +269,14 @@ def nodes_by_language(self): # Convenience methods # ##################################################### - def retrieve_partition(self, id: str, depth_limit: int | None = None): + def retrieve_partition(self, id: str, depth_limit: int | None = None) -> Node: res = self.retrieve([id], depth_limit=depth_limit) - roots = [n for n in res if res.get_parent() is None] + roots = [n for n in res if n.get_parent() is None] if len(roots) != 1: - raise ValueError() + raise ValueError(f"Expected one root partition for id {id}, found {len(roots)}") return roots[0] - def retrieve_node(self, id: str, depth_limit: int | None = None): + def retrieve_node(self, id: str, depth_limit: int | None = None) -> Node: from lionweb.model.impl.proxy_node import ProxyNode retrieved_nodes = self.retrieve([id], depth_limit=depth_limit) @@ -294,7 +319,7 @@ def get_parent_id(self, node_id: str) -> str | None: """ nodes = self._retrieve_raw([node_id], depth_limit=0)["chunk"]["nodes"] if len(nodes) != 1: - raise ValueError() + raise ValueError(f"Expected exactly one node for id {node_id}, found {len(nodes)}") node = nodes[0] return node["parent"] @@ -302,7 +327,7 @@ def get_parent_id(self, node_id: str) -> str | None: # Additional APIs # ##################################################### - def bulk_import_using_json(self, bulk_import: "BulkImport"): + def bulk_import_using_json(self, bulk_import: "BulkImport") -> None: body_attach_points = [] for attach_point in bulk_import.get_attach_points(): @@ -336,6 +361,6 @@ def bulk_import_using_json(self, bulk_import: "BulkImport"): } url = f"{self._server_url}/additional/bulkImport" - response = requests.post(url, params=query_params, json=body, headers=headers) + response = requests.post(url, params=query_params, json=cast(Any, body), headers=headers) if response.status_code != 200: - raise ValueError("Error:", response.status_code, response.text) + raise LionWebServerError(response.status_code, response.text) diff --git a/src/lionweb/client/repository_archives.py b/src/lionweb/client/repository_archives.py index 99bb8f9..c92dfa6 100644 --- a/src/lionweb/client/repository_archives.py +++ b/src/lionweb/client/repository_archives.py @@ -4,7 +4,21 @@ from lionweb.serialization import LowLevelJsonSerialization -def load_repository_archive(client: Client, archive_path: str, upload_threshold=250_000): +def load_repository_archive( + client: Client, archive_path: str, upload_threshold: int = 250_000 +) -> None: + """Load a repository archive (a zip of JSON serialization chunks) into a server. + + The archive is read entry by entry; nodes are accumulated into a BulkImport + and uploaded in batches once the number of pending nodes exceeds + `upload_threshold`, to limit memory usage and request size. + + Args: + client: The client used to talk to the LionWeb repository server. + archive_path: Path to the zip archive containing `.json` serialization chunks. + upload_threshold: Maximum number of pending nodes to accumulate before + triggering an upload. + """ import time def upload(bulk_import: BulkImport) -> int: diff --git a/src/lionweb/generation/ASTBuilder.py b/src/lionweb/generation/ASTBuilder.py index 0dfd789..016e3ab 100644 --- a/src/lionweb/generation/ASTBuilder.py +++ b/src/lionweb/generation/ASTBuilder.py @@ -5,14 +5,40 @@ class ASTBuilder: """Helper mixin to reduce ast verbosity.""" def name(self, id: str | None, ctx=None) -> ast.Name: + """Build an `ast.Name` node. + + Args: + id: The identifier name (must not be None). + ctx: The expression context to use; defaults to `ast.Load()`. + + Returns: + ast.Name: The constructed name node. + + Raises: + ValueError: If `id` is None. + """ if id is None: raise ValueError("id must not be None") return ast.Name(id=id, ctx=ctx or ast.Load()) def const(self, value) -> ast.Constant: + """Build an `ast.Constant` node wrapping the given value.""" return ast.Constant(value=value) def attr(self, value, attr: str | None, ctx=None) -> ast.Attribute: + """Build an `ast.Attribute` access node (e.g. `value.attr`). + + Args: + value: Either a string (interpreted as a name) or an existing AST node. + attr: The attribute name to access (must not be None). + ctx: The expression context to use; defaults to `ast.Load()`. + + Returns: + ast.Attribute: The constructed attribute-access node. + + Raises: + ValueError: If `attr` is None. + """ if attr is None: raise ValueError("attr must not be None") # value can be a string (implies a Name node) or an AST node @@ -21,9 +47,18 @@ def attr(self, value, attr: str | None, ctx=None) -> ast.Attribute: return ast.Attribute(value=value, attr=attr, ctx=ctx or ast.Load()) def call(self, func, args=None, keywords=None) -> ast.Call: - """Creates a function call. - 'func' can be a string (function name) or an AST node. - 'keywords' is a dict of {arg_name: ast_node}. + """Build an `ast.Call` node representing a function call. + + Args: + func: Either a string (function name) or an existing AST node + representing the callee. + args: Positional argument AST nodes. + keywords: A dict of `{arg_name: ast_node}` mapping keyword argument + names to their value expressions; entries with a None value are + skipped. + + Returns: + ast.Call: The constructed call node. """ if isinstance(func, str): func = self.name(func) @@ -38,4 +73,5 @@ def call(self, func, args=None, keywords=None) -> ast.Call: return ast.Call(func=func, args=args or [], keywords=ast_keywords) def assign(self, target_id: str, value) -> ast.Assign: + """Build an `ast.Assign` node assigning `value` to a single named target.""" return ast.Assign(targets=[self.name(target_id, ctx=ast.Store())], value=value) diff --git a/src/lionweb/generation/__init__.py b/src/lionweb/generation/__init__.py index e69de29..fa89a1b 100644 --- a/src/lionweb/generation/__init__.py +++ b/src/lionweb/generation/__init__.py @@ -0,0 +1,21 @@ +from .ASTBuilder import ASTBuilder as ASTBuilder +from .base_generator import BaseGenerator as BaseGenerator +from .configuration import LanguageMappingSpec as LanguageMappingSpec +from .configuration import PrimitiveTypeMappingSpec as PrimitiveTypeMappingSpec +from .deserializer_generation import DeserializerGenerator as DeserializerGenerator +from .language_generation import LanguageGenerator as LanguageGenerator +from .node_classes_generation import NodeClassesGenerator as NodeClassesGenerator +from .topological_sorting import ( + topological_classifiers_sort as topological_classifiers_sort, +) + +__all__ = [ + "ASTBuilder", + "BaseGenerator", + "LanguageMappingSpec", + "PrimitiveTypeMappingSpec", + "DeserializerGenerator", + "LanguageGenerator", + "NodeClassesGenerator", + "topological_classifiers_sort", +] diff --git a/src/lionweb/generation/base_generator.py b/src/lionweb/generation/base_generator.py index a93563a..bb9eed1 100644 --- a/src/lionweb/generation/base_generator.py +++ b/src/lionweb/generation/base_generator.py @@ -61,6 +61,14 @@ def _package_lookup(self, language: Language) -> str | None: return None def _data_type_lookup(self, primitive_type: DataType) -> str | None: + """Find the qualified Python type name mapped to the given primitive type. + + Args: + primitive_type: The primitive data type to look up, matched by ID or name. + + Returns: + str | None: The qualified Python type name if a mapping exists, else None. + """ for mapping in self.primitive_types: if ( primitive_type.id == mapping.primitive_type diff --git a/src/lionweb/generation/deserializer_generation.py b/src/lionweb/generation/deserializer_generation.py index 133238a..9913666 100644 --- a/src/lionweb/generation/deserializer_generation.py +++ b/src/lionweb/generation/deserializer_generation.py @@ -14,6 +14,14 @@ class DeserializerGenerator(BaseGenerator, ASTBuilder): + """Generates a `deserializer.py` module for a given LionWeb language. + + The generated module defines, for each Concept in the language, a small + deserializer function that instantiates the corresponding generated Python + class, plus a `register_deserializers` function that registers all of them + on a serialization instance. + """ + def __init__( self, language_packages: tuple[LanguageMappingSpec, ...], @@ -21,7 +29,15 @@ def __init__( ): super().__init__(language_packages, primitive_types) - def deserializer_generation(self, click, language: Language, output): + def deserializer_generation(self, click, language: Language, output: str) -> None: + """Generate and write `deserializer.py` for the given language. + + Args: + click: The click module/context used to print progress messages. + language: The LionWeb language to generate a deserializer for. + output: Directory path where `deserializer.py` will be written + (created if it does not exist). + """ module_body = [] # Import statements diff --git a/src/lionweb/generation/generation_utils.py b/src/lionweb/generation/generation_utils.py index ff44bcb..f80b001 100644 --- a/src/lionweb/generation/generation_utils.py +++ b/src/lionweb/generation/generation_utils.py @@ -4,6 +4,17 @@ def make_class_def(name: str, bases: list[ast.expr], body: list[ast.stmt]) -> ast.ClassDef: + """Build an `ast.ClassDef` node, handling the Python-version-specific fields. + + Args: + name: The class name. + bases: AST expressions for the base classes. + body: Statements making up the class body. + + Returns: + ast.ClassDef: The constructed class-definition node, with `type_params` + populated only on Python 3.12+ where the field is required. + """ if sys.version_info >= (3, 12): return ast.ClassDef( name=name, @@ -24,6 +35,22 @@ def make_function_def( decorator_list: list[ast.expr] | None = None, returns: ast.expr | None = None, ) -> ast.FunctionDef: + """Build an `ast.FunctionDef` node, handling the Python-version-specific fields. + + Args: + name: The function name (must not be None). + args: The function's argument specification. + body: Statements making up the function body. + decorator_list: AST expressions for decorators applied to the function. + returns: AST expression for the return type annotation, if any. + + Returns: + ast.FunctionDef: The constructed function-definition node, with + `type_params` populated only on Python 3.12+ where the field is required. + + Raises: + ValueError: If `name` is None. + """ if name is None: raise ValueError("Name should not be None") diff --git a/src/lionweb/generation/language_generation.py b/src/lionweb/generation/language_generation.py index 1284cb6..860a493 100644 --- a/src/lionweb/generation/language_generation.py +++ b/src/lionweb/generation/language_generation.py @@ -28,6 +28,14 @@ class LanguageGenerator(BaseGenerator, ASTBuilder): + """Generates a `language.py` module describing a LionWeb language in Python. + + The generated module builds, via a `get_language()` function, a `Language` + instance mirroring the input LionWeb language (concepts, interfaces, + primitive types, enumerations, and their features), plus convenience getter + functions (e.g. `get_`) for each concept and primitive type. + """ + def __init__( self, language_packages: tuple[LanguageMappingSpec, ...] = (), @@ -341,7 +349,15 @@ def _define_enumeration_in_language( get_language_body.append(self._add_to_language(var_name)) - def language_generation(self, click, language: Language, output): + def language_generation(self, click, language: Language, output: str) -> None: + """Generate and write `language.py` for the given language. + + Args: + click: The click module/context used to print progress messages. + language: The LionWeb language to generate Python code for. + output: Directory path where `language.py` will be written + (created if it does not exist). + """ # 1. Clean Static Imports # Instead of building nodes manually, parse a string. It's readable and standard. body = ast.parse( @@ -357,21 +373,23 @@ def language_generation(self, click, language: Language, output): # Creation Loop for el in language.get_elements(): - if isinstance(el, Concept): - self._create_concept_in_language(el, func_body) - elif isinstance(el, Interface): - self._create_interface_in_language(el, func_body) - elif isinstance(el, PrimitiveType): - self._define_primitive_type_in_language(el, func_body) - elif isinstance(el, Enumeration): - self._define_enumeration_in_language(el, func_body) + match el: + case Concept(): + self._create_concept_in_language(el, func_body) + case Interface(): + self._create_interface_in_language(el, func_body) + case PrimitiveType(): + self._define_primitive_type_in_language(el, func_body) + case Enumeration(): + self._define_enumeration_in_language(el, func_body) # Population Loop for el in language.get_elements(): - if isinstance(el, Concept): - self._populate_concept_in_language(el, func_body) - elif isinstance(el, Interface): - self._populate_interface_in_language(el, func_body) + match el: + case Concept(): + self._populate_concept_in_language(el, func_body) + case Interface(): + self._populate_interface_in_language(el, func_body) # Return statement func_body.append(ast.Return(value=self.name("language"))) @@ -391,10 +409,11 @@ def language_generation(self, click, language: Language, output): # 4. Generate Getters (Refactored duplication) for el in language.get_elements(): - if isinstance(el, Concept): - self._add_getter_method(el, "get_concept_by_name", "Concept") - elif isinstance(el, PrimitiveType): - self._add_getter_method(el, "get_primitive_type_by_name", "PrimitiveType") + match el: + case Concept(): + self._add_getter_method(el, "get_concept_by_name", "Concept") + case PrimitiveType(): + self._add_getter_method(el, "get_primitive_type_by_name", "PrimitiveType") # 5. Final Assembly body.extend(self.imports) diff --git a/src/lionweb/generation/naming_utils.py b/src/lionweb/generation/naming_utils.py index 2d4b461..4ef36bb 100644 --- a/src/lionweb/generation/naming_utils.py +++ b/src/lionweb/generation/naming_utils.py @@ -21,6 +21,17 @@ def dotted_name_expr(dotted: str) -> ast.expr: def calculate_field_name(feature: Feature) -> str: + """Compute the Python field name for a LionWeb feature. + + Appends a trailing underscore if the feature's name collides with a + Python keyword. + + Args: + feature: The feature whose field name should be computed. + + Returns: + str: A Python-safe field name. + """ field_name = cast(str, feature.get_name()) if field_name in keyword.kwlist: field_name = f"{field_name}_" @@ -28,6 +39,17 @@ def calculate_field_name(feature: Feature) -> str: def to_snake_case(name: str | None) -> str: + """Convert a CamelCase/PascalCase name to snake_case. + + Args: + name: The name to convert (must not be None or empty). + + Returns: + str: The snake_case version of the name. + + Raises: + ValueError: If `name` is None or empty. + """ if not name: raise ValueError("Name should not be None") # Replace capital letters with _lowercase, except at the beginning @@ -37,7 +59,18 @@ def to_snake_case(name: str | None) -> str: def to_var_name(name: str | None) -> str: - """Convert a name to snake_case while avoiding Python keywords.""" + """Convert a name to snake_case while avoiding Python keywords. + + Args: + name: The name to convert (must not be None). + + Returns: + str: A snake_case identifier safe to use as a Python variable name, + with a trailing underscore appended if it would otherwise be a keyword. + + Raises: + ValueError: If `name` is None. + """ import keyword import re @@ -58,13 +91,34 @@ def to_var_name(name: str | None) -> str: def to_type_name(name: str | None) -> str: - """Convert a name to snake_case while avoiding Python keywords.""" + """Convert a name to a Python type/class name by capitalizing its first letter. + + Args: + name: The name to convert (must not be None). + + Returns: + str: The name with its first letter capitalized. + + Raises: + ValueError: If `name` is None. + """ if name is None: raise ValueError("Name should not be None") return name[0].upper() + name[1:] def getter_name(name: str | None) -> str: + """Compute the conventional getter method name (`get_`) for a feature name. + + Args: + name: The feature name (must not be None). + + Returns: + str: The getter method name. + + Raises: + ValueError: If `name` is None. + """ if name is None: raise ValueError("Name should not be None") return f"get_{to_snake_case(name)}" diff --git a/src/lionweb/generation/node_classes_generation.py b/src/lionweb/generation/node_classes_generation.py index caba2a4..5951397 100644 --- a/src/lionweb/generation/node_classes_generation.py +++ b/src/lionweb/generation/node_classes_generation.py @@ -26,6 +26,14 @@ class NodeClassesGenerator(BaseGenerator, ASTBuilder): + """Generates Python source files for the classes of a LionWeb language. + + For each Concept, Interface and Enumeration in the language, a dedicated + module is written (one class per file), including generated getters/setters + for properties, containments and references. An `__init__.py` re-exporting + all generated classes is written as well. + """ + def __init__( self, language_packages: tuple[LanguageMappingSpec, ...], @@ -185,15 +193,16 @@ def _resolve_property_type_for_node_class(self, feature: Property, concept: Conc if f_type == LionCoreBuiltins.get_boolean(concept.lion_web_version): return "bool" - elif f_type == LionCoreBuiltins.get_string(concept.lion_web_version): + if f_type == LionCoreBuiltins.get_string(concept.lion_web_version): return "str" - elif f_type == LionCoreBuiltins.get_integer(concept.lion_web_version): + if f_type == LionCoreBuiltins.get_integer(concept.lion_web_version): return "int" - elif f_type.language == concept.language: - if isinstance(f_type, Enumeration): - return to_type_name(f_type.name) - else: - raise ValueError("using type that we are generating") + if f_type.language == concept.language: + match f_type: + case Enumeration(): + return to_type_name(f_type.name) + case _: + raise ValueError("using type that we are generating") else: qualified_name = self._data_type_lookup(f_type) if qualified_name is not None: @@ -590,7 +599,19 @@ def _generate_multiple_containment_adder(self, feature: Containment, prop_type: returns=None, ) - def node_classes_generation(self, click, language: Language, output): + def node_classes_generation(self, click, language: Language, output: str) -> None: + """Generate and write one Python module per Concept/Interface/Enumeration. + + Concepts are generated in topological (dependency-first) order so that + a concept's base classes are always defined before it. An `__init__.py` + re-exporting all generated classes is written last. + + Args: + click: The click module/context used to print progress messages. + language: The LionWeb language to generate node classes for. + output: Directory path where the generated files will be written + (created if it does not exist). + """ output_path = Path(output) output_path.mkdir(parents=True, exist_ok=True) click.echo(f"📂 Generating node classes to: {output}") @@ -761,30 +782,35 @@ def _generate_concept_class(self, concept: Concept): methods: list[stmt] = [init_func] for feature in self._relevant_features(concept): - if isinstance(feature, Property): - prop_type = self._resolve_property_type_for_node_class(feature, concept) - methods.append(self._generate_property_getter(feature, prop_type)) - methods.append(self._generate_property_setter(feature, prop_type)) - elif isinstance(feature, Containment): - feature_type = cast(Classifier, feature.get_type()) - prop_type = cast(str, feature_type.get_name()) - if feature.is_multiple(): - methods.append(self._generate_multiple_containment_getter(feature, prop_type)) - methods.append(self._generate_multiple_containment_adder(feature, prop_type)) - else: - methods.append(self._generate_containment_getter(feature, prop_type)) - methods.append(self._generate_containment_setter(feature, prop_type)) - elif isinstance(feature, Reference): - feature_type = cast(Classifier, feature.get_type()) - prop_type = cast(str, feature_type.get_name()) - if feature.is_multiple(): - methods.append(self._generate_multiple_reference_getter(feature, prop_type)) - methods.append(self._generate_multiple_reference_adder(feature, prop_type)) - else: - methods.append(self._generate_reference_getter(feature, prop_type)) - methods.append(self._generate_reference_setter(feature, prop_type)) - else: - raise ValueError(f"Unsupported feature type: {type(feature)}") + match feature: + case Property(): + prop_type = self._resolve_property_type_for_node_class(feature, concept) + methods.append(self._generate_property_getter(feature, prop_type)) + methods.append(self._generate_property_setter(feature, prop_type)) + case Containment(): + feature_type = cast(Classifier, feature.get_type()) + prop_type = cast(str, feature_type.get_name()) + if feature.is_multiple(): + methods.append( + self._generate_multiple_containment_getter(feature, prop_type) + ) + methods.append( + self._generate_multiple_containment_adder(feature, prop_type) + ) + else: + methods.append(self._generate_containment_getter(feature, prop_type)) + methods.append(self._generate_containment_setter(feature, prop_type)) + case Reference(): + feature_type = cast(Classifier, feature.get_type()) + prop_type = cast(str, feature_type.get_name()) + if feature.is_multiple(): + methods.append(self._generate_multiple_reference_getter(feature, prop_type)) + methods.append(self._generate_multiple_reference_adder(feature, prop_type)) + else: + methods.append(self._generate_reference_getter(feature, prop_type)) + methods.append(self._generate_reference_setter(feature, prop_type)) + case _: + raise ValueError(f"Unsupported feature type: {type(feature)}") # Determine base class extended_concept = concept.get_extended_concept() diff --git a/src/lionweb/generation/topological_sorting.py b/src/lionweb/generation/topological_sorting.py index 0664336..eebd059 100644 --- a/src/lionweb/generation/topological_sorting.py +++ b/src/lionweb/generation/topological_sorting.py @@ -4,37 +4,68 @@ def _identify_topological_deps( - classifiers: list[Classifier], id_to_concept + classifiers: list[Classifier], id_to_concept: dict ) -> dict[str, list[str]]: + """Build a dependency graph mapping each classifier ID to the IDs it depends on. + + A classifier depends on its extended concept/interfaces, the interfaces it + implements, and the (concept) types of its containments — but only for + dependencies that are themselves part of `classifiers`. + + Args: + classifiers: The classifiers to analyze. + id_to_concept: Mapping from classifier ID to classifier, restricted to + the classifiers of interest; used to filter out external dependencies. + + Returns: + dict[str, list[str]]: Adjacency list mapping each classifier ID to the + list of IDs it depends on. + + Raises: + ValueError: If a classifier is neither a Concept nor an Interface. + """ graph: dict[str, list[str]] = {cast(str, el.get_id()): [] for el in classifiers} for c in classifiers: - if isinstance(c, Concept): - c_id = cast(str, c.get_id()) - ec = c.get_extended_concept() - if ec and cast(str, ec.get_id()) in id_to_concept: - graph[c_id].append(cast(str, ec.get_id())) - for i in c.get_implemented(): - graph[c_id].append(cast(str, i.get_id())) - for f in c.get_features(): - if isinstance(f, Containment): - f_type = f.get_type() - if f_type and cast(str, f_type.get_id()) in id_to_concept: - graph[cast(str, c_id)].append(cast(str, f_type.get_id())) - elif isinstance(c, Interface): - c_id = cast(str, c.get_id()) - for i in c.get_extended_interfaces(): - graph[c_id].append(cast(str, i.get_id())) - for f in c.get_features(): - if isinstance(f, Containment): - f_type = f.get_type() - if f_type and cast(str, f_type.get_id()) in id_to_concept: - graph[cast(str, c_id)].append(cast(str, f_type.get_id())) - else: - raise ValueError() + match c: + case Concept(): + c_id = cast(str, c.get_id()) + ec = c.get_extended_concept() + if ec and cast(str, ec.get_id()) in id_to_concept: + graph[c_id].append(cast(str, ec.get_id())) + for i in c.get_implemented(): + graph[c_id].append(cast(str, i.get_id())) + for f in c.get_features(): + if isinstance(f, Containment): + f_type = f.get_type() + if f_type and cast(str, f_type.get_id()) in id_to_concept: + graph[cast(str, c_id)].append(cast(str, f_type.get_id())) + case Interface(): + c_id = cast(str, c.get_id()) + for i in c.get_extended_interfaces(): + graph[c_id].append(cast(str, i.get_id())) + for f in c.get_features(): + if isinstance(f, Containment): + f_type = f.get_type() + if f_type and cast(str, f_type.get_id()) in id_to_concept: + graph[cast(str, c_id)].append(cast(str, f_type.get_id())) + case _: + raise ValueError(f"Unsupported classifier type: {type(c).__name__}") return graph def topological_classifiers_sort(classifiers: list[Classifier]) -> list[Classifier]: + """Sort classifiers so that each one appears after the classifiers it depends on. + + Dependencies considered are: extended concepts/interfaces, implemented + interfaces, and containment target types (limited to the given classifiers). + The sort is a depth-first post-order traversal of the dependency graph. + + Args: + classifiers: The classifiers to sort. + + Returns: + list[Classifier]: The classifiers in topological (dependency-first) order. + """ id_to_concept = {el.get_id(): el for el in classifiers} # Build graph edges: child -> [parents] diff --git a/src/lionweb/language/__init__.py b/src/lionweb/language/__init__.py index 7e4356f..7c738c1 100644 --- a/src/lionweb/language/__init__.py +++ b/src/lionweb/language/__init__.py @@ -22,3 +22,30 @@ from .property import Property as Property from .reference import Reference as Reference from .structured_data_type import StructuredDataType as StructuredDataType + +__all__ = [ + "Annotation", + "Classifier", + "Concept", + "Containment", + "DataType", + "LanguageFactory", + "Multiplicity", + "Enumeration", + "EnumerationLiteral", + "Feature", + "Field", + "IKeyed", + "INamed", + "Interface", + "Language", + "LanguageEntity", + "Link", + "LionCoreBuiltins", + "NamespaceProvider", + "NamespacedEntity", + "PrimitiveType", + "Property", + "Reference", + "StructuredDataType", +] diff --git a/src/lionweb/language/annotation.py b/src/lionweb/language/annotation.py index 8ac57ca..e346520 100644 --- a/src/lionweb/language/annotation.py +++ b/src/lionweb/language/annotation.py @@ -5,6 +5,8 @@ class Annotation(Classifier["Annotation"]): + """A classifier whose instances attach extra information to instances of another classifier.""" + if TYPE_CHECKING: from lionweb.language.concept import Concept from lionweb.language.feature import Feature @@ -63,7 +65,15 @@ def extended_annotation(self, extended: Optional["Annotation"]): def implemented(self) -> list["Interface"]: return cast(list[Interface], self.get_reference_multiple_value("implements")) - def add_implemented_interface(self, iface: "Interface"): + def add_implemented_interface(self, iface: "Interface") -> None: + """Add an interface to the list of interfaces implemented by this annotation. + + Args: + iface: The interface to implement. + + Raises: + ValueError: If ``iface`` is ``None``. + """ if iface is None: raise ValueError("iface should not be null") from lionweb.model.reference_value import ReferenceValue diff --git a/src/lionweb/language/classifier.py b/src/lionweb/language/classifier.py index 1ac089b..55ad83c 100644 --- a/src/lionweb/language/classifier.py +++ b/src/lionweb/language/classifier.py @@ -11,6 +11,9 @@ class Classifier(LanguageEntity[T], NamespaceProvider): + """Base class for language entities that classify model nodes and declare features + (concepts, interfaces, annotations).""" + from lionweb.language.containment import Containment from lionweb.language.feature import Feature from lionweb.language.language import Language @@ -32,13 +35,27 @@ def __init__( super().__init__(lion_web_version=lion_web_version, language=language, name=name, id=id) def get_feature_by_name(self, name: str) -> Feature | None: + """Look up a feature (own or inherited) by its name. + + Args: + name: The name of the feature to find. + + Returns: + Optional[Feature]: The matching feature, or ``None`` if none is found. + """ return next((f for f in self.all_features() if f.get_name() == name), None) @abstractmethod def direct_ancestors(self) -> list["Classifier"]: + """Return the classifiers this classifier directly extends or implements.""" pass def all_ancestors(self) -> set["Classifier"]: + """Compute the transitive closure of all ancestor classifiers. + + Returns: + set[Classifier]: All ancestors reachable through ``direct_ancestors``. + """ result = set() ancestors = set(self.direct_ancestors()) while ancestors: @@ -49,12 +66,18 @@ def all_ancestors(self) -> set["Classifier"]: return result def all_features(self) -> list[Feature]: + """Return the own features combined with the inherited ones (own features take precedence). + + Returns: + list[Feature]: The combined list of features. + """ result = list(self.get_features()) self.combine_features(result, self.inherited_features()) return result @abstractmethod def inherited_features(self) -> list[Feature]: + """Return the features inherited from ancestor classifiers.""" pass def all_properties(self) -> list[Property]: @@ -85,6 +108,14 @@ def features(self) -> list[Feature]: return self.get_features() def add_feature(self, feature: Feature) -> "Classifier": + """Add a feature (own declaration) to this classifier and set its parent. + + Args: + feature: The feature to add. + + Returns: + Classifier: This classifier, to allow fluent chaining. + """ self.add_containment_multiple_value("features", feature) feature.set_parent(self) return self @@ -93,6 +124,13 @@ def namespace_qualifier(self) -> str: return self.qualified_name() def combine_features(self, features_a: list[Feature], features_b: list[Feature]) -> None: + """Append to ``features_a`` (in place) the features from ``features_b`` whose meta-pointer + is not already present in ``features_a``. + + Args: + features_a: The list to extend; entries already present take precedence. + features_b: The candidate features to merge in. + """ existing_metapointers = {MetaPointer.from_feature(f) for f in features_a} for f in features_b: meta_pointer = MetaPointer.from_feature(f) diff --git a/src/lionweb/language/concept.py b/src/lionweb/language/concept.py index 6927cd8..c86ff52 100644 --- a/src/lionweb/language/concept.py +++ b/src/lionweb/language/concept.py @@ -4,6 +4,9 @@ class Concept(Classifier["Concept"]): + """A classifier that defines instantiable node types, optionally extending another concept + and implementing interfaces.""" + from lionweb.language.feature import Feature from lionweb.language.interface import Interface from lionweb.language.language import Language diff --git a/src/lionweb/language/containment.py b/src/lionweb/language/containment.py index 63088ba..844dd5c 100644 --- a/src/lionweb/language/containment.py +++ b/src/lionweb/language/containment.py @@ -4,6 +4,8 @@ class Containment(Link["Containment"]): + """A link expressing a part-whole (ownership) relationship between classifiers.""" + if TYPE_CHECKING: from lionweb.language.classifier import Classifier from lionweb.language.concept import Concept diff --git a/src/lionweb/language/data_type.py b/src/lionweb/language/data_type.py index 4c7bfb4..2a1fabd 100644 --- a/src/lionweb/language/data_type.py +++ b/src/lionweb/language/data_type.py @@ -5,6 +5,8 @@ class DataType(LanguageEntity[M3Node]): + """Base class for the data types of a language: primitive types, enumerations, and structured data types.""" + def __init__( self, lion_web_version: LionWebVersion | None = None, diff --git a/src/lionweb/language/debug_utils.py b/src/lionweb/language/debug_utils.py index b24cba1..3449f6c 100644 --- a/src/lionweb/language/debug_utils.py +++ b/src/lionweb/language/debug_utils.py @@ -1,9 +1,19 @@ class DebugUtils: + """Helper utilities for producing debug-friendly string representations.""" + @staticmethod def qualified_name(namespaced_entity) -> str: - """ + """Compute a best-effort qualified name for a namespaced entity. + This variant of qualified name can be obtained also for invalid states. This is intended to be used in methods which should not throw exceptions, like toString methods. + + Args: + namespaced_entity: The entity (typically a ``NamespacedEntity``) to describe. + + Returns: + str: A qualified name such as ``"."`` falling back to + placeholder text when the container or name is missing. """ qualifier = "" if namespaced_entity.get_container() is not None: diff --git a/src/lionweb/language/definition.py b/src/lionweb/language/definition.py index 4eca69d..09f8435 100644 --- a/src/lionweb/language/definition.py +++ b/src/lionweb/language/definition.py @@ -243,37 +243,35 @@ def populate( classifier.add_extended_interface(cast(Interface, extends)) def build(self, language: Language) -> "Classifier": - if self.type == "Concept": - concept = Concept( - lion_web_version=language.lion_web_version, - language=language, - abstract=self.abstract, - partition=self.partition, - id=self.id, - key=self.key, - name=self.name, - ) - return concept - elif self.type == "Interface": - interface = Interface( - lion_web_version=language.lion_web_version, - language=language, - id=self.id, - key=self.key, - name=self.name, - ) - return interface - elif self.type == "Annotation": - annotation = Annotation( - lion_web_version=language.lion_web_version, - language=language, - id=self.id, - key=self.key, - name=self.name, - ) - return annotation - else: - raise ValueError(f"Invalid classifier type: {self.type}") + match self.type: + case "Concept": + return Concept( + lion_web_version=language.lion_web_version, + language=language, + abstract=self.abstract, + partition=self.partition, + id=self.id, + key=self.key, + name=self.name, + ) + case "Interface": + return Interface( + lion_web_version=language.lion_web_version, + language=language, + id=self.id, + key=self.key, + name=self.name, + ) + case "Annotation": + return Annotation( + lion_web_version=language.lion_web_version, + language=language, + id=self.id, + key=self.key, + name=self.name, + ) + case _: + raise ValueError(f"Invalid classifier type: {self.type}") def set_extends(self, extends: "Classifier | ClassifierFactory") -> "ClassifierFactory": self.extends = [extends] @@ -432,7 +430,7 @@ def __init__( lambda parent_id, name: name if parent_id is None else f"{parent_id}_{name}" ) self.key_calculator = key_calculator or ( - lambda parent_key, name: (name if parent_key is None else f"{parent_key}_{name}") + lambda parent_key, name: name if parent_key is None else f"{parent_key}_{name}" ) self.id = id or self.id_calculator(None, name) self.key = key or self.key_calculator(None, name) diff --git a/src/lionweb/language/enumeration.py b/src/lionweb/language/enumeration.py index 2fdf123..5afee9d 100644 --- a/src/lionweb/language/enumeration.py +++ b/src/lionweb/language/enumeration.py @@ -11,6 +11,8 @@ class Enumeration(DataType, NamespaceProvider): + """A data type defined as a fixed set of named literals.""" + def __init__( self, lion_web_version: Optional["LionWebVersion"] = None, @@ -28,6 +30,17 @@ def literals(self) -> list[EnumerationLiteral]: return self.get_containment_multiple_value("literals") def add_literal(self, literal: EnumerationLiteral) -> "Enumeration": + """Add a literal to this enumeration. + + Args: + literal: The literal to add. + + Returns: + Enumeration: This enumeration, to allow fluent chaining. + + Raises: + ValueError: If ``literal`` is ``None``. + """ if literal is None: raise ValueError("literal should not be null") self.add_containment_multiple_value(link_name="literals", value=literal) @@ -41,7 +54,15 @@ def get_classifier(self) -> "Concept": return LionCore.get_enumeration(self.get_lionweb_version()) - def get_literal_by_name(self, name) -> Optional["EnumerationLiteral"]: + def get_literal_by_name(self, name: str) -> Optional["EnumerationLiteral"]: + """Look up a literal by its name. + + Args: + name: The name of the literal to find. + + Returns: + Optional[EnumerationLiteral]: The matching literal, or ``None`` if none is found. + """ return next( (literal for literal in self.literals if literal.get_name() == name), None, diff --git a/src/lionweb/language/enumeration_literal.py b/src/lionweb/language/enumeration_literal.py index bdff480..9e2896b 100644 --- a/src/lionweb/language/enumeration_literal.py +++ b/src/lionweb/language/enumeration_literal.py @@ -6,6 +6,8 @@ class EnumerationLiteral(M3Node, NamespacedEntity, IKeyed): + """A single named literal value belonging to an Enumeration.""" + if TYPE_CHECKING: from lionweb.language.concept import Concept from lionweb.language.enumeration import Enumeration diff --git a/src/lionweb/language/feature.py b/src/lionweb/language/feature.py index b10e2d8..f2c9c18 100644 --- a/src/lionweb/language/feature.py +++ b/src/lionweb/language/feature.py @@ -10,6 +10,8 @@ class Feature(M3Node[T], NamespacedEntity, IKeyed[T], Generic[T]): + """Base class for the named, keyed members of a Classifier (properties and links).""" + if TYPE_CHECKING: from lionweb.language.classifier import Classifier from lionweb.language.language import Language diff --git a/src/lionweb/language/field.py b/src/lionweb/language/field.py index 2a50cb3..a440447 100644 --- a/src/lionweb/language/field.py +++ b/src/lionweb/language/field.py @@ -41,8 +41,9 @@ def __init__( def get_name(self) -> str | None: return cast(str | None, self.get_property_value(property="name")) - def set_name(self, name: str | None): + def set_name(self, name: str | None) -> "Field": self.set_property_value(property="name", value=name) + return self def get_container(self) -> NamespaceProvider | None: """ @@ -64,7 +65,7 @@ def get_classifier(self) -> "Concept": def get_type(self) -> DataType | None: return cast(DataType | None, self.get_reference_single_value("type")) - def set_type(self, type: DataType | None): + def set_type(self, type: DataType | None) -> None: if type is None: self.set_reference_single_value("type", None) else: diff --git a/src/lionweb/language/ikeyed.py b/src/lionweb/language/ikeyed.py index 841cc68..1f4b1f3 100644 --- a/src/lionweb/language/ikeyed.py +++ b/src/lionweb/language/ikeyed.py @@ -5,10 +5,25 @@ class IKeyed(Generic[T], ABC): + """Interface for entities identified by a stable, unique key (in addition to an id).""" + @abstractmethod def get_key(self) -> str: + """Return the key of this entity. + + Returns: + str: The key. + """ pass @abstractmethod def set_key(self, value: str) -> T: + """Set the key of this entity. + + Args: + value: The new key. + + Returns: + T: This entity, to allow fluent chaining. + """ pass diff --git a/src/lionweb/language/inamed.py b/src/lionweb/language/inamed.py index 9dfd88e..97701dc 100644 --- a/src/lionweb/language/inamed.py +++ b/src/lionweb/language/inamed.py @@ -2,6 +2,9 @@ class INamed(ABC): + """Interface for entities that have a (possibly absent) name.""" + @abstractmethod def get_name(self) -> str | None: + """Return the name of this entity, or ``None`` if it has none.""" pass diff --git a/src/lionweb/language/interface.py b/src/lionweb/language/interface.py index cd87a2f..31de1cc 100644 --- a/src/lionweb/language/interface.py +++ b/src/lionweb/language/interface.py @@ -5,6 +5,9 @@ class Interface(Classifier["Interface"]): + """A classifier that declares features to be implemented/inherited by concepts and other + interfaces, without being directly instantiable.""" + if TYPE_CHECKING: from lionweb.language.concept import Concept from lionweb.language.feature import Feature @@ -39,7 +42,15 @@ def get_extended_interfaces(self) -> list["Interface"]: def extended_interfaces(self) -> list["Interface"]: return self.get_extended_interfaces() - def add_extended_interface(self, extended_interface: "Interface"): + def add_extended_interface(self, extended_interface: "Interface") -> None: + """Add an interface to the list of interfaces this interface extends. + + Args: + extended_interface: The interface to extend. + + Raises: + ValueError: If ``extended_interface`` is ``None``. + """ if not extended_interface: raise ValueError("extended_interface should not be null") @@ -64,6 +75,11 @@ def direct_ancestors(self) -> list[Classifier]: return list(itertools.chain(self.get_extended_interfaces())) def all_extended_interfaces(self) -> set["Interface"]: + """Compute the transitive closure of all interfaces extended by this interface (cycle-safe). + + Returns: + set[Interface]: All directly and indirectly extended interfaces. + """ to_avoid = {self} return self._all_extended_interfaces_helper(to_avoid) diff --git a/src/lionweb/language/language.py b/src/lionweb/language/language.py index 3c78476..cd48e8e 100644 --- a/src/lionweb/language/language.py +++ b/src/lionweb/language/language.py @@ -8,7 +8,19 @@ T = TypeVar("T", bound=M3Node) +class WrongElementTypeError(RuntimeError): + """Raised when a language element is found by name but has a different type than expected.""" + + def __init__(self, element_name: str, expected_type: type): + super().__init__(f"Element {element_name} is not a {expected_type.__name__}") + self.element_name = element_name + self.expected_type = expected_type + + class Language(M3Node["Language"], NamespaceProvider, IKeyed["Language"]): + """A LionWeb Language: a named, versioned collection of language entities + (concepts, interfaces, annotations, data types) and their dependencies.""" + if TYPE_CHECKING: from lionweb.language.annotation import Annotation from lionweb.language.classifier import Classifier @@ -96,6 +108,14 @@ def add_dependency(self, dependency: "Language") -> "Language": return dependency def add_element(self, element: T) -> T: + """Add a language entity to this language and set its parent. + + Args: + element: The language entity to add. + + Returns: + T: The added element (for convenient chaining). + """ self.add_containment_multiple_value("entities", element) element.set_parent(self) return element @@ -193,7 +213,7 @@ def get_primitive_type_by_name(self, name: str) -> Optional["PrimitiveType"]: if isinstance(element, PrimitiveType): return element elif element: - raise RuntimeError(f"Element {name} is not a PrimitiveType") + raise WrongElementTypeError(name, PrimitiveType) return None def get_data_type_by_name(self, name: str) -> Optional["DataType"]: @@ -203,7 +223,7 @@ def get_data_type_by_name(self, name: str) -> Optional["DataType"]: if isinstance(element, DataType): return element elif element: - raise RuntimeError(f"Element {name} is not a DataType") + raise WrongElementTypeError(name, DataType) return None def get_classifier(self) -> "Concept": diff --git a/src/lionweb/language/language_entity.py b/src/lionweb/language/language_entity.py index 8873d87..325517b 100644 --- a/src/lionweb/language/language_entity.py +++ b/src/lionweb/language/language_entity.py @@ -12,6 +12,8 @@ class LanguageEntity(M3Node[T], NamespacedEntity, IKeyed[T]): + """Base class for the top-level entities declared in a Language (classifiers, data types).""" + def __init__( self, lion_web_version: Optional["LionWebVersion"] = None, diff --git a/src/lionweb/language/link.py b/src/lionweb/language/link.py index 2d12720..3b34725 100644 --- a/src/lionweb/language/link.py +++ b/src/lionweb/language/link.py @@ -8,6 +8,9 @@ class Link(Feature[T]): + """Base class for features that relate a classifier to instances of other classifiers + (containments and references).""" + if TYPE_CHECKING: from lionweb.language.classifier import Classifier diff --git a/src/lionweb/language/lioncore_builtins.py b/src/lionweb/language/lioncore_builtins.py index 02dfc60..d4ef12b 100644 --- a/src/lionweb/language/lioncore_builtins.py +++ b/src/lionweb/language/lioncore_builtins.py @@ -5,6 +5,12 @@ class LionCoreBuiltins(Language): + """The built-in LionCore language, providing the base primitive types (String, Boolean, + Integer, optionally JSON), the ``Node`` concept, and the ``INamed`` interface. + + Instances are cached per :class:`LionWebVersion` and obtained via :meth:`get_instance`. + """ + if TYPE_CHECKING: from lionweb.language.concept import Concept from lionweb.language.interface import Interface diff --git a/src/lionweb/language/namespace_provider.py b/src/lionweb/language/namespace_provider.py index 8cc8f98..d35e2f6 100644 --- a/src/lionweb/language/namespace_provider.py +++ b/src/lionweb/language/namespace_provider.py @@ -10,4 +10,9 @@ class NamespaceProvider(ABC): @abstractmethod def namespace_qualifier(self) -> str: + """Return the qualifier prefix to use to build qualified names of contained entities. + + Returns: + str: The namespace qualifier string. + """ pass diff --git a/src/lionweb/language/namespaced_entity.py b/src/lionweb/language/namespaced_entity.py index ea539b4..d044162 100644 --- a/src/lionweb/language/namespaced_entity.py +++ b/src/lionweb/language/namespaced_entity.py @@ -17,13 +17,21 @@ def get_name(self) -> str | None: pass def qualified_name(self) -> str: + """Compute the fully qualified name of this entity. + + Returns: + str: The container's namespace qualifier joined with this entity's name. + + Raises: + ValueError: If this entity has no container or no name. + """ container = self.get_container() name = self.get_name() if container is None: - raise ValueError("No container for " + str(self)) + raise ValueError(f"No container for {self}") if name is None: - raise ValueError("No name for " + str(self)) - return container.namespace_qualifier() + "." + name + raise ValueError(f"No name for {self}") + return f"{container.namespace_qualifier()}.{name}" @abstractmethod def get_container(self) -> NamespaceProvider | None: diff --git a/src/lionweb/language/primitive_type.py b/src/lionweb/language/primitive_type.py index dc82b3b..6d58692 100644 --- a/src/lionweb/language/primitive_type.py +++ b/src/lionweb/language/primitive_type.py @@ -9,6 +9,8 @@ class PrimitiveType(DataType): + """A data type whose values are not further decomposed (e.g. String, Integer, Boolean).""" + def __init__( self, lion_web_version: LionWebVersion = LionWebVersion.current_version(), diff --git a/src/lionweb/language/property.py b/src/lionweb/language/property.py index cd044fe..f6956ec 100644 --- a/src/lionweb/language/property.py +++ b/src/lionweb/language/property.py @@ -5,6 +5,8 @@ class Property(Feature["Property"]): + """A feature holding a single value of a given data type for instances of a classifier.""" + if TYPE_CHECKING: from lionweb.language.classifier import Classifier from lionweb.language.concept import Concept diff --git a/src/lionweb/language/reference.py b/src/lionweb/language/reference.py index 8252ab7..bbf3c73 100644 --- a/src/lionweb/language/reference.py +++ b/src/lionweb/language/reference.py @@ -4,6 +4,8 @@ class Reference(Link["Reference"]): + """A link expressing a non-containing (cross) relationship between classifiers.""" + if TYPE_CHECKING: from lionweb.language.classifier import Classifier from lionweb.language.concept import Concept diff --git a/src/lionweb/language/structured_data_type.py b/src/lionweb/language/structured_data_type.py index 0628538..20f01ab 100644 --- a/src/lionweb/language/structured_data_type.py +++ b/src/lionweb/language/structured_data_type.py @@ -34,6 +34,17 @@ def __init__( self.set_key(key) def add_field(self, field: "Field") -> "StructuredDataType": + """Add a field to this structured data type. + + Args: + field: The field to add. + + Returns: + StructuredDataType: This structured data type, to allow fluent chaining. + + Raises: + ValueError: If ``field`` is ``None``. + """ if field is None: raise ValueError("field should not be null") self.add_containment_multiple_value("fields", field) @@ -41,6 +52,7 @@ def add_field(self, field: "Field") -> "StructuredDataType": return self def get_fields(self) -> list["Field"]: + """Return the fields declared on this structured data type.""" return self.get_containment_multiple_value("fields") def namespace_qualifier(self) -> str: @@ -52,6 +64,17 @@ def get_classifier(self) -> "Concept": return LionCore.get_structured_data_type(self.get_lionweb_version()) def get_field_by_name(self, field_name: str) -> Optional["Field"]: + """Look up a field by its name. + + Args: + field_name: The name of the field to find. + + Returns: + Optional[Field]: The matching field, or ``None`` if none is found. + + Raises: + ValueError: If ``field_name`` is ``None``. + """ if field_name is None: raise ValueError("fieldName should not be null") return next((f for f in self.get_fields() if f.get_name() == field_name), None) diff --git a/src/lionweb/model/__init__.py b/src/lionweb/model/__init__.py index 3bbc517..e537eb1 100644 --- a/src/lionweb/model/__init__.py +++ b/src/lionweb/model/__init__.py @@ -3,3 +3,11 @@ from .impl.dynamic_node import DynamicNode as DynamicNode from .node import Node as Node from .reference_value import ReferenceValue as ReferenceValue + +__all__ = [ + "ClassifierInstance", + "get_root", + "DynamicNode", + "Node", + "ReferenceValue", +] diff --git a/src/lionweb/model/annotation_instance.py b/src/lionweb/model/annotation_instance.py index 89038d1..f5e9184 100644 --- a/src/lionweb/model/annotation_instance.py +++ b/src/lionweb/model/annotation_instance.py @@ -14,7 +14,17 @@ class AnnotationInstance(ClassifierInstance, ABC): @abstractmethod def get_annotation_definition(self) -> "Annotation": + """Returns the Annotation this instance is an instance of. + + Returns: + Annotation: The annotation definition for this instance. + """ pass def get_classifier(self) -> "Annotation": + """Returns the classifier of this instance, i.e. its annotation definition. + + Returns: + Annotation: The annotation definition for this instance. + """ return self.get_annotation_definition() diff --git a/src/lionweb/model/classifier_instance.py b/src/lionweb/model/classifier_instance.py index 1af797f..c313ea7 100644 --- a/src/lionweb/model/classifier_instance.py +++ b/src/lionweb/model/classifier_instance.py @@ -8,6 +8,13 @@ class ClassifierInstance(Generic[T], HasFeatureValues, ABC): + """An instance of a Classifier (a Concept or an Annotation). + + This is the base abstraction shared by Nodes and AnnotationInstances: it + provides access to the id, the classifier, the parent, the annotations and + the feature values (inherited from :class:`HasFeatureValues`). + """ + if TYPE_CHECKING: from lionweb.language.annotation import Annotation from lionweb.language.classifier import Classifier @@ -48,9 +55,17 @@ def collect_self_and_descendants( self: "ClassifierInstance", include_annotations: bool, result: Collection["ClassifierInstance"], - ): - """ - Collects `self` and all its descendants into `result`. + ) -> None: + """Collects `self` and all its descendants into `result`. + + Args: + self: The classifier instance to start the collection from. + include_annotations: Whether annotations should also be visited and collected. + result: A mutable collection (list or set) into which the instances are added. + + Raises: + ValueError: If `self` is not a ClassifierInstance, or `result` is neither + a list nor a set. """ if not isinstance(self, ClassifierInstance): raise ValueError(f"Expecting a ClassifierInstance but got {self}") @@ -59,7 +74,7 @@ def collect_self_and_descendants( elif isinstance(result, set): result.add(self) else: - raise ValueError() + raise ValueError(f"Unsupported result collection type: {type(result).__name__}") if include_annotations: for annotation in self.get_annotations(): ClassifierInstance.collect_self_and_descendants( @@ -68,5 +83,5 @@ def collect_self_and_descendants( for child in self.get_children(): ClassifierInstance.collect_self_and_descendants(child, include_annotations, result) - def __hash__(self): + def __hash__(self) -> int: return hash(self.id) diff --git a/src/lionweb/model/classifier_instance_utils.py b/src/lionweb/model/classifier_instance_utils.py index b2cef6d..45b4d94 100644 --- a/src/lionweb/model/classifier_instance_utils.py +++ b/src/lionweb/model/classifier_instance_utils.py @@ -14,6 +14,18 @@ def get_property_value_by_name(instance: "ClassifierInstance", property_name: str) -> object | None: + """Returns the value of the property with the given name on the given instance. + + Args: + instance: The classifier instance to query. + property_name: The name of the property to look up. + + Returns: + The value of the property, or None. + + Raises: + ValueError: If the classifier does not have a property with that name. + """ property_ = instance.get_classifier().get_property_by_name(property_name=property_name) if property_ is None: raise ValueError( @@ -25,6 +37,16 @@ def get_property_value_by_name(instance: "ClassifierInstance", property_name: st def set_property_value_by_name( instance: "ClassifierInstance", property_name: str, value: object | None ) -> None: + """Sets the value of the property with the given name on the given instance. + + Args: + instance: The classifier instance to modify. + property_name: The name of the property to set. + value: The value to assign to the property. + + Raises: + ValueError: If the classifier is None or does not have a property with that name. + """ classifier = instance.get_classifier() if classifier is None: raise ValueError(f"Classifier should not be null for {instance}") @@ -37,6 +59,14 @@ def set_property_value_by_name( def get_children(instance: "ClassifierInstance") -> list["Node"]: + """Returns all children of the given instance, across all its containments. + + Args: + instance: The classifier instance whose children should be collected. + + Returns: + A list of all child nodes. + """ all_children = [] for containment in instance.get_classifier().all_containments(): all_children.extend(instance.get_children(containment)) @@ -46,6 +76,16 @@ def get_children(instance: "ClassifierInstance") -> list["Node"]: def get_referred_nodes( instance: "ClassifierInstance", reference: Optional["Reference"] = None ) -> list["ClassifierInstance"]: + """Returns the nodes referred to by the given instance through the given reference + (or all references, if None is given), excluding unresolved reference values. + + Args: + instance: The classifier instance to query. + reference: The reference to consider, or None to consider all references. + + Returns: + A list of the resolved referred classifier instances. + """ return [ e for e in [rv.get_referred() for rv in get_reference_values(instance, reference)] @@ -56,6 +96,16 @@ def get_referred_nodes( def get_reference_values( instance: "ClassifierInstance", reference: Optional["Reference"] = None ) -> list["ReferenceValue"]: + """Returns the reference values held by the given instance for the given reference + (or for all references, if None is given). + + Args: + instance: The classifier instance to query. + reference: The reference to consider, or None to consider all references. + + Returns: + A list of reference values. + """ if reference is None: all_referred_values = [] for reference in instance.get_classifier().all_references(): @@ -66,6 +116,16 @@ def get_reference_values( def reference_to(entity: "LanguageEntity") -> "ReferenceValue": + """Builds a ReferenceValue pointing to the given language entity, computing an + appropriate `resolve_info` (using auto-resolve prefixes for LionCore_M3 / builtins + entities when applicable). + + Args: + entity: The language entity to build a reference to. + + Returns: + A ReferenceValue referring to the given entity. + """ language = entity.language from lionweb.language.lioncore_builtins import LionCoreBuiltins from lionweb.lionweb_version import LionWebVersion @@ -96,6 +156,14 @@ def reference_to(entity: "LanguageEntity") -> "ReferenceValue": def is_builtin_element(entity: "Node") -> bool: + """Checks whether the given node is a builtin element of LionCore_M3 or LionCoreBuiltins. + + Args: + entity: The node to check. + + Returns: + True if the entity is a LanguageEntity that is a builtin element, False otherwise. + """ from lionweb.language.language_entity import LanguageEntity if isinstance(entity, LanguageEntity): @@ -104,6 +172,15 @@ def is_builtin_element(entity: "Node") -> bool: def is_builtin_element_language_entity(entity: "LanguageEntity") -> bool: + """Checks whether the given language entity is a builtin element of + LionCore_M3 or LionCoreBuiltins (for the LionWeb 2024.1 version). + + Args: + entity: The language entity to check. + + Returns: + True if the entity is a builtin element, False otherwise. + """ language = entity.language from lionweb.language.lioncore_builtins import LionCoreBuiltins from lionweb.lionweb_version import LionWebVersion @@ -126,6 +203,20 @@ def is_builtin_element_language_entity(entity: "LanguageEntity") -> bool: def get_reference_value_by_name( instance: "ClassifierInstance", reference_name: str ) -> list["ReferenceValue"]: + """Returns the reference values held by the given instance for the reference + with the given name. + + Args: + instance: The classifier instance to query. + reference_name: The name of the reference to look up. + + Returns: + A list of reference values. + + Raises: + ValueError: If `instance` or `reference_name` is None, the classifier is + None, or the classifier does not have a reference with that name. + """ if instance is None: raise ValueError("_this should not be null") if reference_name is None: @@ -149,6 +240,20 @@ def get_reference_value_by_name( def get_only_reference_value_by_reference_name( instance, reference_name: str ) -> Optional["ReferenceValue"]: + """Returns the single reference value held by the given instance for the + reference with the given name, or None if there is none. + + Args: + instance: The classifier instance to query. + reference_name: The name of the reference to look up. + + Returns: + The single reference value found, or None if there is none. + + Raises: + ValueError: If `instance` or `reference_name` is None. + RuntimeError: If more than one reference value is found. + """ if instance is None: raise ValueError("_this should not be null") if reference_name is None: @@ -164,6 +269,20 @@ def get_only_reference_value_by_reference_name( def get_only_child_by_reference_name(instance, containment_name: str) -> Optional["Node"]: + """Returns the single child held by the given instance for the containment + with the given name, or None if there is none. + + Args: + instance: The classifier instance to query. + containment_name: The name of the containment to look up. + + Returns: + The single child found, or None if there is none. + + Raises: + ValueError: If `instance` or `containment_name` is None. + RuntimeError: If more than one child is found. + """ if instance is None: raise ValueError("_this should not be null") if containment_name is None: @@ -179,6 +298,17 @@ def get_only_child_by_reference_name(instance, containment_name: str) -> Optiona def get_root(nodes: list["Node"]) -> "Node": + """Returns the single root among the given nodes (i.e. the node without a parent). + + Args: + nodes: The list of nodes to search. + + Returns: + The single root node found. + + Raises: + ValueError: If `nodes` is empty, or if there isn't exactly one root. + """ if len(nodes) == 0: raise ValueError("No nodes found") roots = [n for n in nodes if n.get_parent() is None] diff --git a/src/lionweb/model/has_feature_values.py b/src/lionweb/model/has_feature_values.py index 51a206e..c7c7f76 100644 --- a/src/lionweb/model/has_feature_values.py +++ b/src/lionweb/model/has_feature_values.py @@ -3,6 +3,10 @@ class HasFeatureValues(ABC): + """Interface for objects exposing property, containment, and reference values + associated with the features of their classifier. + """ + if TYPE_CHECKING: from lionweb.language import Containment, Property, Reference from lionweb.model import Node, ReferenceValue diff --git a/src/lionweb/model/has_settable_parent.py b/src/lionweb/model/has_settable_parent.py index db5a046..da73aa0 100644 --- a/src/lionweb/model/has_settable_parent.py +++ b/src/lionweb/model/has_settable_parent.py @@ -4,5 +4,13 @@ class HasSettableParent(ABC): + """Mixin for classifier instances whose parent can be changed after creation.""" + @abstractmethod - def set_parent(self, parent: ClassifierInstance | None) -> None: ... + def set_parent(self, parent: ClassifierInstance | None) -> None: + """Sets the parent of this instance. + + Args: + parent: The new parent, or None to detach this instance from its parent. + """ + ... diff --git a/src/lionweb/model/impl/abstract_classifier_instance.py b/src/lionweb/model/impl/abstract_classifier_instance.py index 13f50a6..278adf5 100644 --- a/src/lionweb/model/impl/abstract_classifier_instance.py +++ b/src/lionweb/model/impl/abstract_classifier_instance.py @@ -7,6 +7,10 @@ class AbstractClassifierInstance(Generic[T], ClassifierInstance[T], ABC): + """Base implementation of ClassifierInstance providing common annotation, + containment, and reference management logic shared by concrete instances. + """ + if TYPE_CHECKING: from lionweb.language.annotation import Annotation from lionweb.language.containment import Containment @@ -16,7 +20,7 @@ class AbstractClassifierInstance(Generic[T], ClassifierInstance[T], ABC): from lionweb.model.impl.dynamic_annotation_instance import DynamicAnnotationInstance from lionweb.model.reference_value import ReferenceValue - def __init__(self): + def __init__(self) -> None: from lionweb.model.annotation_instance import AnnotationInstance self.annotations: list[AnnotationInstance] = [] diff --git a/src/lionweb/model/impl/dynamic_annotation_instance.py b/src/lionweb/model/impl/dynamic_annotation_instance.py index 8b9a74e..518ff16 100644 --- a/src/lionweb/model/impl/dynamic_annotation_instance.py +++ b/src/lionweb/model/impl/dynamic_annotation_instance.py @@ -10,6 +10,10 @@ class DynamicAnnotationInstance(DynamicClassifierInstance, AnnotationInstance): + """A generic, reflective implementation of AnnotationInstance backed by a + DynamicClassifierInstance, suitable for any Annotation definition. + """ + def __init__( self, id: str, @@ -26,10 +30,10 @@ def __init__( def get_id(self) -> str | None: return self._id - def set_annotation(self, annotation: "Annotation"): + def set_annotation(self, annotation: "Annotation") -> None: self.annotation = annotation - def set_annotated(self, annotated: ClassifierInstance | None): + def set_annotated(self, annotated: ClassifierInstance | None) -> None: from lionweb.model.impl.dynamic_node import DynamicNode if annotated == self.annotated: diff --git a/src/lionweb/model/impl/dynamic_classifier_instance.py b/src/lionweb/model/impl/dynamic_classifier_instance.py index f03f639..af25703 100644 --- a/src/lionweb/model/impl/dynamic_classifier_instance.py +++ b/src/lionweb/model/impl/dynamic_classifier_instance.py @@ -12,6 +12,24 @@ from lionweb.language import Property +class FeatureNotInClassifierError(ValueError): + """Raised when a feature (property, containment, or reference) does not belong + to the classifier of the instance it is being used on. + + Args: + feature: The feature that does not belong to the classifier. + classifier_instance: The instance whose classifier does not declare the feature. + """ + + def __init__(self, feature, classifier_instance): + super().__init__( + f"{feature} does not belong to the classifier of {classifier_instance} " + f"(class {type(classifier_instance).__name__})" + ) + self.feature = feature + self.classifier_instance = classifier_instance + + class DynamicClassifierInstance(AbstractClassifierInstance, ClassifierInstance): """DynamicClassifierInstance can represent any instance of a Classifier. It allows flexible property, containment, and reference management. @@ -27,7 +45,7 @@ def __init__(self): def get_id(self) -> str | None: return self._id - def set_id(self, id: str | None): + def set_id(self, id: str | None) -> None: self._id = id # Public methods for properties @@ -50,7 +68,7 @@ def get_property_value(self, property: Union[str, "Property"]) -> object | None: if property.key is None: raise ValueError("Property.key should not be null") if property not in self.get_classifier().all_properties(): - raise ValueError("Property not belonging to this classifier") + raise FeatureNotInClassifierError(property, self) stored_value = self.property_values.get(property.key) @@ -108,11 +126,11 @@ def get_children(self, containment: Containment | str | None = None) -> list[Nod if my_containment.get_key() is None: raise ValueError("Containment.key should not be null") if my_containment not in self.get_classifier().all_containments(): - raise ValueError("Containment not belonging to this concept") + raise FeatureNotInClassifierError(my_containment, self) return self.containment_values.get(my_containment.get_key(), []) - def add_child(self, containment: Containment | str, child: Node): + def add_child(self, containment: Containment | str, child: Node) -> None: if containment is None or child is None: raise ValueError("Containment and child should not be null") my_containment: Containment | None @@ -138,13 +156,13 @@ def remove_child(self, **kwargs) -> None: return raise ValueError("The given node is not a child of this node") - def remove_child_by_index(self, containment: Containment, index: int): + def remove_child_by_index(self, containment: Containment, index: int) -> None: if containment is None: raise ValueError("Containment should not be null") if containment.get_key() is None: raise ValueError("Containment.key should not be null") if containment not in self.get_classifier().all_containments(): - raise ValueError("Containment not belonging to this concept") + raise FeatureNotInClassifierError(containment, self) children = self.containment_values.get(containment.get_key(), []) if len(children) > index: @@ -160,11 +178,11 @@ def get_reference_values(self, reference: Reference) -> list[ReferenceValue]: if reference.get_key() is None: raise ValueError("Reference.key should not be null") if reference not in self.get_classifier().all_references(): - raise ValueError("Reference not belonging to this concept") + raise FeatureNotInClassifierError(reference, self) return self.reference_values.get(reference.get_key(), []) - def add_reference_value(self, reference: Reference, value: ReferenceValue | None): + def add_reference_value(self, reference: Reference, value: ReferenceValue | None) -> None: if reference is None: raise ValueError("Reference should not be null") if reference.is_multiple(): @@ -173,13 +191,15 @@ def add_reference_value(self, reference: Reference, value: ReferenceValue | None else: self._set_reference_single_value(reference, value) - def remove_reference_value(self, reference: Reference, reference_value: ReferenceValue | None): + def remove_reference_value( + self, reference: Reference, reference_value: ReferenceValue | None + ) -> None: if reference is None: raise ValueError("Reference should not be null") if reference.get_key() is None: raise ValueError("Reference.key should not be null") if reference not in self.get_classifier().all_references(): - raise ValueError("Reference not belonging to this concept") + raise FeatureNotInClassifierError(reference, self) reference_values = self.reference_values.get(reference.get_key(), []) for i, rv in enumerate(reference_values): @@ -193,13 +213,13 @@ def remove_reference_value(self, reference: Reference, reference_value: Referenc f"The given reference value could not be found under reference {reference.get_name()}" ) - def remove_reference_value_by_index(self, reference: Reference, index: int): + def remove_reference_value_by_index(self, reference: Reference, index: int) -> None: if reference is None: raise ValueError("Reference should not be null") if reference.get_key() is None: raise ValueError("Reference.key should not be null") if reference not in self.get_classifier().all_references(): - raise ValueError("Reference not belonging to this classifier") + raise FeatureNotInClassifierError(reference, self) reference_values = self.reference_values.get(reference.get_key(), []) if len(reference_values) > index: @@ -209,25 +229,25 @@ def remove_reference_value_by_index(self, reference: Reference, index: int): f"Invalid index {index} when reference values are {len(reference_values)}" ) - def set_reference_values(self, reference: Reference, values: list[ReferenceValue]): + def set_reference_values(self, reference: Reference, values: list[ReferenceValue]) -> None: if reference is None: raise ValueError("Reference should not be null") if reference.get_key() is None: raise ValueError("Reference.key should not be null") if reference not in self.get_classifier().all_references(): - raise ValueError("Reference not belonging to this classifier") + raise FeatureNotInClassifierError(reference, self) self.reference_values[reference.get_key()] = values # Private methods for containments - def _add_containment(self, containment: Containment, value: Node): + def _add_containment(self, containment: Containment, value: Node) -> None: assert containment.is_multiple() if isinstance(value, HasSettableParent): value.set_parent(self) self.containment_values.setdefault(containment.get_key(), []).append(value) - def _set_containment_single_value(self, containment: Containment, value: Node | None): + def _set_containment_single_value(self, containment: Containment, value: Node | None) -> None: prev_value = self.containment_values.get(containment.get_key()) if prev_value: for child in list(prev_value): @@ -242,13 +262,17 @@ def _set_containment_single_value(self, containment: Containment, value: Node | # Private methods for references - def _set_reference_single_value(self, reference: Reference, value: ReferenceValue | None): + def _set_reference_single_value( + self, reference: Reference, value: ReferenceValue | None + ) -> None: if value is None: self.reference_values.pop(reference.get_key(), None) else: self.reference_values[reference.get_key()] = [value] - def _add_reference_multiple_value(self, reference: Reference, reference_value: ReferenceValue): + def _add_reference_multiple_value( + self, reference: Reference, reference_value: ReferenceValue + ) -> None: assert reference.is_multiple() if reference_value is not None: self.reference_values.setdefault(reference.get_key(), []).append(reference_value) diff --git a/src/lionweb/model/impl/dynamic_node.py b/src/lionweb/model/impl/dynamic_node.py index 8e3b4f7..ba6b40f 100644 --- a/src/lionweb/model/impl/dynamic_node.py +++ b/src/lionweb/model/impl/dynamic_node.py @@ -10,8 +10,25 @@ from lionweb.model.node import Node +class ContainmentFeatureNotFoundError(RuntimeError): + """Raised when the containment feature used to hold a node within its parent + cannot be located among the parent's containments. + + Args: + node: The node whose containment feature could not be found. + """ + + def __init__(self, node: Node): + super().__init__("Unable to find the containment feature") + self.node = node + + class DynamicNode(DynamicClassifierInstance, Node, HasSettableParent): - def __init__(self, id: str | None = None, concept: Optional["Concept"] = None): + """A generic, reflective implementation of Node backed by a + DynamicClassifierInstance, suitable for any Concept definition. + """ + + def __init__(self, id: str | None = None, concept: Optional["Concept"] = None) -> None: self._id = id self.concept = concept self.parent: Node | None = None @@ -27,7 +44,7 @@ def __init__(self, id: str | None = None, concept: Optional["Concept"] = None): def get_id(self) -> str | None: return self._id - def set_concept(self, concept: "Concept"): + def set_concept(self, concept: "Concept") -> None: self.concept = concept def get_parent(self) -> Node | None: @@ -44,9 +61,9 @@ def get_containment_feature(self) -> Containment | None: for containment in self.parent.get_classifier().all_containments(): if any(child == self for child in self.parent.get_children(containment)): return containment - raise RuntimeError("Unable to find the containment feature") + raise ContainmentFeatureNotFoundError(self) - def set_parent(self, parent: Optional["ClassifierInstance"]): + def set_parent(self, parent: Optional["ClassifierInstance"]) -> None: self.parent = cast(Node | None, parent) def __eq__(self, other): diff --git a/src/lionweb/model/impl/dynamic_structured_datype_instance.py b/src/lionweb/model/impl/dynamic_structured_datype_instance.py index df83bbb..b8c6c4e 100644 --- a/src/lionweb/model/impl/dynamic_structured_datype_instance.py +++ b/src/lionweb/model/impl/dynamic_structured_datype_instance.py @@ -5,6 +5,10 @@ class DynamicStructuredDataTypeInstance: + """A generic, reflective implementation of StructuredDataTypeInstance that stores + field values in a dictionary keyed by Field, suitable for any StructuredDataType. + """ + def __init__(self, structured_data_type: StructuredDataType): if structured_data_type is None: raise ValueError("structuredDataType should not be null") @@ -23,7 +27,7 @@ def get_field_value(self, field: Field) -> Any: raise ValueError(f"Invalid field for StructuredDataType {self.structured_data_type}") return self.field_values.get(field) - def set_field_value(self, field: Field | str, value: Any): + def set_field_value(self, field: Field | str, value: Any) -> None: if field is None: raise ValueError("Field should not be null") my_field: Field diff --git a/src/lionweb/model/impl/m3node.py b/src/lionweb/model/impl/m3node.py index 151475c..0b10055 100644 --- a/src/lionweb/model/impl/m3node.py +++ b/src/lionweb/model/impl/m3node.py @@ -10,6 +10,12 @@ class M3Node(Generic[T], Node, IKeyed[T], AbstractClassifierInstance, ABC): + """Base class for all M3 (metamodel) nodes, such as Concepts, Properties, + Containments, and References. Provides a fluent, reflective implementation + of Node backed by simple dictionaries for property, containment, and + reference values. + """ + if TYPE_CHECKING: from lionweb.language.containment import Containment from lionweb.language.property import Property @@ -17,7 +23,7 @@ class M3Node(Generic[T], Node, IKeyed[T], AbstractClassifierInstance, ABC): from lionweb.model.classifier_instance import ClassifierInstance from lionweb.model.reference_value import ReferenceValue - def __init__(self, lion_web_version: LionWebVersion | None = None): + def __init__(self, lion_web_version: LionWebVersion | None = None) -> None: AbstractClassifierInstance.__init__(self) if lion_web_version is not None and not isinstance(lion_web_version, LionWebVersion): raise ValueError( @@ -41,7 +47,7 @@ def id(self) -> str | None: return self._id @id.setter - def id(self, new_value): + def id(self, new_value: str | None) -> None: self._id = new_value def set_name(self, name: str | None) -> "M3Node": @@ -196,5 +202,5 @@ def add_reference_multiple_value(self, link_name: str, value: "ReferenceValue") def get_lionweb_version(self) -> LionWebVersion: return self.lion_web_version - def __hash__(self): + def __hash__(self) -> int: return hash(self.id) diff --git a/src/lionweb/model/impl/proxy_node.py b/src/lionweb/model/impl/proxy_node.py index a1fc804..d2c86e7 100644 --- a/src/lionweb/model/impl/proxy_node.py +++ b/src/lionweb/model/impl/proxy_node.py @@ -14,13 +14,16 @@ class ProxyNode(Node): retrieve the data necessary to properly instantiate it. """ - def add_annotation(self, instance: "AnnotationInstance") -> None: - raise self.CannotDoBecauseProxyException(self.id) + class CannotDoBecauseProxyException(Exception): + """Raised when an operation is attempted on a ProxyNode. - def remove_annotation(self, instance: "AnnotationInstance") -> None: - raise self.CannotDoBecauseProxyException(self.id) + A ProxyNode only holds an ID and cannot support any of the regular Node + operations; the proxy must be replaced with a real node first. + + Args: + node_id: The ID of the proxy node on which the operation was attempted. + """ - class CannotDoBecauseProxyException(Exception): def __init__(self, node_id: str | None): super().__init__( f"Replace the proxy node with a real node to perform this operation (nodeID: {node_id})" @@ -32,7 +35,13 @@ def __init__(self, node_id: str): raise ValueError("The node ID of a ProxyNode should not be null") self._id = node_id - def get_parent(self): + def add_annotation(self, instance: "AnnotationInstance") -> None: + raise self.CannotDoBecauseProxyException(self.id) + + def remove_annotation(self, instance: "AnnotationInstance") -> None: + raise self.CannotDoBecauseProxyException(self.id) + + def get_parent(self) -> Optional["Node"]: raise self.CannotDoBecauseProxyException(self.id) def get_property_value(self, property): diff --git a/src/lionweb/model/node.py b/src/lionweb/model/node.py index 28a318c..21c702f 100644 --- a/src/lionweb/model/node.py +++ b/src/lionweb/model/node.py @@ -72,6 +72,18 @@ def _shallow_annotations_equality(annotations1: list, annotations2: list) -> boo ) +class CircularHierarchyError(RuntimeError): + """Raised when a node is found to be its own ancestor while walking up the parent chain. + + Args: + node: The node at which the circularity was detected. + """ + + def __init__(self, node: "Node"): + super().__init__("A circular hierarchy has been identified") + self.node = node + + class Node(ClassifierInstance["Concept"], ABC): """ A node is an instance of a Concept. It contains all the values associated with that instance. @@ -110,7 +122,7 @@ def get_root(self) -> "Node": ancestors.append(curr) curr = curr.get_parent() else: - raise RuntimeError("A circular hierarchy has been identified") + raise CircularHierarchyError(curr) return ancestors[-1] def is_root(self) -> bool: diff --git a/src/lionweb/model/reference_value.py b/src/lionweb/model/reference_value.py index 9a7cc3a..7c1164d 100644 --- a/src/lionweb/model/reference_value.py +++ b/src/lionweb/model/reference_value.py @@ -1,14 +1,20 @@ +from dataclasses import dataclass + from lionweb.model import ClassifierInstance +@dataclass(eq=False) class ReferenceValue: - def __init__( - self, - referred: ClassifierInstance | None = None, - resolve_info: str | None = None, - ): - self.referred = referred - self.resolve_info = resolve_info + """A value held by a Reference, pointing to a referred node and/or carrying + a human-readable resolve info string used to help resolve the reference. + + Attributes: + referred: The node being referred to, if resolved. + resolve_info: A human-readable string that can help resolve the reference. + """ + + referred: ClassifierInstance | None = None + resolve_info: str | None = None def get_referred(self) -> ClassifierInstance | None: return self.referred @@ -16,13 +22,13 @@ def get_referred(self) -> ClassifierInstance | None: def get_referred_id(self) -> str | None: return self.referred.id if self.referred else None - def set_referred(self, referred: ClassifierInstance | None): + def set_referred(self, referred: ClassifierInstance | None) -> None: self.referred = referred def get_resolve_info(self) -> str | None: return self.resolve_info - def set_resolve_info(self, resolve_info: str | None): + def set_resolve_info(self, resolve_info: str | None) -> None: self.resolve_info = resolve_info def __eq__(self, other): diff --git a/src/lionweb/presentation/__init__.py b/src/lionweb/presentation/__init__.py index e69de29..3ac37ea 100644 --- a/src/lionweb/presentation/__init__.py +++ b/src/lionweb/presentation/__init__.py @@ -0,0 +1,3 @@ +from .show_nodes import display_node as display_node + +__all__ = ["display_node"] diff --git a/src/lionweb/presentation/show_nodes.py b/src/lionweb/presentation/show_nodes.py index 6ffc5bd..75714fe 100644 --- a/src/lionweb/presentation/show_nodes.py +++ b/src/lionweb/presentation/show_nodes.py @@ -28,6 +28,16 @@ def _generate_color_for_text(text: str) -> str: def _html_for_node(node: Node, role: str = "root") -> str: + """Recursively render a node and its containment subtree as an HTML `
  • ` fragment. + + Args: + node: The node to render. + role: The name of the containment role under which `node` appears in + its parent (used as a label and to derive a consistent color). + + Returns: + str: The HTML fragment representing the node and its descendants. + """ role_color = _generate_color_for_text(role) classifier_color = _generate_color_for_text(node.get_classifier().qualified_name()) @@ -58,7 +68,16 @@ def _html_for_node(node: Node, role: str = "root") -> str: return html -def display_node(node: Node): +def display_node(node: Node) -> None: + """Render an interactive, collapsible HTML tree view of a node and display it. + + Intended for use in Jupyter/IPython environments: builds an HTML/CSS/JS + snippet visualizing the node and its containment subtree, and displays it + via `IPython.display`. + + Args: + node: The root node to display. + """ html_code = """