Skip to content

Commit 01bb654

Browse files
authored
Merge pull request #15 from LionWeb-io/feature/language-factory-improvements
LanguageFactory: declaration order, concept relations, elements of other languages
2 parents 590fbe0 + a17f8dc commit 01bb654

4 files changed

Lines changed: 229 additions & 59 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,28 @@
22

33
All notable changes to this project will be documented in this file.
44

5+
## 0.4.6
6+
7+
### Added
8+
9+
- `LanguageFactory.concept` accepts `extends`, `implements`, `abstract` and `partition`;
10+
`LanguageFactory.annotation` accepts `extends` and `implements`.
11+
- `LanguageFactory` accepts `dependencies`, added to the built language.
12+
- Types, extended and implemented classifiers passed to the factories can be elements of
13+
other languages (for example `LionCoreBuiltins.get_node()` or a concept of a language
14+
the new one depends on). Before, they were looked up by name in the language being
15+
built. A factory of another `LanguageFactory` is rejected with a clear error.
16+
17+
### Fixed
18+
19+
- `LanguageFactory.build` creates the elements in the order in which they are declared.
20+
Before, it created all primitive types, then all enumerations, then all classifiers.
21+
- `set_extends` on a concept factory was ignored.
22+
23+
### Changed
24+
25+
- `ClassifierFactory.populate` takes the map of the built elements.
26+
527
## 0.4.5
628

729
### Fixed

‎src/lionweb/language/definition.py‎

Lines changed: 111 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from .enumeration_literal import EnumerationLiteral
1414
from .interface import Interface
1515
from .language import Language
16+
from .language_entity import LanguageEntity
1617
from .primitive_type import PrimitiveType
1718
from .property import Property
1819
from .reference import Reference
@@ -79,14 +80,22 @@ class ClassifierFactory:
7980
and metadata through a fluent interface. The supported classifier types include
8081
Concept, Interface, and Annotation. The factory ensures proper linking between
8182
classifiers and their features, leveraging optional and multiple configurations for
82-
flexibility.
83+
flexibility. Properties, references and containments are each created in the order in
84+
which they are declared.
85+
86+
Types, extended and implemented classifiers can be factories of the same
87+
LanguageFactory or already built elements, including elements of other languages.
8388
8489
Attributes:
8590
type: The type of the classifier (one of "Concept", "Interface", "Annotation").
8691
name: The name of the classifier.
8792
id: A unique identifier for the classifier.
8893
key: A unique key for identifying the classifier.
89-
extends: A list of other ClassifierFactory or Classifier objects that this classifier extends.
94+
extends: The classifiers this classifier extends: the extended interfaces of an
95+
Interface, or at most one extended Concept or Annotation.
96+
implements: The interfaces implemented by a Concept or an Annotation.
97+
abstract: Whether a Concept is abstract.
98+
partition: Whether a Concept is a partition.
9099
"""
91100

92101
def __init__(
@@ -95,19 +104,23 @@ def __init__(
95104
name: str,
96105
id: str,
97106
key: str,
98-
extends: list["ClassifierFactory | Classifier"] = [],
107+
extends: list["ClassifierFactory | Classifier"] | None = None,
108+
implements: list["ClassifierFactory | Interface"] | None = None,
109+
abstract: bool = False,
110+
partition: bool = False,
99111
):
100112
self.type = type
101113
self.name = name
102-
self.abstract = False
103-
self.partition = False
114+
self.abstract = abstract
115+
self.partition = partition
104116
self.id = id
105117
self.key = key
106118
self.properties: list[PropertyData] = []
107119
self.references: list[LinkData] = []
108120
self.containments: list[LinkData] = []
109121
self.annotates: Classifier | ClassifierFactory | None = None
110-
self.extends = extends
122+
self.extends: list[ClassifierFactory | Classifier] = list(extends or [])
123+
self.implements: list[ClassifierFactory | Interface] = list(implements or [])
111124

112125
def property(
113126
self,
@@ -150,7 +163,7 @@ def reference(
150163
def containment(
151164
self,
152165
name: str,
153-
type: "ClassifierFactory",
166+
type: "ClassifierFactory | Classifier",
154167
multiplicity: Multiplicity = Multiplicity.REQUIRED,
155168
id: str | None = None,
156169
key: str | None = None,
@@ -171,30 +184,26 @@ def populate(
171184
classifier: Classifier,
172185
id_calculator: Callable[[str | None, str], str],
173186
key_calculator: Callable[[str | None, str], str],
187+
built: "dict[EntityFactory, LanguageEntity]",
174188
):
175-
language = classifier.language
176-
assert language is not None
189+
"""Add the features and the relations to other classifiers to `classifier`.
190+
191+
Args:
192+
classifier: The classifier built from this factory.
193+
id_calculator: Calculates the id of features without an explicit one.
194+
key_calculator: Calculates the key of features without an explicit one.
195+
built: The elements built so far, by the factory that defined them.
196+
"""
177197
for property_data in self.properties:
178198
property = Property(
179199
lion_web_version=classifier.lion_web_version,
180-
name=property_data.get("name"),
200+
name=property_data["name"],
181201
container=classifier,
182202
id=property_data["id"] or id_calculator(classifier.id, property_data["name"]),
183203
key=property_data["key"] or key_calculator(classifier.key, property_data["name"]),
184204
)
185205
property.set_optional(not property_data["multiplicity"].value["required"])
186-
property_type = property_data["type"]
187-
if isinstance(property_type, DataType):
188-
type = property_type
189-
else:
190-
if isinstance(property_type, PrimitiveTypeFactory):
191-
type_name = property_type.name
192-
elif isinstance(property_type, EnumerationTypeFactory):
193-
type_name = property_type.name
194-
type = language.require_data_type_by_name(type_name)
195-
if type is None:
196-
raise ValueError(f"Type {type_name} not found")
197-
property.type = type
206+
property.type = cast(DataType, _resolve(property_data["type"], built))
198207
classifier.add_feature(property)
199208
for data in self.references:
200209
reference = Reference(
@@ -206,11 +215,7 @@ def populate(
206215
)
207216
reference.set_optional(not data["multiplicity"].value["required"])
208217
reference.set_multiple(data["multiplicity"].value["many"])
209-
type_name = cast(str, data["type"].name)
210-
link_type = language.require_classifier_by_name(type_name)
211-
if link_type is None:
212-
raise ValueError(f"Type {type_name} not found")
213-
reference.set_type(link_type)
218+
reference.set_type(cast(Classifier, _resolve(data["type"], built)))
214219
classifier.add_feature(reference)
215220
for data in self.containments:
216221
containment = Containment(
@@ -222,25 +227,27 @@ def populate(
222227
)
223228
containment.set_optional(not data["multiplicity"].value["required"])
224229
containment.set_multiple(data["multiplicity"].value["many"])
225-
type_name = cast(str, data["type"].name)
226-
link_type = language.require_classifier_by_name(type_name)
227-
if link_type is None:
228-
raise ValueError(f"Type {type_name} not found")
229-
containment.set_type(link_type)
230+
containment.set_type(cast(Classifier, _resolve(data["type"], built)))
230231
classifier.add_feature(containment)
231-
if isinstance(classifier, Annotation):
232-
if isinstance(self.annotates, ClassifierFactory):
233-
classifier.annotates = language.require_classifier_by_name(self.annotates.name)
234-
elif isinstance(self.annotates, Classifier):
235-
classifier.annotates = self.annotates
232+
if isinstance(classifier, Concept):
233+
if len(self.extends) > 1:
234+
raise ValueError(f"Concept {self.name} can extend at most one concept")
235+
for extended in self.extends:
236+
classifier.set_extended_concept(cast(Concept, _resolve(extended, built)))
237+
for implemented in self.implements:
238+
classifier.add_implemented_interface(cast(Interface, _resolve(implemented, built)))
239+
elif isinstance(classifier, Annotation):
240+
if self.annotates is not None:
241+
classifier.annotates = cast(Classifier, _resolve(self.annotates, built))
242+
if len(self.extends) > 1:
243+
raise ValueError(f"Annotation {self.name} can extend at most one annotation")
244+
for extended in self.extends:
245+
classifier.extended_annotation = cast(Annotation, _resolve(extended, built))
246+
for implemented in self.implements:
247+
classifier.add_implemented_interface(cast(Interface, _resolve(implemented, built)))
236248
elif isinstance(classifier, Interface):
237-
for extends in self.extends:
238-
if isinstance(extends, ClassifierFactory):
239-
classifier.add_extended_interface(
240-
language.require_interface_by_name(extends.name)
241-
)
242-
elif isinstance(extends, Classifier):
243-
classifier.add_extended_interface(cast(Interface, extends))
249+
for extended in self.extends:
250+
classifier.add_extended_interface(cast(Interface, _resolve(extended, built)))
244251

245252
def build(self, language: Language) -> "Classifier":
246253
match self.type:
@@ -343,6 +350,23 @@ def build(
343350
return enumeration
344351

345352

353+
EntityFactory = ClassifierFactory | PrimitiveTypeFactory | EnumerationTypeFactory
354+
355+
356+
def _resolve(
357+
element: "EntityFactory | LanguageEntity", built: "dict[EntityFactory, LanguageEntity]"
358+
) -> LanguageEntity:
359+
"""Return the element built from a factory, or the element itself if already built."""
360+
if isinstance(element, ClassifierFactory | PrimitiveTypeFactory | EnumerationTypeFactory):
361+
if element not in built:
362+
raise ValueError(
363+
f"{element.name} is defined by another LanguageFactory: "
364+
"use the element built by that factory instead"
365+
)
366+
return built[element]
367+
return element
368+
369+
346370
class LanguageFactory:
347371
"""
348372
Represents a factory for creating and managing languages and their components.
@@ -387,6 +411,7 @@ def __init__(
387411
key: str | None = None,
388412
id_calculator: Callable[[str | None, str], str] | None = None,
389413
key_calculator: Callable[[str | None, str], str] | None = None,
414+
dependencies: list[Language] | None = None,
390415
):
391416
"""
392417
Initializes a new instance of the class with provided parameters and default values where
@@ -409,6 +434,7 @@ def __init__(
409434
key_calculator (Optional[Callable[[Optional[str], str], str]]): A function to calculate
410435
the instance key. Defaults to a lambda function to generate key based on parent key
411436
and name if not provided.
437+
dependencies (Optional[list[Language]]): The languages this language depends on.
412438
413439
Attributes:
414440
lw_version (LionWebVersion): The LionWeb version associated with the instance.
@@ -434,6 +460,8 @@ def __init__(
434460
)
435461
self.id = id or self.id_calculator(None, name)
436462
self.key = key or self.key_calculator(None, name)
463+
self.dependencies: list[Language] = list(dependencies or [])
464+
self.entities: list[EntityFactory] = []
437465
self.classifiers: list[ClassifierFactory] = []
438466
self.primitive_types: list[PrimitiveTypeFactory] = []
439467
self.enumerations: list[EnumerationTypeFactory] = []
@@ -445,8 +473,8 @@ def build(self) -> Language:
445473
This function is responsible for creating a `Language` instance based on the
446474
attributes of the current object. It initializes the language with relevant
447475
details such as its name, id, key, version, and lion web version. Additionally,
448-
it iterates over primitive types, enumerations, and classifiers to build and
449-
populate their corresponding components in the language.
476+
it builds the elements in the order in which they were declared, then populates
477+
the classifiers.
450478
451479
Returns:
452480
Language: The constructed `Language` object.
@@ -459,37 +487,51 @@ def build(self) -> Language:
459487
lion_web_version=self.lw_version,
460488
)
461489

462-
for primitive_type in self.primitive_types:
463-
primitive_type.build(language)
464-
for enumeration in self.enumerations:
465-
enumeration.build(language, self.id_calculator, self.key_calculator)
490+
for dependency in self.dependencies:
491+
language.add_dependency(dependency)
466492

467-
classifiers = {}
468-
for classifier in self.classifiers:
469-
classifiers[classifier] = classifier.build(language)
493+
built: dict[EntityFactory, LanguageEntity] = {}
494+
for entity in self.entities:
495+
if isinstance(entity, EnumerationTypeFactory):
496+
built[entity] = entity.build(language, self.id_calculator, self.key_calculator)
497+
else:
498+
built[entity] = entity.build(language)
470499
for classifier in self.classifiers:
471-
classifier.populate(classifiers[classifier], self.id_calculator, self.key_calculator)
500+
classifier.populate(
501+
cast(Classifier, built[classifier]), self.id_calculator, self.key_calculator, built
502+
)
472503

473504
return language
474505

475506
def concept(
476-
self, name: str, id: str | None = None, key: str | None = None
507+
self,
508+
name: str,
509+
id: str | None = None,
510+
key: str | None = None,
511+
extends: ClassifierFactory | Concept | None = None,
512+
implements: list[ClassifierFactory | Interface] | None = None,
513+
abstract: bool = False,
514+
partition: bool = False,
477515
) -> ClassifierFactory:
478516
sub = ClassifierFactory(
479517
"Concept",
480518
name,
481519
id=id or self.id_calculator(self.id, name),
482520
key=key or self.key_calculator(self.key, name),
521+
extends=[extends] if extends is not None else None,
522+
implements=implements,
523+
abstract=abstract,
524+
partition=partition,
483525
)
484-
self.classifiers.append(sub)
526+
self._add_classifier(sub)
485527
return sub
486528

487529
def interface(
488530
self,
489531
name: str,
490532
id: str | None = None,
491533
key: str | None = None,
492-
extends: list[ClassifierFactory | Classifier] = [],
534+
extends: list[ClassifierFactory | Classifier] | None = None,
493535
) -> ClassifierFactory:
494536
sub = ClassifierFactory(
495537
"Interface",
@@ -498,7 +540,7 @@ def interface(
498540
key=key or self.key_calculator(self.key, name),
499541
extends=extends,
500542
)
501-
self.classifiers.append(sub)
543+
self._add_classifier(sub)
502544
return sub
503545

504546
def annotation(
@@ -507,15 +549,19 @@ def annotation(
507549
annotates: ClassifierFactory | Classifier,
508550
id: str | None = None,
509551
key: str | None = None,
552+
extends: ClassifierFactory | Annotation | None = None,
553+
implements: list[ClassifierFactory | Interface] | None = None,
510554
) -> ClassifierFactory:
511555
sub = ClassifierFactory(
512556
"Annotation",
513557
name,
514558
id=id or self.id_calculator(self.id, name),
515559
key=key or self.key_calculator(self.key, name),
560+
extends=[extends] if extends is not None else None,
561+
implements=implements,
516562
)
517563
sub.set_annotates(annotates)
518-
self.classifiers.append(sub)
564+
self._add_classifier(sub)
519565
return sub
520566

521567
def primitive_type(
@@ -527,6 +573,7 @@ def primitive_type(
527573
key=key or self.key_calculator(self.key, name),
528574
)
529575
self.primitive_types.append(sub)
576+
self.entities.append(sub)
530577
return sub
531578

532579
def enumeration(
@@ -543,4 +590,9 @@ def enumeration(
543590
literals=literals,
544591
)
545592
self.enumerations.append(sub)
593+
self.entities.append(sub)
546594
return sub
595+
596+
def _add_classifier(self, classifier: ClassifierFactory) -> None:
597+
self.classifiers.append(classifier)
598+
self.entities.append(classifier)

‎tests/generation/test_language_generation.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ def get_language() ->Language:
5555
my_other_concept.abstract = False
5656
my_other_concept.partition = False
5757
language.add_element(my_other_concept)
58+
my_other_concept.set_extended_concept(my_concept)
5859
return language
5960
6061

0 commit comments

Comments
 (0)