From 6da98b1e02a2ae4be78b7ed4f9c24ed9fc297b2c Mon Sep 17 00:00:00 2001 From: ftomassetti Date: Sun, 7 Jun 2026 10:38:47 +0200 Subject: [PATCH 1/7] Remove `ROADMAP.md`, add `__all__` to modules for public API control, introduce specific exception types, enhance docstrings, leverage Python 3.10+ features (e.g., pattern matching), and tighten type hints. --- CHANGELOG.md | 29 +++++ ROADMAP.md | 11 -- src/lionweb/generation/__init__.py | 21 ++++ src/lionweb/language/__init__.py | 27 +++++ src/lionweb/model/__init__.py | 8 ++ src/lionweb/presentation/__init__.py | 3 + src/lionweb/self/__init__.py | 3 + src/lionweb/serialization/__init__.py | 3 + .../serialization/classifier_resolver.py | 63 +++++++++- src/lionweb/utils/__init__.py | 11 +- src/lionweb/utils/language_validator.py | 114 +++++++++++------- 11 files changed, 231 insertions(+), 62 deletions(-) create mode 100644 CHANGELOG.md delete mode 100644 ROADMAP.md 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/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/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/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/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/self/__init__.py b/src/lionweb/self/__init__.py index e69de29..05f3d30 100644 --- a/src/lionweb/self/__init__.py +++ b/src/lionweb/self/__init__.py @@ -0,0 +1,3 @@ +from .lioncore import LionCore as LionCore + +__all__ = ["LionCore"] diff --git a/src/lionweb/serialization/__init__.py b/src/lionweb/serialization/__init__.py index f5dcc34..1615efa 100644 --- a/src/lionweb/serialization/__init__.py +++ b/src/lionweb/serialization/__init__.py @@ -1,5 +1,6 @@ from .abstract_serialization import AbstractSerialization from .archive import load_archive, process_archive +from .classifier_resolver import ClassifierResolver, UnresolvedClassifierError from .data import ( MetaPointer, SerializationChunk, @@ -20,6 +21,8 @@ __all__ = [ "AbstractSerialization", + "ClassifierResolver", + "UnresolvedClassifierError", "InstantiationError", "JsonSerialization", "create_standard_json_serialization", diff --git a/src/lionweb/serialization/classifier_resolver.py b/src/lionweb/serialization/classifier_resolver.py index 9ff23d9..f9beb87 100644 --- a/src/lionweb/serialization/classifier_resolver.py +++ b/src/lionweb/serialization/classifier_resolver.py @@ -6,32 +6,83 @@ from lionweb.serialization.data.metapointer import MetaPointer +class UnresolvedClassifierError(RuntimeError): + """Raised when a classifier, concept, or annotation cannot be resolved from a MetaPointer. + + Args: + kind: The kind of element that could not be resolved (e.g. "classifier", "concept"). + meta_pointer: The :class:`MetaPointer` that could not be resolved. + """ + + def __init__(self, kind: str, meta_pointer: MetaPointer): + super().__init__(f"Unable to resolve {kind} with metaPointer {meta_pointer}") + self.kind = kind + self.meta_pointer = meta_pointer + + class ClassifierResolver: - def __init__(self): + """Resolves classifiers, concepts, and annotations by their :class:`MetaPointer`. + + Concepts and annotations must be registered (directly or via + :meth:`register_language`) before they can be resolved. + """ + + def __init__(self) -> None: self.registered_concepts: dict[MetaPointer, Concept] = {} self.registered_annotations: dict[MetaPointer, Annotation] = {} def resolve_classifier(self, concept_meta_pointer: MetaPointer) -> "Classifier": + """Resolve a classifier (concept or annotation) by its meta-pointer. + + Args: + concept_meta_pointer: The meta-pointer identifying the classifier. + + Returns: + Classifier: The resolved concept or annotation. + + Raises: + UnresolvedClassifierError: If no classifier is registered for the meta-pointer. + """ if concept_meta_pointer in self.registered_concepts: return self.registered_concepts[concept_meta_pointer] elif concept_meta_pointer in self.registered_annotations: return self.registered_annotations[concept_meta_pointer] else: - raise RuntimeError( - f"Unable to resolve classifier with metaPointer {concept_meta_pointer}" - ) + raise UnresolvedClassifierError("classifier", concept_meta_pointer) def resolve_concept(self, concept_meta_pointer: MetaPointer) -> "Concept": + """Resolve a concept by its meta-pointer. + + Args: + concept_meta_pointer: The meta-pointer identifying the concept. + + Returns: + Concept: The resolved concept. + + Raises: + UnresolvedClassifierError: If no concept is registered for the meta-pointer. + """ if concept_meta_pointer in self.registered_concepts: return self.registered_concepts[concept_meta_pointer] else: - raise RuntimeError(f"Unable to resolve concept with metaPointer {concept_meta_pointer}") + raise UnresolvedClassifierError("concept", concept_meta_pointer) def resolve_annotation(self, meta_pointer: MetaPointer) -> "Annotation": + """Resolve an annotation by its meta-pointer. + + Args: + meta_pointer: The meta-pointer identifying the annotation. + + Returns: + Annotation: The resolved annotation. + + Raises: + UnresolvedClassifierError: If no annotation is registered for the meta-pointer. + """ if meta_pointer in self.registered_annotations: return self.registered_annotations[meta_pointer] else: - raise RuntimeError(f"Unable to resolve annotation with metaPointer {meta_pointer}") + raise UnresolvedClassifierError("annotation", meta_pointer) def register_language(self, language: "Language") -> "ClassifierResolver": from lionweb.language import Annotation, Concept diff --git a/src/lionweb/utils/__init__.py b/src/lionweb/utils/__init__.py index d30a082..e7469d1 100644 --- a/src/lionweb/utils/__init__.py +++ b/src/lionweb/utils/__init__.py @@ -1,6 +1,15 @@ from .id_utils import clean_string_as_id, is_valid_id from .issue import Issue from .issue_severity import IssueSeverity +from .language_validator import InvalidLanguageError, LanguageValidator from .node_navigation import root -__all__ = ["is_valid_id", "clean_string_as_id", "Issue", "IssueSeverity", "root"] +__all__ = [ + "is_valid_id", + "clean_string_as_id", + "Issue", + "IssueSeverity", + "InvalidLanguageError", + "LanguageValidator", + "root", +] diff --git a/src/lionweb/utils/language_validator.py b/src/lionweb/utils/language_validator.py index e39c2df..44a456f 100644 --- a/src/lionweb/utils/language_validator.py +++ b/src/lionweb/utils/language_validator.py @@ -1,3 +1,4 @@ +from collections.abc import Sequence from typing import cast from lionweb.language.annotation import Annotation @@ -13,12 +14,36 @@ from lionweb.utils.validator import Validator +class InvalidLanguageError(ValueError): + """Raised when a :class:`Language` fails validation. + + Args: + language: The invalid language. + validation_result: The validation result describing the issues found. + """ + + def __init__(self, language: Language, validation_result: ValidationResult): + super().__init__(f"Invalid language: {validation_result.get_issues()}") + self.language = language + self.validation_result = validation_result + + class LanguageValidator(Validator): + """Validates :class:`Language` definitions for structural and naming consistency.""" + @staticmethod - def ensure_is_valid(language: Language): + def ensure_is_valid(language: Language) -> None: + """Validate a language and raise if it is invalid. + + Args: + language: The language to validate. + + Raises: + InvalidLanguageError: If the language fails validation. + """ vr = LanguageValidator().validate(language) if not vr.is_successful(): - raise RuntimeError(f"Invalid language: {vr.get_issues()}") + raise InvalidLanguageError(language, vr) def validate_enumeration(self, result: ValidationResult, enumeration: Enumeration): for lit in enumeration.literals: @@ -109,7 +134,9 @@ def validate(self, language: Language) -> ValidationResult: return result - def validate_names_are_unique(self, elements, result: ValidationResult): + def validate_names_are_unique( + self, elements: Sequence[object], result: ValidationResult + ) -> None: elements_by_name: dict[str, list[object]] = {} for el in elements: if el.get_name(): @@ -171,47 +198,46 @@ def check_ancestors_helper( validation_result: ValidationResult, examining_concept: bool, ): - if isinstance(classifier, Concept): - concept = classifier - if concept in already_explored: - validation_result.add_error("Cyclic hierarchy found", concept) - else: - already_explored.add(concept) - extended = concept.get_extended_concept() - if extended: - self.check_ancestors_helper( - already_explored, extended, validation_result, examining_concept - ) - for interf in concept.get_implemented(): - self.check_ancestors_helper( - already_explored, interf, validation_result, examining_concept - ) - elif isinstance(classifier, Interface): - iface = classifier - if iface in already_explored: - # It is ok to indirectly implement the same interface multiple times for a Concept. - # It is instead an issue in case we are looking into interfaces. - # - # For example, this is fine: - # class A extends B, implements I - # class B implements I - # - # This is not fine: - # interface I1 extends I2 - # interface I2 extends I1 - if not examining_concept: - validation_result.add_error("Cyclic hierarchy found", iface) - else: - already_explored.add(iface) - for extended_interface in iface.get_extended_interfaces(): - self.check_ancestors_helper( - already_explored, - extended_interface, - validation_result, - examining_concept, - ) - else: - raise ValueError() + match classifier: + case Concept() as concept: + if concept in already_explored: + validation_result.add_error("Cyclic hierarchy found", concept) + else: + already_explored.add(concept) + extended = concept.get_extended_concept() + if extended: + self.check_ancestors_helper( + already_explored, extended, validation_result, examining_concept + ) + for interf in concept.get_implemented(): + self.check_ancestors_helper( + already_explored, interf, validation_result, examining_concept + ) + case Interface() as iface: + if iface in already_explored: + # It is ok to indirectly implement the same interface multiple times for a Concept. + # It is instead an issue in case we are looking into interfaces. + # + # For example, this is fine: + # class A extends B, implements I + # class B implements I + # + # This is not fine: + # interface I1 extends I2 + # interface I2 extends I1 + if not examining_concept: + validation_result.add_error("Cyclic hierarchy found", iface) + else: + already_explored.add(iface) + for extended_interface in iface.get_extended_interfaces(): + self.check_ancestors_helper( + already_explored, + extended_interface, + validation_result, + examining_concept, + ) + case _: + raise ValueError(f"Unsupported classifier type: {type(classifier).__name__}") def check_interfaces_cycles(self, iface: Interface, validation_result: ValidationResult): if iface in iface.all_extended_interfaces(): From 1151c8c766d9f625b47a42fb28bf466a3c148444 Mon Sep 17 00:00:00 2001 From: ftomassetti Date: Sun, 7 Jun 2026 10:47:43 +0200 Subject: [PATCH 2/7] Enhance type hints, add and update docstrings across modules, introduce `ImmutableInstanceError` exception, refactor `SerializedContainmentValue` to a `dataclass`, and leverage Python 3.10+ features in method definitions. --- .../composite_classifier_instance_resolver.py | 22 +++ .../api/local_classifier_instance_resolver.py | 34 ++++- src/lionweb/client/bulk_import.py | 27 +++- src/lionweb/client/client.py | 95 ++++++++----- src/lionweb/client/repository_archives.py | 16 ++- src/lionweb/generation/ASTBuilder.py | 42 +++++- src/lionweb/generation/generation_utils.py | 27 ++++ src/lionweb/generation/naming_utils.py | 58 +++++++- src/lionweb/generation/topological_sorting.py | 79 +++++++---- src/lionweb/language/annotation.py | 12 +- src/lionweb/language/classifier.py | 38 +++++ src/lionweb/language/concept.py | 3 + src/lionweb/language/containment.py | 2 + src/lionweb/language/data_type.py | 2 + src/lionweb/language/debug_utils.py | 12 +- src/lionweb/language/definition.py | 62 ++++----- src/lionweb/language/enumeration.py | 23 +++- src/lionweb/language/enumeration_literal.py | 2 + src/lionweb/language/feature.py | 2 + src/lionweb/language/field.py | 4 +- src/lionweb/language/ikeyed.py | 15 ++ src/lionweb/language/inamed.py | 3 + src/lionweb/language/interface.py | 18 ++- src/lionweb/language/language.py | 24 +++- src/lionweb/language/language_entity.py | 2 + src/lionweb/language/link.py | 3 + src/lionweb/language/lioncore_builtins.py | 6 + src/lionweb/language/namespace_provider.py | 5 + src/lionweb/language/namespaced_entity.py | 14 +- src/lionweb/language/primitive_type.py | 2 + src/lionweb/language/property.py | 2 + src/lionweb/language/reference.py | 2 + src/lionweb/language/structured_data_type.py | 23 ++++ src/lionweb/model/annotation_instance.py | 10 ++ src/lionweb/model/classifier_instance.py | 25 +++- .../model/classifier_instance_utils.py | 130 ++++++++++++++++++ src/lionweb/model/has_feature_values.py | 4 + src/lionweb/model/has_settable_parent.py | 10 +- .../impl/abstract_classifier_instance.py | 6 +- .../model/impl/dynamic_annotation_instance.py | 8 +- .../model/impl/dynamic_classifier_instance.py | 60 +++++--- src/lionweb/model/impl/dynamic_node.py | 25 +++- .../dynamic_structured_datype_instance.py | 6 +- src/lionweb/model/impl/m3node.py | 12 +- src/lionweb/model/impl/proxy_node.py | 21 ++- src/lionweb/model/node.py | 14 +- src/lionweb/model/reference_value.py | 24 ++-- src/lionweb/serialization/archive.py | 23 +++- .../serialization/data/language_version.py | 30 +++- .../serialization/data/serialized_chunk.py | 30 +++- .../data/serialized_classifier_instance.py | 44 +++--- .../data/serialized_containment_value.py | 30 ++-- .../data/serialized_property_value.py | 19 ++- .../data/serialized_reference_value.py | 23 ++-- .../serialization/deserialization_status.py | 49 ++++++- src/lionweb/serialization/instantiator.py | 69 ++++++++-- .../low_level_json_serialization.py | 24 +++- src/lionweb/serialization/node_populator.py | 50 ++++++- .../serialization/serialization_provider.py | 35 ++++- .../serialized_json_comparison_utils.py | 34 +++-- src/lionweb/utils/model_comparator.py | 42 ++++-- src/lionweb/utils/naming.py | 19 +++ src/lionweb/utils/node_navigation.py | 11 ++ src/lionweb/utils/node_tree_validator.py | 7 + src/lionweb/utils/validation_result.py | 28 +++- src/lionweb/utils/validator.py | 11 +- 66 files changed, 1352 insertions(+), 262 deletions(-) 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..d40fcb3 100644 --- a/src/lionweb/api/local_classifier_instance_resolver.py +++ b/src/lionweb/api/local_classifier_instance_resolver.py @@ -8,23 +8,51 @@ 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": + 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. + """ 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..e711780 100644 --- a/src/lionweb/client/client.py +++ b/src/lionweb/client/client.py @@ -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, @@ -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: + """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") @@ -137,9 +160,9 @@ def create_partitions(self, nodes: list["Node"]): data = self._serialization.serialize_trees_to_json_element(nodes) response = requests.post(url, params=query_params, json=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 +174,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 +187,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 = { @@ -177,16 +200,16 @@ def store(self, nodes: list["ClassifierInstance"]): data = self._serialization.serialize_trees_to_json_element(nodes) response = requests.post(url, params=query_params, json=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 +228,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 +246,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 +259,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 +267,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] 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 +317,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 +325,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(): @@ -338,4 +361,4 @@ 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) 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/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/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/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/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..c9a048f 100644 --- a/src/lionweb/language/field.py +++ b/src/lionweb/language/field.py @@ -41,7 +41,7 @@ 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) -> None: self.set_property_value(property="name", value=name) def get_container(self) -> NamespaceProvider | None: @@ -64,7 +64,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/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/serialization/archive.py b/src/lionweb/serialization/archive.py index 2fc199d..bedb14f 100644 --- a/src/lionweb/serialization/archive.py +++ b/src/lionweb/serialization/archive.py @@ -13,6 +13,17 @@ def process_archive( filename: str | PathLike, chunk_processor: Callable[[int, int, "SerializationChunk"], None], ) -> None: + """Stream-process the chunks contained in a zipped LionWeb archive. + + Each entry of the zip archive is read, deserialized as a protobuf + :class:`SerializationChunk`, and passed to ``chunk_processor`` along with + its index and the total number of entries. + + Args: + filename: Path to the zip archive to process. + chunk_processor: Callback invoked as ``(index, total, chunk)`` for each + deserialized chunk. + """ ps = ProtoBufSerialization(LionWebVersion.V2023_1) import zipfile @@ -29,7 +40,15 @@ def process_archive( i += 1 -def load_archive(filename) -> list["SerializationChunk"]: - chunks = [] +def load_archive(filename: str | PathLike) -> list["SerializationChunk"]: + """Load all chunks from a zipped LionWeb archive into memory. + + Args: + filename: Path to the zip archive to load. + + Returns: + The list of deserialized chunks, in archive order. + """ + chunks: list[SerializationChunk] = [] process_archive(filename, lambda i, n, chunk: chunks.append(chunk)) return chunks diff --git a/src/lionweb/serialization/data/language_version.py b/src/lionweb/serialization/data/language_version.py index df7a86a..7e765e3 100644 --- a/src/lionweb/serialization/data/language_version.py +++ b/src/lionweb/serialization/data/language_version.py @@ -2,6 +2,18 @@ from typing import ClassVar, Self +class ImmutableInstanceError(RuntimeError): + """Raised when attempting to mutate an immutable, interned instance. + + Args: + class_name: The name of the class whose instance was mutated. + """ + + def __init__(self, class_name: str): + super().__init__(f"{class_name} instances are immutable after creation") + self.class_name = class_name + + class LanguageVersion: """ The pair Language Key and Language Version identify a specific version of a language. @@ -88,14 +100,24 @@ def from_meta_pointer(meta_pointer): def get_key(self) -> str | None: return self._key - def set_key(self, key: str): - raise RuntimeError("LanguageVersion instances are immutable after creation") + def set_key(self, key: str) -> None: + """Always raises, since instances are immutable. + + Raises: + ImmutableInstanceError: Always. + """ + raise ImmutableInstanceError("LanguageVersion") def get_version(self) -> str | None: return self._version - def set_version(self, version: str): - raise RuntimeError("LanguageVersion instances are immutable after creation") + def set_version(self, version: str) -> None: + """Always raises, since instances are immutable. + + Raises: + ImmutableInstanceError: Always. + """ + raise ImmutableInstanceError("LanguageVersion") @property def key(self) -> str | None: diff --git a/src/lionweb/serialization/data/serialized_chunk.py b/src/lionweb/serialization/data/serialized_chunk.py index 07599ee..c976dfe 100644 --- a/src/lionweb/serialization/data/serialized_chunk.py +++ b/src/lionweb/serialization/data/serialized_chunk.py @@ -6,6 +6,12 @@ @dataclass class SerializationChunk: + """An in-memory representation of a serialized chunk of a model. + + Holds the serialization format version, the languages used, and the + serialized classifier instances (nodes) contained in the chunk. + """ + serialization_format_version: str = "" languages: list[LanguageVersion] = field(default_factory=list) classifier_instances: list[SerializedClassifierInstance] = field(default_factory=list) @@ -13,11 +19,27 @@ class SerializationChunk: default_factory=dict ) - def add_classifier_instance(self, instance): + def add_classifier_instance(self, instance: SerializedClassifierInstance) -> None: + """Add a classifier instance to the chunk, indexing it by its ID. + + Args: + instance: The serialized classifier instance to add. + """ self.classifier_instances_by_id[instance.id] = instance self.classifier_instances.append(instance) def get_instance_by_id(self, instance_id: str) -> SerializedClassifierInstance: + """Look up a classifier instance by its ID. + + Args: + instance_id: The ID of the instance to look up. + + Returns: + The serialized classifier instance with the given ID. + + Raises: + ValueError: If no instance with the given ID exists in this chunk. + """ instance = self.classifier_instances_by_id.get(instance_id) if instance is None: raise ValueError(f"Cannot find instance with ID {instance_id}") @@ -53,10 +75,10 @@ def __hash__(self): def get_classifier_instances(self) -> list[SerializedClassifierInstance]: return list(self.classifier_instances) - def get_classifier_instances_by_id(self) -> dict[str, object]: + def get_classifier_instances_by_id(self) -> dict[str, SerializedClassifierInstance]: return dict(self.classifier_instances_by_id) - def get_languages(self) -> list: + def get_languages(self) -> list[LanguageVersion]: return list(self.languages) def populate_used_languages(self) -> None: @@ -76,7 +98,7 @@ def populate_used_languages(self) -> None: for property_value in classifier_instance.properties: self._consider_meta_pointer(property_value.get_meta_pointer()) - def _consider_meta_pointer(self, meta_pointer): + def _consider_meta_pointer(self, meta_pointer: object) -> None: used_language = LanguageVersion.from_meta_pointer(meta_pointer) if used_language not in self.languages: self.languages.append(used_language) diff --git a/src/lionweb/serialization/data/serialized_classifier_instance.py b/src/lionweb/serialization/data/serialized_classifier_instance.py index d6bc0f1..81f31f4 100644 --- a/src/lionweb/serialization/data/serialized_classifier_instance.py +++ b/src/lionweb/serialization/data/serialized_classifier_instance.py @@ -11,6 +11,12 @@ @dataclass class SerializedClassifierInstance: + """The serialized form of a classifier instance (a node or annotation instance). + + Holds the instance's ID, classifier, parent ID, and its serialized + properties, containments, references, and annotations. + """ + id: str | None classifier: MetaPointer properties: list[SerializedPropertyValue] = field(default_factory=list) @@ -19,49 +25,51 @@ class SerializedClassifierInstance: annotations: list[str | None] = field(default_factory=list) parent_node_id: str | None = None - def get_parent_node_id(self): + def get_parent_node_id(self) -> str | None: return self.parent_node_id - def set_parent_node_id(self, parent_node_id: str | None): + def set_parent_node_id(self, parent_node_id: str | None) -> None: self.parent_node_id = parent_node_id - def get_containments(self): + def get_containments(self) -> list[SerializedContainmentValue]: return list(self.containments) - def get_children(self): - children = [] + def get_children(self) -> list[str | None]: + children: list[str | None] = [] for containment in self.containments: children.extend(containment.get_children_ids()) return list(children) - def add_property_value(self, property_value: SerializedPropertyValue): + def add_property_value(self, property_value: SerializedPropertyValue) -> None: self.properties.append(property_value) - def add_containment_value(self, containment_value: SerializedContainmentValue): + def add_containment_value(self, containment_value: SerializedContainmentValue) -> None: self.containments.append(containment_value) - def add_reference_value(self, reference_value: SerializedReferenceValue): + def add_reference_value(self, reference_value: SerializedReferenceValue) -> None: self.references.append(reference_value) def get_classifier(self) -> MetaPointer: return self.classifier - def set_classifier(self, classifier: MetaPointer): + def set_classifier(self, classifier: MetaPointer) -> None: self.classifier = classifier - def set_property_value(self, property_meta_pointer, serialized_value): - from .serialized_property_value import SerializedPropertyValue - + def set_property_value( + self, property_meta_pointer: MetaPointer, serialized_value: str | None + ) -> None: self.properties.append(SerializedPropertyValue(property_meta_pointer, serialized_value)) - def add_children(self, containment_meta_pointer: MetaPointer, children_ids: list[str | None]): - from .serialized_containment_value import SerializedContainmentValue - + def add_children( + self, containment_meta_pointer: MetaPointer, children_ids: list[str | None] + ) -> None: self.containments.append(SerializedContainmentValue(containment_meta_pointer, children_ids)) - def add_reference_value_entries(self, reference_meta_pointer, reference_values: list): - from .serialized_reference_value import SerializedReferenceValue - + def add_reference_value_entries( + self, + reference_meta_pointer: MetaPointer, + reference_values: list[SerializedReferenceValueEntry], + ) -> None: self.references.append(SerializedReferenceValue(reference_meta_pointer, reference_values)) def get_property_value_by_key(self, property_key: str) -> str | None: diff --git a/src/lionweb/serialization/data/serialized_containment_value.py b/src/lionweb/serialization/data/serialized_containment_value.py index fef8f94..aaf82a0 100644 --- a/src/lionweb/serialization/data/serialized_containment_value.py +++ b/src/lionweb/serialization/data/serialized_containment_value.py @@ -1,30 +1,44 @@ +from dataclasses import dataclass, field + from lionweb.serialization.data.metapointer import MetaPointer +@dataclass class SerializedContainmentValue: - def __init__(self, meta_pointer: MetaPointer, children_ids: list[str | None]): - self.meta_pointer = meta_pointer - self.children_ids = children_ids if children_ids is not None else [] + """A serialized containment feature value: a meta pointer plus the IDs of the children. + + Args: + meta_pointer: The :class:`MetaPointer` identifying the containment feature. + children_ids: The IDs of the contained children (``None`` entries indicate + children with a null/missing ID). + """ + + meta_pointer: MetaPointer + children_ids: list[str | None] = field(default_factory=list) + + def __post_init__(self) -> None: + if self.children_ids is None: + self.children_ids = [] def get_meta_pointer(self) -> MetaPointer: return self.meta_pointer - def set_meta_pointer(self, meta_pointer): + def set_meta_pointer(self, meta_pointer: MetaPointer) -> None: self.meta_pointer = meta_pointer def get_children_ids(self) -> list[str | None]: return self.children_ids.copy() - def set_children_ids(self, value: list[str | None]): + def set_children_ids(self, value: list[str | None]) -> None: self.children_ids = value.copy() - def __eq__(self, other): + def __eq__(self, other: object) -> bool: if not isinstance(other, SerializedContainmentValue): return False return self.meta_pointer == other.meta_pointer and self.children_ids == other.children_ids - def __hash__(self): + def __hash__(self) -> int: return hash((self.meta_pointer, tuple(self.children_ids))) - def __str__(self): + def __str__(self) -> str: return f"SerializedContainmentValue{{meta_pointer={self.meta_pointer}, value={self.children_ids}}}" diff --git a/src/lionweb/serialization/data/serialized_property_value.py b/src/lionweb/serialization/data/serialized_property_value.py index 935c3cc..8d0e87c 100644 --- a/src/lionweb/serialization/data/serialized_property_value.py +++ b/src/lionweb/serialization/data/serialized_property_value.py @@ -1,6 +1,7 @@ import threading from typing import ClassVar, Self +from lionweb.serialization.data.language_version import ImmutableInstanceError from lionweb.serialization.data.metapointer import MetaPointer @@ -51,8 +52,13 @@ def get_meta_pointer(self) -> MetaPointer: def meta_pointer(self) -> MetaPointer: return self._meta_pointer - def set_meta_pointer(self, meta_pointer: MetaPointer): - raise RuntimeError("SerializedPropertyValue instances are immutable after creation") + def set_meta_pointer(self, meta_pointer: MetaPointer) -> None: + """Always raises, since instances are immutable. + + Raises: + ImmutableInstanceError: Always. + """ + raise ImmutableInstanceError("SerializedPropertyValue") def get_value(self) -> str | None: return self._value @@ -61,8 +67,13 @@ def get_value(self) -> str | None: def value(self) -> str | None: return self._value - def set_value(self, value: str | None): - raise RuntimeError("SerializedPropertyValue instances are immutable after creation") + def set_value(self, value: str | None) -> None: + """Always raises, since instances are immutable. + + Raises: + ImmutableInstanceError: Always. + """ + raise ImmutableInstanceError("SerializedPropertyValue") @classmethod def clear_cache(cls): diff --git a/src/lionweb/serialization/data/serialized_reference_value.py b/src/lionweb/serialization/data/serialized_reference_value.py index edc4e52..bcece4c 100644 --- a/src/lionweb/serialization/data/serialized_reference_value.py +++ b/src/lionweb/serialization/data/serialized_reference_value.py @@ -25,37 +25,44 @@ def __hash__(self): class SerializedReferenceValue: + """A serialized reference feature value: a meta pointer plus the list of reference entries. + + Args: + meta_pointer: The :class:`MetaPointer` identifying the reference feature, if known. + value: The list of :class:`SerializedReferenceValueEntry` targets for this reference. + """ + def __init__( self, - meta_pointer=None, + meta_pointer: MetaPointer | None = None, value: list[SerializedReferenceValueEntry] | None = None, ): self.meta_pointer = meta_pointer self.value = value[:] if value else [] - def get_meta_pointer(self) -> MetaPointer: + def get_meta_pointer(self) -> MetaPointer | None: return self.meta_pointer - def set_meta_pointer(self, meta_pointer): + def set_meta_pointer(self, meta_pointer: MetaPointer | None) -> None: self.meta_pointer = meta_pointer def get_value(self) -> list[SerializedReferenceValueEntry]: return list(self.value) - def set_value(self, value: list[SerializedReferenceValueEntry]): + def set_value(self, value: list[SerializedReferenceValueEntry]) -> None: self.value.clear() self.value.extend(value) - def add_value(self, value: SerializedReferenceValueEntry): + def add_value(self, value: SerializedReferenceValueEntry) -> None: self.value.append(value) - def __eq__(self, other): + def __eq__(self, other: object) -> bool: if not isinstance(other, SerializedReferenceValue): return False return self.meta_pointer == other.meta_pointer and self.value == other.value - def __hash__(self): + def __hash__(self) -> int: return hash((self.meta_pointer, tuple(self.value))) - def __str__(self): + def __str__(self) -> str: return f"SerializedReferenceValue{{meta_pointer={self.meta_pointer}, value={self.value}}}" diff --git a/src/lionweb/serialization/deserialization_status.py b/src/lionweb/serialization/deserialization_status.py index 0dfee64..18d7344 100644 --- a/src/lionweb/serialization/deserialization_status.py +++ b/src/lionweb/serialization/deserialization_status.py @@ -14,11 +14,24 @@ class DeserializationStatus: + """Tracks the progress of sorting and resolving instances during deserialization. + + Maintains the list of serialized instances still to be sorted (leaves first), + the resulting sorted list, and any proxy nodes created for unavailable + referenced/parent instances. + """ + def __init__( self, original_list: list[SerializedClassifierInstance], outside_instances_resolver: "ClassifierInstanceResolver", - ): + ) -> None: + """Initialize the deserialization status. + + Args: + original_list: The serialized instances to sort and deserialize. + outside_instances_resolver: Resolver for instances outside the chunk being deserialized. + """ from lionweb.api.composite_classifier_instance_resolver import ( CompositeClassifierInstanceResolver, ) @@ -34,15 +47,22 @@ def __init__( ) def put_nodes_with_null_ids_in_front(self) -> None: + """Move all instances with a ``None`` ID to the front of the sorted list.""" null_id_nodes = [n for n in self.nodes_to_sort if n.id is None] self.sorted_list.extend(null_id_nodes) self.nodes_to_sort = [n for n in self.nodes_to_sort if n.id is not None] def place(self, node: SerializedClassifierInstance) -> None: + """Move an instance from the to-sort list to the sorted list. + + Args: + node: The serialized instance to place. + """ self.sorted_list.append(node) self.nodes_to_sort.remove(node) - def reverse(self): + def reverse(self) -> None: + """Reverse the sorted list in place.""" self.sorted_list.reverse() def how_many_sorted(self) -> int: @@ -51,13 +71,25 @@ def how_many_sorted(self) -> int: def how_many_to_sort(self) -> int: return len(self.nodes_to_sort) - def get_node_to_sort(self, index: int): + def get_node_to_sort(self, index: int) -> SerializedClassifierInstance: return self.nodes_to_sort[index] def stream_sorted(self): return iter(self.sorted_list) def resolve(self, node_id: str | None) -> Node | None: + """Resolve a node by ID, creating a proxy if it cannot be found. + + Args: + node_id: The ID of the node to resolve, or ``None``. + + Returns: + The resolved node, a newly created proxy node, or ``None`` if + ``node_id`` is ``None``. + + Raises: + ValueError: If the given ID resolves to a non-node instance. + """ if node_id is None: return None resolved = self.global_instance_resolver.resolve(node_id) @@ -68,6 +100,17 @@ def resolve(self, node_id: str | None) -> Node | None: raise ValueError(f"The given ID resolved to a non-node instance: {resolved}") def create_proxy(self, node_id: str) -> "ProxyNode": + """Create and register a proxy node for an ID that cannot otherwise be resolved. + + Args: + node_id: The ID the proxy node should represent. + + Returns: + The newly created proxy node. + + Raises: + ValueError: If the ID is already resolvable (a proxy would be redundant). + """ from lionweb.model.impl.proxy_node import ProxyNode if self.global_instance_resolver.resolve(node_id) is not None: diff --git a/src/lionweb/serialization/instantiator.py b/src/lionweb/serialization/instantiator.py index d2c693a..58c685a 100644 --- a/src/lionweb/serialization/instantiator.py +++ b/src/lionweb/serialization/instantiator.py @@ -10,6 +10,7 @@ from lionweb.model.impl.dynamic_annotation_instance import DynamicAnnotationInstance if TYPE_CHECKING: + from lionweb.lionweb_version import LionWebVersion from lionweb.model.node import Node from lionweb.serialization.data.serialized_classifier_instance import ( SerializedClassifierInstance, @@ -17,12 +18,25 @@ class InstantiationError(Exception): + """Raised when no deserializer is able to instantiate a node for a given classifier. + + Args: + classifier: The classifier for which instantiation failed. + """ + def __init__(self, classifier): super().__init__(f"Unable to instantiate instance with classifier {classifier}") self.classifier = classifier class Instantiator: + """Creates deserialized node instances from their serialized form. + + Instantiation can be customized per-classifier via + :meth:`register_custom_deserializer`, or a default dynamic-node based + deserializer can be enabled via :meth:`enable_dynamic_nodes`. + """ + class ClassifierSpecificInstantiator: def instantiate( self, @@ -33,16 +47,20 @@ def instantiate( ): raise NotImplementedError - def __init__(self): + def __init__(self) -> None: self.custom_deserializers: dict[str, Callable] = {} self.default_node_deserializer = ( - lambda classifier, - serialized_node, - deserialized_instances_by_id, - properties_values: InstantiationError(classifier) + lambda classifier, serialized_node, deserialized_instances_by_id, properties_values: ( + InstantiationError(classifier) + ) ) - def enable_dynamic_nodes(self): + def enable_dynamic_nodes(self) -> "Instantiator": + """Enable a default deserializer that produces dynamic nodes/annotation instances. + + Returns: + This instantiator, to allow chaining. + """ from lionweb.language import Annotation, Concept from lionweb.model.impl.dynamic_node import DynamicNode @@ -66,6 +84,21 @@ def instantiate( deserialized_instances_by_id, properties_values, ) -> "Node": + """Instantiate a node from its serialized form using the registered deserializers. + + Args: + classifier: The classifier (concept or annotation) of the instance. + serialized_instance: The serialized classifier instance to instantiate from. + deserialized_instances_by_id: Already-deserialized instances, keyed by ID. + properties_values: The deserialized property values, keyed by property. + + Returns: + The instantiated node. + + Raises: + Exception: Whatever exception (e.g. :class:`InstantiationError`) the + resolved deserializer produces when it cannot instantiate the node. + """ if classifier.id in self.custom_deserializers: res = self.custom_deserializers[classifier.id]( classifier, @@ -85,10 +118,25 @@ def instantiate( return res def register_custom_deserializer(self, classifier_id, deserializer) -> "Instantiator": + """Register a custom deserializer for a specific classifier ID. + + Args: + classifier_id: The ID of the classifier the deserializer handles. + deserializer: A callable producing a node from + ``(classifier, serialized_instance, deserialized_instances_by_id, properties_values)``. + + Returns: + This instantiator, to allow chaining. + """ self.custom_deserializers[classifier_id] = deserializer return self - def register_lioncore_custom_deserializers(self, lion_web_version): + def register_lioncore_custom_deserializers(self, lion_web_version: "LionWebVersion") -> None: + """Register custom deserializers for all LionCore meta-language elements. + + Args: + lion_web_version: The LionWeb version whose LionCore elements should be handled. + """ from lionweb.language import Annotation, Concept, Containment, Interface, Language, Property from lionweb.self.lioncore import LionCore @@ -118,10 +166,9 @@ def register_lioncore_custom_deserializers(self, lion_web_version): LionCore.get_enumeration(lion_web_version).id: lambda c, s, d, p: Enumeration( lion_web_version=lion_web_version ).set_id(s.id), - LionCore.get_enumeration_literal(lion_web_version).id: lambda c, - s, - d, - p: EnumerationLiteral(lion_web_version=lion_web_version).set_id(s.id), + LionCore.get_enumeration_literal(lion_web_version).id: lambda c, s, d, p: ( + EnumerationLiteral(lion_web_version=lion_web_version).set_id(s.id) + ), LionCore.get_annotation(lion_web_version).id: lambda c, s, d, p: Annotation( lion_web_version=lion_web_version ).set_id(s.id), diff --git a/src/lionweb/serialization/low_level_json_serialization.py b/src/lionweb/serialization/low_level_json_serialization.py index ea97756..df657ae 100644 --- a/src/lionweb/serialization/low_level_json_serialization.py +++ b/src/lionweb/serialization/low_level_json_serialization.py @@ -16,7 +16,25 @@ class LowLevelJsonSerialization: + """Translates between raw JSON elements and :class:`SerializationChunk` instances. + + This class operates purely at the level of generic JSON data structures + (dicts, lists, primitives) and the :class:`SerializationChunk` data model, + without any knowledge of the LionWeb metamodel. + """ + def deserialize_serialization_block(self, json_element: JsonElement) -> SerializationChunk: + """Deserialize a raw JSON element into a :class:`SerializationChunk`. + + Args: + json_element: The JSON element to deserialize, expected to be a JSON object. + + Returns: + The deserialized :class:`SerializationChunk`. + + Raises: + ValueError: If ``json_element`` is not a JSON object. + """ serialized_chunk = SerializationChunk() if isinstance(json_element, dict): self._check_no_extra_keys( @@ -185,7 +203,7 @@ def _read_languages(self, serialized_chunk: SerializationChunk, top_level: JsonO raise ValueError(f"Language should be an object. Found: {element}") serialized_chunk.add_language(language_key_version) except Exception as e: - raise RuntimeError(f"Issue while deserializing {element}") from e + raise DeserializationException(f"Issue while deserializing {element}") from e else: raise ValueError(f"We expected a list, we got instead: {languages}") @@ -244,7 +262,9 @@ def _deserialize_classifier_instance( elif "containments" in json_element: containments = cast(JsonArray, json_element.get("containments", [])) else: - raise RuntimeError(f"Node is missing containments entry: {json_element}") + raise DeserializationException( + f"Node is missing containments entry: {json_element}" + ) for containment_entry in containments: containment_obj = cast(JsonObject, containment_entry) diff --git a/src/lionweb/serialization/node_populator.py b/src/lionweb/serialization/node_populator.py index 0aacf59..867cdfb 100644 --- a/src/lionweb/serialization/node_populator.py +++ b/src/lionweb/serialization/node_populator.py @@ -17,6 +17,13 @@ class NodePopulator: + """Populates a deserialized node's containments and references from its serialized form. + + This is used during deserialization, after instances have been created + (instantiated) but before their containment and reference features are filled in, + since resolving these features may require other instances to already exist. + """ + if TYPE_CHECKING: from lionweb.serialization.abstract_serialization import AbstractSerialization @@ -26,7 +33,16 @@ def __init__( classifier_instance_resolver: ClassifierInstanceResolver, deserialization_status: DeserializationStatus, auto_resolve_version: LionWebVersion = LionWebVersion.current_version(), - ): + ) -> None: + """Initialize the populator. + + Args: + serialization: The owning serialization, providing unavailable-node policies. + classifier_instance_resolver: Resolver used to look up already-deserialized instances. + deserialization_status: The deserialization status, used to resolve/create proxies. + auto_resolve_version: The LionWeb version used to build the auto-resolve map + for LionCore and LionCoreBuiltins elements. + """ from lionweb.serialization.abstract_serialization import AbstractSerialization self.serialization: AbstractSerialization = serialization @@ -49,6 +65,12 @@ def populate_classifier_instance( node: ClassifierInstance, serialized_classifier_instance: SerializedClassifierInstance, ) -> None: + """Populate both containments and references of a deserialized node. + + Args: + node: The deserialized node to populate. + serialized_classifier_instance: The serialized form to populate it from. + """ self.populate_containments(node, serialized_classifier_instance) self.populate_node_references(node, serialized_classifier_instance) @@ -57,18 +79,28 @@ def populate_containments( node: ClassifierInstance, serialized_classifier_instance: SerializedClassifierInstance, ) -> None: + """Populate the containment features of a deserialized node. + + Args: + node: The deserialized node to populate. + serialized_classifier_instance: The serialized form providing the children IDs. + + Raises: + DeserializationException: If a containment cannot be resolved on the + node's concept, or its serialized children value is null. + """ concept = node.get_classifier() for serialized_containment_value in serialized_classifier_instance.get_containments(): containment = concept.get_containment_by_meta_pointer( serialized_containment_value.meta_pointer ) if containment is None: - raise ValueError( + raise DeserializationException( f"Unable to resolve containment {serialized_containment_value.meta_pointer} in concept {concept}" ) if serialized_containment_value.children_ids is None: - raise ValueError("The containment value should not be null") + raise DeserializationException("The containment value should not be null") deserialized_value = [] for child_node_id in serialized_containment_value.children_ids: @@ -93,13 +125,23 @@ def populate_node_references( node: ClassifierInstance, serialized_classifier_instance: SerializedClassifierInstance, ) -> None: + """Populate the reference features of a deserialized node. + + Args: + node: The deserialized node to populate. + serialized_classifier_instance: The serialized form providing the reference entries. + + Raises: + DeserializationException: If a reference cannot be resolved on the + node's concept, or an unresolved target must throw per policy. + """ concept = node.get_classifier() for serialized_reference_value in serialized_classifier_instance.references: reference = concept.get_reference_by_meta_pointer( serialized_reference_value.meta_pointer ) if reference is None: - raise ValueError( + raise DeserializationException( f"Unable to resolve reference {serialized_reference_value.meta_pointer}. Concept {concept}. SerializedNode {serialized_classifier_instance}" ) diff --git a/src/lionweb/serialization/serialization_provider.py b/src/lionweb/serialization/serialization_provider.py index 1b609b3..9889925 100644 --- a/src/lionweb/serialization/serialization_provider.py +++ b/src/lionweb/serialization/serialization_provider.py @@ -6,7 +6,19 @@ def create_standard_json_serialization( lion_web_version: LionWebVersion = LionWebVersion.current_version(), -): +) -> JsonSerialization: + """Create a :class:`JsonSerialization` set up with the standard LionWeb languages. + + Args: + lion_web_version: The LionWeb version to target. + + Returns: + A :class:`JsonSerialization` instance, initialized with LionCore and + LionCoreBuiltins so that standard languages can be (de)serialized. + + Raises: + ValueError: If ``lion_web_version`` is not a :class:`LionWebVersion`. + """ if lion_web_version is None: lion_web_version = LionWebVersion.current_version if not isinstance(lion_web_version, LionWebVersion): @@ -18,7 +30,19 @@ def create_standard_json_serialization( def create_standard_protobuf_serialization( lion_web_version: LionWebVersion = LionWebVersion.current_version(), -): +) -> ProtoBufSerialization: + """Create a :class:`ProtoBufSerialization` set up with the standard LionWeb languages. + + Args: + lion_web_version: The LionWeb version to target. + + Returns: + A :class:`ProtoBufSerialization` instance, initialized with LionCore and + LionCoreBuiltins so that standard languages can be (de)serialized. + + Raises: + ValueError: If ``lion_web_version`` is not a :class:`LionWebVersion`. + """ if lion_web_version is None: lion_web_version = LionWebVersion.current_version if not isinstance(lion_web_version, LionWebVersion): @@ -28,7 +52,12 @@ def create_standard_protobuf_serialization( return serialization -def setup_standard_initialization(serialization): +def setup_standard_initialization(serialization) -> None: + """Register LionCore and LionCoreBuiltins languages and deserializers on a serialization. + + Args: + serialization: The serialization instance (JSON or protobuf) to initialize. + """ from lionweb.self.lioncore import LionCore serialization.classifier_resolver.register_language( diff --git a/src/lionweb/serialization/serialized_json_comparison_utils.py b/src/lionweb/serialization/serialized_json_comparison_utils.py index 063e742..eef49fb 100644 --- a/src/lionweb/serialization/serialized_json_comparison_utils.py +++ b/src/lionweb/serialization/serialized_json_comparison_utils.py @@ -3,14 +3,28 @@ from lionweb.serialization.json_utils import JsonArray, JsonObject +class IrregularJsonKeysError(ValueError): + """Raised when a top-level serialized LionWeb JSON object has unexpected keys. + + Args: + label: A short label identifying which object is irregular (e.g. "expected", "actual"). + keys: The actual set of keys found on the object. + """ + + def __init__(self, label: str, keys): + super().__init__(f"The {label} object has irregular keys: {keys}") + self.label = label + self.keys = keys + + class SerializedJsonComparisonUtils: @staticmethod - def assert_equivalent_lionweb_json(expected: JsonObject, actual: JsonObject): + def assert_equivalent_lionweb_json(expected: JsonObject, actual: JsonObject) -> None: keys = {"serializationFormatVersion", "nodes", "languages"} if set(expected.keys()) != keys: - raise RuntimeError(f"The expected object has irregular keys: {expected.keys()}") + raise IrregularJsonKeysError("expected", expected.keys()) if set(actual.keys()) != keys: - raise RuntimeError(f"The actual object has irregular keys: {actual.keys()}") + raise IrregularJsonKeysError("actual", actual.keys()) SerializedJsonComparisonUtils.assert_equals( "serializationFormatVersion", @@ -47,7 +61,7 @@ def assert_equivalent_lionweb_json_languages( ) @staticmethod - def assert_equivalent_lionweb_json_nodes(expected: JsonArray, actual: JsonArray): + def assert_equivalent_lionweb_json_nodes(expected: JsonArray, actual: JsonArray) -> None: expected_elements = {(cast(JsonObject, e))["id"]: e for e in expected} actual_elements = {(cast(JsonObject, e))["id"]: e for e in actual} @@ -71,7 +85,7 @@ def assert_equivalent_lionweb_json_nodes(expected: JsonArray, actual: JsonArray) ) @staticmethod - def assert_equivalent_nodes(expected: dict, actual: dict, context: str): + def assert_equivalent_nodes(expected: dict, actual: dict, context: str) -> None: actual_keys = set(actual.keys()) expected_keys = set(expected.keys()) @@ -104,7 +118,9 @@ def assert_equivalent_nodes(expected: dict, actual: dict, context: str): raise AssertionError(f"({context}) unexpected top-level key found: {key}") @staticmethod - def assert_equivalent_unordered_arrays(expected: list[dict], actual: list[dict], context: str): + def assert_equivalent_unordered_arrays( + expected: list[dict], actual: list[dict], context: str + ) -> None: if len(expected) != len(actual): raise AssertionError( f"({context}) Arrays with different sizes: expected={len(expected)} and actual={len(actual)}" @@ -139,7 +155,7 @@ def are_equivalent_objects(expected: dict, actual: dict) -> bool: return False @staticmethod - def assert_equivalent_objects(expected: dict, actual: dict, context: str): + def assert_equivalent_objects(expected: dict, actual: dict, context: str) -> None: actual_meaningful_keys = {k for k, v in actual.items() if v not in ({}, [], None)} expected_meaningful_keys = {k for k, v in expected.items() if v not in ({}, [], None)} @@ -159,10 +175,10 @@ def assert_equivalent_objects(expected: dict, actual: dict, context: str): ) @staticmethod - def assert_equals(message: str, expected, actual): + def assert_equals(message: str, expected: object, actual: object) -> None: if expected != actual: raise AssertionError(f"{message}: expected {expected} but found {actual}") @staticmethod - def fail(message: str): + def fail(message: str) -> None: raise AssertionError(f"Comparison failed. {message}") diff --git a/src/lionweb/utils/model_comparator.py b/src/lionweb/utils/model_comparator.py index ae57d2f..e1d427f 100644 --- a/src/lionweb/utils/model_comparator.py +++ b/src/lionweb/utils/model_comparator.py @@ -8,13 +8,17 @@ class ComparisonResult: - def __init__(self): - self.differences = [] + """Accumulates the differences found while comparing two model trees.""" - def get_differences(self): + def __init__(self) -> None: + self.differences: list[str] = [] + + def get_differences(self) -> list[str]: + """Return the list of differences found so far, as human-readable strings.""" return self.differences - def are_equivalent(self): + def are_equivalent(self) -> bool: + """Return True if no differences were recorded.""" return len(self.differences) == 0 def mark_different_ids(self, context: str, id_a: str, id_b: str): @@ -114,17 +118,31 @@ def mark_different_number_of_annotations(self, context: str, na: int, nb: int): def mark_different_annotation(self, context: str, i: int): self.differences.append(f"{context} annotation {i} is different") - def __str__(self): + def __str__(self) -> str: return f"ComparisonResult: {self.differences}" class ModelComparator: - def __init__(self, unordered_links=None): - if unordered_links is None: - unordered_links = [] - self.unordered_links = unordered_links + """Compares two model trees node-by-node, collecting differences. + + Containments listed in `unordered_links` are compared as sets (matched by + ID after sorting) rather than positionally, which is useful for links whose + order is not semantically significant. + """ + + def __init__(self, unordered_links: list | None = None) -> None: + self.unordered_links = unordered_links if unordered_links is not None else [] + + def compare(self, node_a: Node, node_b: Node) -> ComparisonResult: + """Compare two node trees and return the differences found. + + Args: + node_a: The first tree to compare. + node_b: The second tree to compare. - def compare(self, node_a: Node, node_b: Node): + Returns: + ComparisonResult: The differences found between the two trees. + """ comparison_result = ComparisonResult() self._compare_nodes(node_a, node_b, comparison_result, "") return comparison_result @@ -171,9 +189,9 @@ def _compare_references( else: for i, (ref_a, ref_b) in enumerate(zip(value_a, value_b)): if not isinstance(ref_a, ReferenceValue): - raise ValueError() + raise ValueError(f"Expected a ReferenceValue, got {ref_a!r}") if not isinstance(ref_b, ReferenceValue): - raise ValueError() + raise ValueError(f"Expected a ReferenceValue, got {ref_b!r}") if ref_a.get_referred_id() != ref_b.get_referred_id(): comparison_result.mark_different_referred_id( context, diff --git a/src/lionweb/utils/naming.py b/src/lionweb/utils/naming.py index d72aee7..5b73075 100644 --- a/src/lionweb/utils/naming.py +++ b/src/lionweb/utils/naming.py @@ -4,15 +4,34 @@ class Naming: + """Helpers to validate names and qualified names used in LionWeb models.""" + QUALIFIED_NAME_PATTERN = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)*$") @staticmethod def validate_qualified_name(qualified_name: str) -> None: + """Validate that the given string is a well-formed qualified name. + + Args: + qualified_name: The qualified name to validate. + + Raises: + InvalidName: If the qualified name does not match the expected pattern. + """ if Naming.QUALIFIED_NAME_PATTERN.fullmatch(qualified_name) is None: raise InvalidName("qualified name", qualified_name) @staticmethod def validate_name(name: str) -> None: + """Validate that the given string is a well-formed simple name. + + Args: + name: The name to validate. + + Raises: + ValueError: If `name` is None. + InvalidName: If the name does not match the expected pattern. + """ if name is None: raise ValueError("The name should not be null") if not re.fullmatch("[a-zA-Z][a-zA-Z0-9_]*", name) is not None: diff --git a/src/lionweb/utils/node_navigation.py b/src/lionweb/utils/node_navigation.py index 89d971f..7cd9e9a 100644 --- a/src/lionweb/utils/node_navigation.py +++ b/src/lionweb/utils/node_navigation.py @@ -5,6 +5,17 @@ def root(nodes: list["Node"]) -> "Node": + """Return the single root node among the given nodes. + + Args: + nodes: The nodes to search. + + Returns: + Node: The unique root node. + + Raises: + ValueError: If there is not exactly one root node. + """ roots = [node for node in nodes if node.is_root()] if len(roots) != 1: raise ValueError(f"Expected one root, found {len(roots)}") diff --git a/src/lionweb/utils/node_tree_validator.py b/src/lionweb/utils/node_tree_validator.py index bbc55bf..0d77ba6 100644 --- a/src/lionweb/utils/node_tree_validator.py +++ b/src/lionweb/utils/node_tree_validator.py @@ -5,6 +5,13 @@ class NodeTreeValidator(Validator): + """Validates a node and all its descendants. + + Checks performed include: ID validity, root node being a Partition, + containment cardinality constraints, and uniqueness of node IDs across + the whole tree. + """ + def validate(self, element: Node) -> ValidationResult: validation_result = ValidationResult() self._validate_node_and_descendants(element, validation_result) diff --git a/src/lionweb/utils/validation_result.py b/src/lionweb/utils/validation_result.py index 3fb66c0..64521f4 100644 --- a/src/lionweb/utils/validation_result.py +++ b/src/lionweb/utils/validation_result.py @@ -4,30 +4,54 @@ class ValidationResult: - def __init__(self): + """Accumulates validation issues found while validating a model element.""" + + def __init__(self) -> None: self.issues: set[Issue] = set() def get_issues(self) -> set[Issue]: + """Return the set of issues collected so far.""" return self.issues def is_successful(self) -> bool: + """Return True if no error-level issues were recorded.""" return not self.has_errors() def has_errors(self) -> bool: + """Return True if at least one error-level issue was recorded.""" return any(issue.is_error() for issue in self.issues) def add_error(self, message: str, subject: ClassifierInstance) -> "ValidationResult": + """Record an error-level issue. + + Args: + message: Description of the problem. + subject: The classifier instance the issue refers to. + + Returns: + ValidationResult: This instance, to allow chaining. + """ self.issues.add(Issue(IssueSeverity.ERROR, message, subject)) return self def add_error_if( self, check: bool, message: str, subject: ClassifierInstance ) -> "ValidationResult": + """Record an error-level issue only if `check` is True. + + Args: + check: Condition that, when True, causes the issue to be recorded. + message: Description of the problem. + subject: The classifier instance the issue refers to. + + Returns: + ValidationResult: This instance, to allow chaining. + """ if check: self.issues.add(Issue(IssueSeverity.ERROR, message, subject)) return self - def __str__(self): + def __str__(self) -> str: return f"ValidationResult({', '.join(str(issue) for issue in self.issues)})" def __bool__(self) -> bool: diff --git a/src/lionweb/utils/validator.py b/src/lionweb/utils/validator.py index 5941f92..0dabb8b 100644 --- a/src/lionweb/utils/validator.py +++ b/src/lionweb/utils/validator.py @@ -2,9 +2,18 @@ class Validator(ABC): + """Base class for objects that can validate an element and report issues.""" + @abstractmethod def validate(self, element): - """Abstract method to validate an element.""" + """Validate the given element. + + Args: + element: The element to validate. + + Returns: + ValidationResult: The result of the validation, including any issues found. + """ ... def is_valid(self, element) -> bool: From d1d953073411d39af76573e45f2e21f74ae05a14 Mon Sep 17 00:00:00 2001 From: ftomassetti Date: Sun, 7 Jun 2026 10:48:07 +0200 Subject: [PATCH 3/7] Enhance type hints, refactor to leverage Python 3.10+ features, and update docstrings across multiple modules for clarity and consistency. --- src/lionweb/generation/base_generator.py | 8 ++ .../generation/deserializer_generation.py | 18 +++- src/lionweb/generation/language_generation.py | 53 +++++++---- .../generation/node_classes_generation.py | 92 ++++++++++++------- src/lionweb/presentation/show_nodes.py | 21 ++++- src/lionweb/self/lioncore.py | 71 ++++++++++++-- .../serialization/abstract_serialization.py | 81 ++++++++++++++-- .../serialization/json_serialization.py | 4 +- .../serialization/map_based_resolver.py | 20 ++-- .../primitives_values_serialization.py | 78 +++++++++++++--- .../serialization/protobuf_serialization.py | 5 + .../serialization/serialization_utils.py | 5 +- 12 files changed, 366 insertions(+), 90 deletions(-) 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/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/node_classes_generation.py b/src/lionweb/generation/node_classes_generation.py index caba2a4..71608f5 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,37 @@ 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/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 = """