flamapy-fm 2.9.0.dev3__tar.gz → 2.9.0.dev4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/PKG-INFO +4 -4
  2. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/models/clause_set.py +5 -0
  3. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/clafer_writer.py +12 -3
  4. flamapy_fm-2.9.0.dev4/flamapy/metamodels/fm_metamodel/transformations/constraint_support.py +73 -0
  5. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/featureide_writer.py +13 -1
  6. flamapy_fm-2.9.0.dev4/flamapy/metamodels/fm_metamodel/transformations/flat_fm.py +207 -0
  7. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/json_writer.py +10 -1
  8. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/pl_writer.py +10 -1
  9. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/feature_cardinality_refactoring_paper.py +2 -1
  10. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/splot_writer.py +14 -1
  11. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/uvl_reader.py +26 -4
  12. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy_fm.egg-info/PKG-INFO +4 -4
  13. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy_fm.egg-info/SOURCES.txt +1 -0
  14. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy_fm.egg-info/requires.txt +3 -3
  15. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/pyproject.toml +4 -4
  16. flamapy_fm-2.9.0.dev3/flamapy/metamodels/fm_metamodel/transformations/flat_fm.py +0 -140
  17. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/LICENSE +0 -0
  18. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/README.md +0 -0
  19. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/__init__.py +0 -0
  20. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/models/__init__.py +0 -0
  21. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/models/feature_model.py +0 -0
  22. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/__init__.py +0 -0
  23. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_atomic_sets.py +0 -0
  24. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_average_branching_factor.py +0 -0
  25. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_core_features.py +0 -0
  26. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_count_leafs.py +0 -0
  27. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_estimated_configurations_number.py +0 -0
  28. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_feature_ancestors.py +0 -0
  29. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_generate_random_attribute.py +0 -0
  30. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_generate_random_feature_model.py +0 -0
  31. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_language_level.py +0 -0
  32. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_leaf_features.py +0 -0
  33. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_max_depth_tree.py +0 -0
  34. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_metrics.py +0 -0
  35. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/fm_variation_points.py +0 -0
  36. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/interfaces/__init__.py +0 -0
  37. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/operations/interfaces/variation_points.py +0 -0
  38. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/__init__.py +0 -0
  39. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/_uvl_lexer.py +0 -0
  40. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/afm_reader.py +0 -0
  41. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/afm_writer.py +0 -0
  42. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/featureide_reader.py +0 -0
  43. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/fm_secure_features_names.py +0 -0
  44. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/glencoe_reader.py +0 -0
  45. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/glencoe_writer.py +0 -0
  46. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/group_support.py +0 -0
  47. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/json_reader.py +0 -0
  48. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/pysat_to_fm.py +0 -0
  49. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/__init__.py +0 -0
  50. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/cardinality_group_refactoring.py +0 -0
  51. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/commitment_feature.py +0 -0
  52. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/deletion_feature.py +0 -0
  53. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/feature_cardinality_refactoring.py +0 -0
  54. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/multiple_group_decomposition_refactoring.py +0 -0
  55. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/mutex_group_refactoring.py +0 -0
  56. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/or_mandatory_refactoring.py +0 -0
  57. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/pseudocomplex_constraint_refactoring.py +0 -0
  58. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/refactoring_exception.py +0 -0
  59. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/refactoring_interface.py +0 -0
  60. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/strictcomplex_constraint_refactoring.py +0 -0
  61. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/refactorings/xor_mandatory_refactoring.py +0 -0
  62. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/uvl_writer.py +0 -0
  63. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/xml_reader.py +0 -0
  64. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy/metamodels/fm_metamodel/transformations/xml_writer.py +0 -0
  65. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy_fm.egg-info/dependency_links.txt +0 -0
  66. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy_fm.egg-info/entry_points.txt +0 -0
  67. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/flamapy_fm.egg-info/top_level.txt +0 -0
  68. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/setup.cfg +0 -0
  69. {flamapy_fm-2.9.0.dev3 → flamapy_fm-2.9.0.dev4}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flamapy-fm
3
- Version: 2.9.0.dev3
3
+ Version: 2.9.0.dev4
4
4
  Summary: flamapy-fm is a plugin to Flamapy module
5
5
  Author-email: Flamapy <flamapy@us.es>
6
6
  License-Expression: GPL-3.0-or-later
@@ -8,7 +8,7 @@ Project-URL: Homepage, https://github.com/flamapy/fm_metamodel
8
8
  Requires-Python: >=3.11
9
9
  Description-Content-Type: text/markdown
10
10
  License-File: LICENSE
11
- Requires-Dist: flamapy-fw~=2.9.0.dev3
11
+ Requires-Dist: flamapy-fw~=2.9.0.dev4
12
12
  Requires-Dist: uvlparser~=2.5.0
13
13
  Requires-Dist: afmparser~=1.0.3
14
14
  Provides-Extra: dev
@@ -20,8 +20,8 @@ Requires-Dist: coverage; extra == "dev"
20
20
  Requires-Dist: antlr4-tools; extra == "dev"
21
21
  Provides-Extra: test
22
22
  Requires-Dist: pytest; extra == "test"
23
- Requires-Dist: flamapy-sat~=2.9.0.dev3; extra == "test"
24
- Requires-Dist: flamapy-bdd~=2.9.0.dev3; extra == "test"
23
+ Requires-Dist: flamapy-sat~=2.9.0.dev4; extra == "test"
24
+ Requires-Dist: flamapy-bdd~=2.9.0.dev4; extra == "test"
25
25
  Dynamic: license-file
26
26
 
27
27
  # flamapy-fm
@@ -145,6 +145,11 @@ class _Encoder:
145
145
  self.clause_groups: list[tuple[str, list[list[int]]]] = []
146
146
 
147
147
  def encode(self, feature_model: FeatureModel) -> ClauseSet:
148
+ # Only the logical constraints are encoded; say so when others are left out (#5).
149
+ from flamapy.metamodels.fm_metamodel.transformations.constraint_support import ( # noqa: PLC0415 pylint: disable=import-outside-toplevel,cyclic-import
150
+ warn_non_boolean_constraints,
151
+ )
152
+ warn_non_boolean_constraints(feature_model, 'CNF encoding', stacklevel=5)
148
153
  for feature in feature_model.get_features():
149
154
  self._add_feature(feature)
150
155
  self._add_root(feature_model.root)
@@ -14,6 +14,9 @@ from flamapy.metamodels.fm_metamodel.transformations.fm_secure_features_names im
14
14
  prefix_if_not_letter,
15
15
  secure_name,
16
16
  )
17
+ from flamapy.metamodels.fm_metamodel.transformations.constraint_support import (
18
+ reject_non_boolean_constraints,
19
+ )
17
20
 
18
21
 
19
22
  ATTRIBUTED_FEATURE = 'AttributedFeature'
@@ -55,8 +58,9 @@ class ClaferWriter(ModelToText):
55
58
  (MultipleGroupDecompositionRefactoring), which adds abstract features but keeps the
56
59
  configurations of the original features.
57
60
 
58
- Only the logical constraints of the model are written; arithmetic and other non-Boolean
59
- constraints are omitted (as in PLWriter and FeatureIDEWriter).
61
+ Only the logical constraints of the model are written; a model with arithmetic or other
62
+ non-Boolean constraints is rejected (as in PLWriter and FeatureIDEWriter), or, with
63
+ ``boolean_only=True``, written without them, with a warning and a comment in the file.
60
64
  """
61
65
 
62
66
  @staticmethod
@@ -64,13 +68,16 @@ class ClaferWriter(ModelToText):
64
68
  return 'txt'
65
69
 
66
70
  def __init__(self, path: str, source_model: FeatureModel,
67
- apply_refactorings: bool = False) -> None:
71
+ apply_refactorings: bool = False, *, boolean_only: bool = False) -> None:
68
72
  self.path = path
69
73
  self.source_model = source_model
70
74
  self.apply_refactorings = apply_refactorings
75
+ self.boolean_only = boolean_only
71
76
  self.mapping_names: dict[str, str] = {}
72
77
 
73
78
  def transform(self) -> str:
79
+ note = reject_non_boolean_constraints(self.source_model, 'The Clafer writer',
80
+ self.boolean_only)
74
81
  model = prepare_model(self.source_model, 'Clafer', [mixed_decomposition],
75
82
  [decompose_groups], self.apply_refactorings)
76
83
  secure_names = FMSecureFeaturesNames(model)
@@ -79,6 +86,8 @@ class ClaferWriter(ModelToText):
79
86
  feature_model = secure_names.transform()
80
87
  self.mapping_names = secure_names.mapping_names
81
88
  clafer_str = fm_to_clafer(feature_model)
89
+ if note:
90
+ clafer_str = f'// {note}\n{clafer_str}'
82
91
  if self.path is not None:
83
92
  with open(self.path, 'w', encoding='utf8') as file:
84
93
  file.write(clafer_str)
@@ -0,0 +1,73 @@
1
+ """Constraints that the Boolean output formats and encodings cannot represent.
2
+
3
+ SPLOT, FeatureIDE XML, Clafer, the propositional-logic writer and the JSON serialisation write
4
+ only the Boolean (logical) constraints of a model, and the CNF and BDD encodings only reason over
5
+ them. Leaving the arithmetic, aggregate or string constraints out silently would describe a
6
+ different model, so the writers reject such models and the encodings warn (flamapy/flamapy#5).
7
+ A writer called with ``boolean_only=True`` writes the Boolean part of the model instead, with a
8
+ warning and, where the format has comments, a note in the file.
9
+ """
10
+ import warnings
11
+
12
+ from flamapy.core.exceptions import FlamaException
13
+ from flamapy.metamodels.fm_metamodel.models import Constraint, FeatureModel
14
+
15
+ MAX_SHOWN = 5 # constraints listed in a message
16
+
17
+
18
+ def non_boolean_constraints(feature_model: FeatureModel) -> list[Constraint]:
19
+ """The constraints of the model that are not Boolean (arithmetic, aggregate, string)."""
20
+ return [ctc for ctc in feature_model.get_constraints() if not ctc.is_logical_constraint()]
21
+
22
+
23
+ def describe_constraints(constraints: list[Constraint]) -> str:
24
+ # Local import: uvl_writer imports from this package.
25
+ from flamapy.metamodels.fm_metamodel.transformations.uvl_writer import ( # noqa: PLC0415 pylint: disable=import-outside-toplevel
26
+ UVLWriter,
27
+ )
28
+ shown = [UVLWriter.serialize_constraint(ctc) for ctc in constraints[:MAX_SHOWN]]
29
+ more = f' and {len(constraints) - MAX_SHOWN} more' if len(constraints) > MAX_SHOWN else ''
30
+ return '; '.join(shown) + more
31
+
32
+
33
+ def reject_non_boolean_constraints(feature_model: FeatureModel, format_name: str,
34
+ boolean_only: bool = False) -> str:
35
+ """Raise if the model has constraints that `format_name` cannot represent.
36
+
37
+ With `boolean_only`, warn instead, and return a note naming the constraints left out (an
38
+ empty string when there are none) for the writer to put in the file where it can.
39
+ """
40
+ unsupported = non_boolean_constraints(feature_model)
41
+ if not unsupported:
42
+ return ''
43
+ described = describe_constraints(unsupported)
44
+ if not boolean_only:
45
+ raise FlamaException(
46
+ f'{format_name} cannot represent the {len(unsupported)} non-Boolean constraint(s) '
47
+ f'of the model ({described}); writing the model without them would describe a '
48
+ 'different model. The UVL writer keeps them; boolean_only=True writes the Boolean '
49
+ 'part of the model.')
50
+ warnings.warn(
51
+ f'{format_name} writes only the Boolean part of the model: its {len(unsupported)} '
52
+ f'non-Boolean constraint(s) are left out ({described}).', UserWarning, stacklevel=3)
53
+ return (f'Boolean part of the model only: {len(unsupported)} non-Boolean constraint(s) '
54
+ f'left out ({described}).')
55
+
56
+
57
+ def xml_comment(text: str) -> str:
58
+ """`text` made safe for an XML comment, which cannot contain '--'."""
59
+ while '--' in text:
60
+ text = text.replace('--', '- -')
61
+ return text
62
+
63
+
64
+ def warn_non_boolean_constraints(feature_model: FeatureModel, encoding: str,
65
+ stacklevel: int = 3) -> None:
66
+ """Warn that `encoding` leaves out the non-Boolean constraints of the model, if any."""
67
+ unsupported = non_boolean_constraints(feature_model)
68
+ if unsupported:
69
+ warnings.warn(
70
+ f'The {encoding} leaves out the {len(unsupported)} non-Boolean constraint(s) of the '
71
+ f'model ({describe_constraints(unsupported)}), so results computed on it are not '
72
+ 'exact for this model. The Z3 backend reasons over them.',
73
+ UserWarning, stacklevel=stacklevel)
@@ -19,6 +19,10 @@ from flamapy.metamodels.fm_metamodel.transformations.group_support import (
19
19
  refactor_cardinality_groups,
20
20
  refactor_mutex_groups,
21
21
  )
22
+ from flamapy.metamodels.fm_metamodel.transformations.constraint_support import (
23
+ reject_non_boolean_constraints,
24
+ xml_comment,
25
+ )
22
26
 
23
27
 
24
28
 
@@ -47,12 +51,18 @@ class FeatureIDEWriter(ModelToText):
47
51
  return '.xml'
48
52
 
49
53
  def __init__(self, path: str, source_model: FeatureModel,
50
- apply_refactorings: bool = False) -> None:
54
+ apply_refactorings: bool = False, *, boolean_only: bool = False) -> None:
55
+ """With ``boolean_only=True`` a model with arithmetic, aggregate or string constraints is
56
+ written without them, with a warning and a comment in the file; by default it is
57
+ rejected (flamapy/flamapy#5)."""
51
58
  self._path = path
52
59
  self._source_model = source_model
53
60
  self.apply_refactorings = apply_refactorings
61
+ self.boolean_only = boolean_only
54
62
 
55
63
  def transform(self) -> str:
64
+ note = reject_non_boolean_constraints(self._source_model, 'FeatureIDE XML',
65
+ self.boolean_only)
56
66
  model = prepare_model(self._source_model, 'FeatureIDE XML',
57
67
  [mixed_decomposition, mutex_group, cardinality_group],
58
68
  [decompose_groups, refactor_mutex_groups,
@@ -61,6 +71,8 @@ class FeatureIDEWriter(ModelToText):
61
71
  fm_tree = _to_featureidexml(model).getroot()
62
72
  if fm_tree is None:
63
73
  raise ValueError("The FeatureIDE XML tree has no root element.")
74
+ if note:
75
+ fm_tree.insert(0, ElementTree.Comment(f' {xml_comment(note)} '))
64
76
  xml_str = ElementTree.tostring(fm_tree,
65
77
  encoding='UTF-8',
66
78
  method='xml',
@@ -0,0 +1,207 @@
1
+ import copy
2
+ from collections import Counter
3
+ from typing import cast
4
+
5
+ from flamapy.core.exceptions import FlamaException
6
+ from flamapy.core.transformations import ModelToModel
7
+ from flamapy.core.models import VariabilityModel, AST
8
+ from flamapy.core.models.ast import ASTOperation, Node
9
+
10
+ from flamapy.metamodels.fm_metamodel.models import FeatureModel, Feature
11
+
12
+
13
+ class FlatFM(ModelToModel):
14
+ """Given a feature model with imports information, it returns a flat feature model with
15
+ all references resolved.
16
+
17
+ That is, it copies all imported feature models in only one feature model ready to be analyzed.
18
+ """
19
+
20
+ @staticmethod
21
+ def get_source_extension() -> str:
22
+ return 'fm'
23
+
24
+ @staticmethod
25
+ def get_destination_extension() -> str:
26
+ return 'fm'
27
+
28
+ def __init__(self, source_model: VariabilityModel) -> None:
29
+ self.feature_model = cast(FeatureModel, source_model)
30
+ self._maintain_namespaces: bool = True
31
+
32
+ def set_maintain_namespaces(self, maintain_namespaces: bool) -> None:
33
+ """Set whether to maintain the namespaces of the imported features."""
34
+ self._maintain_namespaces = maintain_namespaces
35
+
36
+ def transform(self) -> FeatureModel:
37
+ new_feature_model = copy.deepcopy(self.feature_model)
38
+ imported_models = get_imported_models_by_root(new_feature_model)
39
+ if not self._maintain_namespaces:
40
+ for ctc in new_feature_model.ctcs:
41
+ remove_namespace_constraint(ctc.ast, new_feature_model)
42
+ # A model imported once but referenced under several parents gives one instance per
43
+ # reference; their names are qualified with the parent's name ('Three.S.Spirits',
44
+ # 'Two.S.Spirits') so that the instances are independent (flamapy/fm_metamodel#110).
45
+ repeated = _repeated_references(new_feature_model.root)
46
+ if self._maintain_namespaces:
47
+ _reject_ambiguous_references(new_feature_model, repeated)
48
+ used_namespaces: set[str] = set()
49
+ features = [new_feature_model.root]
50
+ while features:
51
+ feature = features.pop()
52
+ if feature.reference is not None:
53
+ self._expand_reference(feature, new_feature_model, imported_models,
54
+ repeated, used_namespaces)
55
+ # The copy's own references are now namespaced per instance; count them so
56
+ # that one referenced twice inside it is told apart too.
57
+ repeated |= _repeated_references(feature)
58
+ features.extend(feature.get_children())
59
+ new_feature_model.imports = {} # Clear imports as they are not needed in the flat model
60
+ new_feature_model.alias_namespace = {} # Clear alias namespace as it is not needed in
61
+ return new_feature_model
62
+
63
+ def _expand_reference(self,
64
+ feature: Feature, new_feature_model: FeatureModel,
65
+ imported_models: dict[int, FeatureModel], repeated: set[str],
66
+ used_namespaces: set[str]) -> None:
67
+ """Replace a feature that references an imported model by a copy of that model."""
68
+ # Every reference gets its own copy of the imported model: the same model may
69
+ # be referenced more than once (under one alias or several), and each
70
+ # reference is a separate subtree with its own namespace.
71
+ imported_fm = copy.deepcopy(imported_models[id(feature.reference)])
72
+ imported_models.update(get_imported_models_by_root(imported_fm))
73
+ reference = imported_fm.root
74
+ # Copy the feature's attributes and relations from the referenced feature
75
+ feature.relations = reference.relations
76
+ for relation in feature.relations:
77
+ relation.parent = feature
78
+ for child in relation.children:
79
+ child.parent = feature
80
+ feature.attributes.extend(reference.attributes)
81
+ # Process attribute constraints
82
+ # (they are also in the imported model's ctcs, which are processed below)
83
+ feature.constraints_attributes.extend(reference.constraints_attributes)
84
+ if not self._maintain_namespaces:
85
+ feature.name = reference.name
86
+ for ctc in imported_fm.ctcs:
87
+ remove_namespace_constraint(ctc.ast, imported_fm)
88
+ else:
89
+ namespace = '.'.join(feature.name.split('.')[:-1])
90
+ if feature.name in repeated:
91
+ namespace = _instance_namespace(feature, namespace, used_namespaces)
92
+ feature.name = f'{namespace}.{feature.name.split(".")[-1]}'
93
+ put_namespace_to_features(reference, namespace)
94
+ for ctc in imported_fm.ctcs:
95
+ put_namespace_to_constraint(ctc.ast, namespace)
96
+ # Add the constraints of the imported model (nested imports are reached when
97
+ # their referencing features are visited)
98
+ new_feature_model.ctcs.extend(imported_fm.ctcs)
99
+ feature.reference = None # Clear reference after copying
100
+
101
+
102
+ def _repeated_references(root: Feature) -> set[str]:
103
+ """Names of the features under `root` that reference an imported model, and that more than
104
+ one feature shares (several references to the same import)."""
105
+ counts = Counter(f.name for f in _all_features(root) if f.reference is not None)
106
+ return {name for name, count in counts.items() if count > 1}
107
+
108
+
109
+ def _all_features(root: Feature) -> list[Feature]:
110
+ features, stack = [], [root]
111
+ while stack:
112
+ feature = stack.pop()
113
+ features.append(feature)
114
+ stack.extend(feature.get_children())
115
+ return features
116
+
117
+
118
+ def _instance_namespace(feature: Feature, namespace: str, used: set[str]) -> str:
119
+ """A namespace for one of several references to the same imported model: the import
120
+ namespace qualified with the name of the referencing feature's parent, and numbered if
121
+ two references share the parent as well."""
122
+ parent = feature.get_parent()
123
+ base = f'{parent.name}.{namespace}' if parent is not None else namespace
124
+ candidate, index = base, 2
125
+ while candidate in used:
126
+ candidate, index = f'{base}{index}', index + 1
127
+ used.add(candidate)
128
+ return candidate
129
+
130
+
131
+ def _reject_ambiguous_references(feature_model: FeatureModel, repeated: set[str]) -> None:
132
+ """A constraint of the importing model that names a feature of a model referenced more
133
+ than once cannot tell which instance it means; say so instead of guessing."""
134
+ namespaces = {'.'.join(name.split('.')[:-1]) for name in repeated}
135
+ for ctc in feature_model.ctcs:
136
+ for node in get_feature_terms(ctc.ast):
137
+ namespace = '.'.join(str(node.data).split('.')[:-1])
138
+ if namespace in namespaces:
139
+ raise FlamaException(
140
+ f'The constraint {ctc.name} refers to {node.data}, but the model imported '
141
+ f'as {namespace} is referenced more than once, so it has one instance per '
142
+ 'reference and the constraint does not say which one it means. Import the '
143
+ 'model under a separate alias for each reference to tell them apart.')
144
+
145
+
146
+ def put_namespace_to_features(root: Feature, namespace: str) -> None:
147
+ """Put the namespace to the features in the feature model."""
148
+ features = [root]
149
+ while features:
150
+ feature = features.pop()
151
+ feature.name = f'{namespace}.{feature.name}'
152
+ features.extend(feature.get_children())
153
+
154
+
155
+ def get_imported_models_by_root(feature_model: FeatureModel) -> dict[int, FeatureModel]:
156
+ """Return all the (nested) imported models of the feature model, indexed by the id of their
157
+ root feature, which is the object referenced by the importing feature."""
158
+ imported_models = {}
159
+ models = list(feature_model.imports.values())
160
+ while models:
161
+ imported_fm = models.pop()
162
+ imported_models[id(imported_fm.root)] = imported_fm
163
+ models.extend(imported_fm.imports.values())
164
+ return imported_models
165
+
166
+
167
+ def get_feature_terms(ast: AST) -> list[Node]:
168
+ """Return the terms of the constraint that reference a feature (or a Feature.Attribute).
169
+
170
+ Literals are excluded, and so is the attribute name of the sum/avg aggregates
171
+ (e.g., in sum(Price, B) only B is a feature).
172
+ """
173
+ terms = []
174
+ stack = [ast.root]
175
+ while stack:
176
+ node = stack.pop()
177
+ if node is None:
178
+ continue
179
+ if node.data in (ASTOperation.SUM, ASTOperation.AVG):
180
+ stack.append(node.right)
181
+ elif node.is_op():
182
+ stack.extend([node.left, node.right])
183
+ elif (isinstance(node.data, str) and not node.is_literal()
184
+ and not node.data.startswith("'")):
185
+ terms.append(node)
186
+ return terms
187
+
188
+
189
+ def put_namespace_to_constraint(ast: AST, namespace: str) -> None:
190
+ """Put the namespace to the features referenced in the constraint."""
191
+ for node in get_feature_terms(ast):
192
+ node.data = f'{namespace}.{node.data}'
193
+
194
+
195
+ def remove_namespace_constraint(ast: AST, feature_model: FeatureModel) -> None:
196
+ """Remove the import aliases of the features referenced in a constraint of the model."""
197
+ for node in get_feature_terms(ast):
198
+ node.data = remove_namespace(node.data, feature_model)
199
+
200
+
201
+ def remove_namespace(reference: str, feature_model: FeatureModel) -> str:
202
+ """Remove the import alias prefixing the reference, following nested imports
203
+ (e.g., 's.l.Y' -> 'Y', and 's.B.Price' -> 'B.Price')."""
204
+ for alias, namespace in feature_model.alias_namespace.items():
205
+ if reference.startswith(f'{alias}.') and namespace in feature_model.imports:
206
+ return remove_namespace(reference[len(alias) + 1:], feature_model.imports[namespace])
207
+ return reference
@@ -10,6 +10,9 @@ from flamapy.metamodels.fm_metamodel.models import (
10
10
  FeatureModel,
11
11
  Attribute
12
12
  )
13
+ from flamapy.metamodels.fm_metamodel.transformations.constraint_support import (
14
+ reject_non_boolean_constraints,
15
+ )
13
16
 
14
17
 
15
18
  class JSONFeatureType(Enum):
@@ -33,11 +36,17 @@ class JSONWriter(ModelToText):
33
36
  def get_destination_extension() -> str:
34
37
  return 'json'
35
38
 
36
- def __init__(self, path: str, source_model: FeatureModel):
39
+ def __init__(self, path: str, source_model: FeatureModel, *, boolean_only: bool = False):
40
+ """With ``boolean_only=True`` a model with arithmetic, aggregate or string constraints is
41
+ written without them, with a warning (JSON has no comments); by default it is rejected
42
+ (flamapy/flamapy#5)."""
37
43
  self.path = path
38
44
  self.source_model = source_model
45
+ self.boolean_only = boolean_only
39
46
 
40
47
  def transform(self) -> str:
48
+ reject_non_boolean_constraints(self.source_model, 'The JSON serialisation',
49
+ self.boolean_only)
41
50
  json_object = to_json(self.source_model)
42
51
  if self.path is not None:
43
52
  with open(self.path, 'w', encoding='utf8') as file:
@@ -9,6 +9,9 @@ from flamapy.metamodels.fm_metamodel.transformations.fm_secure_features_names im
9
9
  FMSecureFeaturesNames,
10
10
  )
11
11
  from flamapy.metamodels.fm_metamodel.transformations.uvl_writer import xor_as_negated_equivalence
12
+ from flamapy.metamodels.fm_metamodel.transformations.constraint_support import (
13
+ reject_non_boolean_constraints,
14
+ )
12
15
 
13
16
 
14
17
  # Reserved words of the Logic2BDD expression scanner (synExpScanner.lpp).
@@ -54,12 +57,18 @@ class PLWriter(ModelToText):
54
57
  def get_destination_extension() -> str:
55
58
  return 'exp'
56
59
 
57
- def __init__(self, path: str, source_model: FeatureModel):
60
+ def __init__(self, path: str, source_model: FeatureModel, *, boolean_only: bool = False):
61
+ """With ``boolean_only=True`` a model with arithmetic, aggregate or string constraints is
62
+ written without them, with a warning (the format has no comments); by default it is
63
+ rejected (flamapy/flamapy#5)."""
58
64
  self.path: str = path
59
65
  self.source_model: FeatureModel = source_model
66
+ self.boolean_only = boolean_only
60
67
  self.mapping_names: dict[str, str] = {}
61
68
 
62
69
  def transform(self) -> str:
70
+ reject_non_boolean_constraints(self.source_model, 'The propositional-logic format',
71
+ self.boolean_only)
63
72
  secure_names = FMSecureFeaturesNames(self.source_model)
64
73
  secure_names.reserved_names |= PL_KEYWORDS
65
74
  feature_model = secure_names.transform()
@@ -144,7 +144,8 @@ def create_contextual_constraint(context: ContextualConstraintContext) -> None:
144
144
  """Create contextual constraints for the given feature clone."""
145
145
  for constraint in context.feature_model.get_constraints():
146
146
  features_in_constraint = constraint.get_features()
147
- if all(feat in context.features_names_map for feat in features_in_constraint):
147
+ if features_in_constraint and all(feat in context.features_names_map
148
+ for feat in features_in_constraint):
148
149
  # Contextualize constraint for the clone
149
150
  context.ctcs_to_be_removed.add(constraint)
150
151
  new_constraint = contextualize_constraint(context.feature_model,
@@ -6,6 +6,10 @@ from flamapy.metamodels.fm_metamodel.models import (
6
6
  Feature,
7
7
  Constraint
8
8
  )
9
+ from flamapy.metamodels.fm_metamodel.transformations.constraint_support import (
10
+ reject_non_boolean_constraints,
11
+ xml_comment,
12
+ )
9
13
 
10
14
  TAB = '\t'
11
15
 
@@ -16,12 +20,21 @@ class SPLOTWriter(ModelToText):
16
20
  def get_destination_extension() -> str:
17
21
  return 'sxfm'
18
22
 
19
- def __init__(self, path: str, source_model: FeatureModel) -> None:
23
+ def __init__(self, path: str, source_model: FeatureModel, *,
24
+ boolean_only: bool = False) -> None:
25
+ """With ``boolean_only=True`` a model with arithmetic, aggregate or string constraints is
26
+ written without them, with a warning and a note in the file; by default it is rejected
27
+ (flamapy/flamapy#5)."""
20
28
  self.path = path
21
29
  self.source_model = source_model
30
+ self.boolean_only = boolean_only
22
31
 
23
32
  def transform(self) -> str:
33
+ note = reject_non_boolean_constraints(self.source_model, 'SPLOT', self.boolean_only)
24
34
  splot_str = fm_to_splot(self.source_model)
35
+ if note:
36
+ header, rest = splot_str.split('\n', 1)
37
+ splot_str = f'{header}\n<!-- {xml_comment(note)} -->\n{rest}'
25
38
  if self.path is not None:
26
39
  with open(self.path, 'w', encoding='utf8') as file:
27
40
  file.write(splot_str)
@@ -1,5 +1,6 @@
1
1
  import os
2
2
  import logging
3
+ import warnings
3
4
  from typing import Any, Optional, Union
4
5
 
5
6
  from antlr4 import CommonTokenStream, FileStream
@@ -44,7 +45,14 @@ class UVLReader(TextToModel):
44
45
  def get_source_extension() -> str:
45
46
  return "uvl"
46
47
 
47
- def __init__(self, path: str) -> None:
48
+ def __init__(self, path: str, strict: bool = False) -> None:
49
+ """Read the UVL model at `path`.
50
+
51
+ A character the UVL lexer cannot tokenize (e.g. the leading `_` of `_Root_`) is skipped
52
+ with a warning by default, so models that earlier versions read keep reading; with
53
+ `strict=True` it makes the reader fail, as a syntax error of the parser always does.
54
+ """
55
+ self.strict: bool = strict
48
56
  self.path: str = os.sep.join(path.split(os.sep)[:-1])
49
57
  self.file: str = path.rsplit(os.sep, maxsplit=1)[-1]
50
58
  self.namespace: str = ""
@@ -63,13 +71,27 @@ class UVLReader(TextToModel):
63
71
  stream = CommonTokenStream(lexer)
64
72
  parser = UVLPythonParser(stream)
65
73
 
66
- # Attach custom error listener
74
+ # A character the lexer cannot tokenize is reported, not silently skipped: as a
75
+ # warning by default (the model is read without it, as before) and as an error with
76
+ # strict=True. Syntax errors of the parser always make the reader fail.
77
+ lexer_listener = CustomErrorListener()
78
+ lexer.removeErrorListeners()
79
+ lexer.addErrorListener(lexer_listener)
67
80
  error_listener = CustomErrorListener()
68
81
  parser.removeErrorListeners()
69
82
  parser.addErrorListener(error_listener)
70
83
 
71
84
  self.parse_tree = parser.featureModel()
72
85
 
86
+ if lexer_listener.errors and self.strict:
87
+ error_listener.errors[:0] = lexer_listener.errors
88
+ elif lexer_listener.errors:
89
+ warnings.warn(
90
+ f"{self.file}: the UVL lexer skipped characters it cannot read, so the model "
91
+ f"is read without them ({'; '.join(lexer_listener.errors)}). "
92
+ "Use UVLReader(path, strict=True) to reject such models.",
93
+ UserWarning, stacklevel=3)
94
+
73
95
  if error_listener.errors:
74
96
  for error in error_listener.errors:
75
97
  logging.error(error)
@@ -209,7 +231,7 @@ class UVLReader(TextToModel):
209
231
  value)
210
232
  for attr in attributes_list:
211
233
  attributes.append(attr)
212
- default_value = None
234
+ default_value = None # also when the block is empty
213
235
  else:
214
236
  default_value = value
215
237
  attribute = Attribute(name=f'{parent_attribute_name}.{key}',
@@ -517,7 +539,7 @@ class UVLReader(TextToModel):
517
539
  "Import %s not found in path %s", namespace, self.path
518
540
  )
519
541
  continue
520
- self.imports[namespace] = UVLReader(import_path).transform()
542
+ self.imports[namespace] = UVLReader(import_path, strict=self.strict).transform()
521
543
  # The same model may be imported under several aliases: each one resolves to it.
522
544
  self.import_root[alias or namespace] = namespace
523
545
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flamapy-fm
3
- Version: 2.9.0.dev3
3
+ Version: 2.9.0.dev4
4
4
  Summary: flamapy-fm is a plugin to Flamapy module
5
5
  Author-email: Flamapy <flamapy@us.es>
6
6
  License-Expression: GPL-3.0-or-later
@@ -8,7 +8,7 @@ Project-URL: Homepage, https://github.com/flamapy/fm_metamodel
8
8
  Requires-Python: >=3.11
9
9
  Description-Content-Type: text/markdown
10
10
  License-File: LICENSE
11
- Requires-Dist: flamapy-fw~=2.9.0.dev3
11
+ Requires-Dist: flamapy-fw~=2.9.0.dev4
12
12
  Requires-Dist: uvlparser~=2.5.0
13
13
  Requires-Dist: afmparser~=1.0.3
14
14
  Provides-Extra: dev
@@ -20,8 +20,8 @@ Requires-Dist: coverage; extra == "dev"
20
20
  Requires-Dist: antlr4-tools; extra == "dev"
21
21
  Provides-Extra: test
22
22
  Requires-Dist: pytest; extra == "test"
23
- Requires-Dist: flamapy-sat~=2.9.0.dev3; extra == "test"
24
- Requires-Dist: flamapy-bdd~=2.9.0.dev3; extra == "test"
23
+ Requires-Dist: flamapy-sat~=2.9.0.dev4; extra == "test"
24
+ Requires-Dist: flamapy-bdd~=2.9.0.dev4; extra == "test"
25
25
  Dynamic: license-file
26
26
 
27
27
  # flamapy-fm
@@ -27,6 +27,7 @@ flamapy/metamodels/fm_metamodel/transformations/_uvl_lexer.py
27
27
  flamapy/metamodels/fm_metamodel/transformations/afm_reader.py
28
28
  flamapy/metamodels/fm_metamodel/transformations/afm_writer.py
29
29
  flamapy/metamodels/fm_metamodel/transformations/clafer_writer.py
30
+ flamapy/metamodels/fm_metamodel/transformations/constraint_support.py
30
31
  flamapy/metamodels/fm_metamodel/transformations/featureide_reader.py
31
32
  flamapy/metamodels/fm_metamodel/transformations/featureide_writer.py
32
33
  flamapy/metamodels/fm_metamodel/transformations/flat_fm.py
@@ -1,4 +1,4 @@
1
- flamapy-fw~=2.9.0.dev3
1
+ flamapy-fw~=2.9.0.dev4
2
2
  uvlparser~=2.5.0
3
3
  afmparser~=1.0.3
4
4
 
@@ -12,5 +12,5 @@ antlr4-tools
12
12
 
13
13
  [test]
14
14
  pytest
15
- flamapy-sat~=2.9.0.dev3
16
- flamapy-bdd~=2.9.0.dev3
15
+ flamapy-sat~=2.9.0.dev4
16
+ flamapy-bdd~=2.9.0.dev4
@@ -4,14 +4,14 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "flamapy-fm"
7
- version = "2.9.0.dev3"
7
+ version = "2.9.0.dev4"
8
8
  description = "flamapy-fm is a plugin to Flamapy module"
9
9
  readme = "README.md"
10
10
  license = "GPL-3.0-or-later"
11
11
  authors = [{ name = "Flamapy", email = "flamapy@us.es" }]
12
12
  requires-python = ">=3.11"
13
13
  dependencies = [
14
- "flamapy-fw~=2.9.0.dev3",
14
+ "flamapy-fw~=2.9.0.dev4",
15
15
  "uvlparser~=2.5.0",
16
16
  "afmparser~=1.0.3",
17
17
  ]
@@ -30,8 +30,8 @@ dev = [
30
30
  # group refactorings through the BDD plugin.
31
31
  test = [
32
32
  "pytest",
33
- "flamapy-sat~=2.9.0.dev3",
34
- "flamapy-bdd~=2.9.0.dev3",
33
+ "flamapy-sat~=2.9.0.dev4",
34
+ "flamapy-bdd~=2.9.0.dev4",
35
35
  ]
36
36
 
37
37
  [project.entry-points."flamapy.plugins"]
@@ -1,140 +0,0 @@
1
- import copy
2
- from typing import cast
3
-
4
- from flamapy.core.transformations import ModelToModel
5
- from flamapy.core.models import VariabilityModel, AST
6
- from flamapy.core.models.ast import ASTOperation, Node
7
-
8
- from flamapy.metamodels.fm_metamodel.models import FeatureModel, Feature
9
-
10
-
11
- class FlatFM(ModelToModel):
12
- """Given a feature model with imports information, it returns a flat feature model with
13
- all references resolved.
14
-
15
- That is, it copies all imported feature models in only one feature model ready to be analyzed.
16
- """
17
-
18
- @staticmethod
19
- def get_source_extension() -> str:
20
- return 'fm'
21
-
22
- @staticmethod
23
- def get_destination_extension() -> str:
24
- return 'fm'
25
-
26
- def __init__(self, source_model: VariabilityModel) -> None:
27
- self.feature_model = cast(FeatureModel, source_model)
28
- self._maintain_namespaces: bool = True
29
-
30
- def set_maintain_namespaces(self, maintain_namespaces: bool) -> None:
31
- """Set whether to maintain the namespaces of the imported features."""
32
- self._maintain_namespaces = maintain_namespaces
33
-
34
- def transform(self) -> FeatureModel:
35
- new_feature_model = copy.deepcopy(self.feature_model)
36
- imported_models = get_imported_models_by_root(new_feature_model)
37
- if not self._maintain_namespaces:
38
- for ctc in new_feature_model.ctcs:
39
- remove_namespace_constraint(ctc.ast, new_feature_model)
40
- features = [new_feature_model.root]
41
- while features:
42
- feature = features.pop()
43
- if feature.reference is not None:
44
- # Every reference gets its own copy of the imported model: the same model may
45
- # be referenced more than once (under one alias or several), and each
46
- # reference is a separate subtree with its own namespace.
47
- imported_fm = copy.deepcopy(imported_models[id(feature.reference)])
48
- imported_models.update(get_imported_models_by_root(imported_fm))
49
- feature.reference = imported_fm.root
50
- # Copy the feature's attributes and relations from the referenced feature
51
- feature.relations = feature.reference.relations
52
- for relation in feature.relations:
53
- relation.parent = feature
54
- for child in relation.children:
55
- child.parent = feature
56
- feature.attributes.extend(feature.reference.attributes)
57
- # Process attribute constraints
58
- # (they are also in the imported model's ctcs, which are processed below)
59
- feature.constraints_attributes.extend(feature.reference.constraints_attributes)
60
- if not self._maintain_namespaces:
61
- feature.name = feature.reference.name
62
- for ctc in imported_fm.ctcs:
63
- remove_namespace_constraint(ctc.ast, imported_fm)
64
- else:
65
- namespace = '.'.join(feature.name.split('.')[:-1])
66
- put_namespace_to_features(feature.reference, namespace)
67
- for ctc in imported_fm.ctcs:
68
- put_namespace_to_constraint(ctc.ast, namespace)
69
- # Add the constraints of the imported model (nested imports are reached when
70
- # their referencing features are visited)
71
- new_feature_model.ctcs.extend(imported_fm.ctcs)
72
- feature.reference = None # Clear reference after copying
73
- features.extend(feature.get_children())
74
- new_feature_model.imports = {} # Clear imports as they are not needed in the flat model
75
- new_feature_model.alias_namespace = {} # Clear alias namespace as it is not needed in
76
- return new_feature_model
77
-
78
-
79
- def put_namespace_to_features(root: Feature, namespace: str) -> None:
80
- """Put the namespace to the features in the feature model."""
81
- features = [root]
82
- while features:
83
- feature = features.pop()
84
- feature.name = f'{namespace}.{feature.name}'
85
- features.extend(feature.get_children())
86
-
87
-
88
- def get_imported_models_by_root(feature_model: FeatureModel) -> dict[int, FeatureModel]:
89
- """Return all the (nested) imported models of the feature model, indexed by the id of their
90
- root feature, which is the object referenced by the importing feature."""
91
- imported_models = {}
92
- models = list(feature_model.imports.values())
93
- while models:
94
- imported_fm = models.pop()
95
- imported_models[id(imported_fm.root)] = imported_fm
96
- models.extend(imported_fm.imports.values())
97
- return imported_models
98
-
99
-
100
- def get_feature_terms(ast: AST) -> list[Node]:
101
- """Return the terms of the constraint that reference a feature (or a Feature.Attribute).
102
-
103
- Literals are excluded, and so is the attribute name of the sum/avg aggregates
104
- (e.g., in sum(Price, B) only B is a feature).
105
- """
106
- terms = []
107
- stack = [ast.root]
108
- while stack:
109
- node = stack.pop()
110
- if node is None:
111
- continue
112
- if node.data in (ASTOperation.SUM, ASTOperation.AVG):
113
- stack.append(node.right)
114
- elif node.is_op():
115
- stack.extend([node.left, node.right])
116
- elif (isinstance(node.data, str) and not node.is_literal()
117
- and not node.data.startswith("'")):
118
- terms.append(node)
119
- return terms
120
-
121
-
122
- def put_namespace_to_constraint(ast: AST, namespace: str) -> None:
123
- """Put the namespace to the features referenced in the constraint."""
124
- for node in get_feature_terms(ast):
125
- node.data = f'{namespace}.{node.data}'
126
-
127
-
128
- def remove_namespace_constraint(ast: AST, feature_model: FeatureModel) -> None:
129
- """Remove the import aliases of the features referenced in a constraint of the model."""
130
- for node in get_feature_terms(ast):
131
- node.data = remove_namespace(node.data, feature_model)
132
-
133
-
134
- def remove_namespace(reference: str, feature_model: FeatureModel) -> str:
135
- """Remove the import alias prefixing the reference, following nested imports
136
- (e.g., 's.l.Y' -> 'Y', and 's.B.Price' -> 'B.Price')."""
137
- for alias, namespace in feature_model.alias_namespace.items():
138
- if reference.startswith(f'{alias}.') and namespace in feature_model.imports:
139
- return remove_namespace(reference[len(alias) + 1:], feature_model.imports[namespace])
140
- return reference
File without changes