deproc-python 0.2.1__py3-none-any.whl → 0.4.0__py3-none-any.whl

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.
@@ -3,16 +3,23 @@ from pathlib import Path
3
3
 
4
4
  from deproc.core.context import Context
5
5
  from deproc.core.interfaces import Linker
6
+ from deproc.core.interfaces.parser.models import SemanticContainer
6
7
 
7
8
  from ..parser.models import PythonModule
9
+ from ..utils.packages import apply_regular_package_precedence_to_registry
8
10
  from .models import Node, PythonNamespacePackage, PythonPackage
9
11
 
10
12
 
11
- class PythonLinker(Linker[PythonModule, Node]):
13
+ class PythonLinker(Linker[PythonModule, Node | SemanticContainer]):
14
+ def __init__(self, *, apply_package_precedence: bool = True) -> None:
15
+ self.apply_package_precedence = apply_package_precedence
16
+
12
17
  def _check_skip_patterns(self, path: str, skip_patterns: set[str]) -> bool:
13
18
  return any(fnmatch.fnmatch(path, pattern) for pattern in skip_patterns)
14
19
 
15
- def link_files(self, nodes: list[PythonModule], context: Context) -> list[Node]:
20
+ def link_files(
21
+ self, nodes: list[PythonModule], context: Context
22
+ ) -> list[Node | SemanticContainer]:
16
23
  base_path = Path(context.base_path)
17
24
 
18
25
  path_to_module: dict[str, PythonModule] = {}
@@ -29,7 +36,7 @@ class PythonLinker(Linker[PythonModule, Node]):
29
36
  path_to_module[relative_path] = node
30
37
 
31
38
  skip_patterns = context.skip_paths
32
- top_level: list[Node] = []
39
+ top_level: list[Node | SemanticContainer] = []
33
40
  for sub_path in base_path.iterdir():
34
41
  if sub_path.name == "__pycache__":
35
42
  continue
@@ -44,7 +51,16 @@ class PythonLinker(Linker[PythonModule, Node]):
44
51
  sub_node.parent_id = None
45
52
  top_level.append(sub_node)
46
53
 
47
- return top_level
54
+ if not self.apply_package_precedence:
55
+ return top_level
56
+
57
+ apply_regular_package_precedence_to_registry(context.entity_registry)
58
+ return [
59
+ node
60
+ for node in top_level
61
+ if not isinstance(node, SemanticContainer)
62
+ or node.id in context.entity_registry
63
+ ]
48
64
 
49
65
  def validate_path(self, path: str) -> bool:
50
66
  return (
@@ -61,7 +77,7 @@ class PythonLinker(Linker[PythonModule, Node]):
61
77
  path_to_module: dict[str, PythonModule],
62
78
  has_init: dict[str, PythonModule],
63
79
  context: Context,
64
- ) -> Node | None:
80
+ ) -> Node | SemanticContainer | None:
65
81
  if not self.validate_path(str(current_path)):
66
82
  return None
67
83
 
@@ -94,5 +110,9 @@ class PythonLinker(Linker[PythonModule, Node]):
94
110
  sub_node.parent_id = package.id
95
111
  package.submodule_ids.append(sub_node.id)
96
112
 
97
- context.entity_registry.add(package)
113
+ if isinstance(package, SemanticContainer):
114
+ package.submodule_ids = sorted(set(package.submodule_ids))
115
+ package = context.entity_registry.merge_semantic_container(package)
116
+ else:
117
+ context.entity_registry.add(package)
98
118
  return package
@@ -1,6 +1,6 @@
1
1
  from dataclasses import dataclass, field
2
2
 
3
- from deproc.core.interfaces.parser.models import Node
3
+ from deproc.core.interfaces.parser.models import Node, SemanticContainer
4
4
 
5
5
  from ..parser.models import (
6
6
  PythonModule,
@@ -9,10 +9,30 @@ from ..parser.models import (
9
9
 
10
10
 
11
11
  @dataclass
12
- class PythonNamespacePackage(Node):
12
+ class PythonNamespacePackage(SemanticContainer):
13
+ path: str
13
14
  fqn: str
14
15
  submodule_ids: list[SymbolID] = field(default_factory=list)
15
16
 
17
+ @property
18
+ def semantic_type(self) -> str:
19
+ return "python.namespace-package"
20
+
21
+ def __post_init__(self) -> None:
22
+ super().__post_init__()
23
+ self.submodule_ids = sorted(set(self.submodule_ids))
24
+
25
+ @property
26
+ def contribution_ids(self) -> list[SymbolID]:
27
+ return self.submodule_ids
28
+
29
+ def _merge_contributions(self, other: SemanticContainer) -> None:
30
+ if not isinstance(other, PythonNamespacePackage):
31
+ raise ValueError(
32
+ "Namespace packages can only merge with namespace packages"
33
+ )
34
+ self.submodule_ids = sorted(set(self.submodule_ids) | set(other.submodule_ids))
35
+
16
36
 
17
37
  @dataclass(kw_only=True)
18
38
  class PythonPackage(PythonModule):
@@ -91,6 +91,7 @@ class PythonSourceParser(SourceParser):
91
91
  source_file = PythonModule(
92
92
  fqn=parent_fqn,
93
93
  path=relative_path,
94
+ source_root_id=context.source_root_id,
94
95
  docstring_range=docstring_range,
95
96
  source=source_bytes.decode("utf-8"),
96
97
  )
@@ -0,0 +1,260 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Sequence
5
+ from dataclasses import dataclass
6
+
7
+ from deproc.core.interfaces.parser.models import SymbolID
8
+ from deproc.core.runtime import EntityRegistry
9
+
10
+ from ..linker.models import PythonNamespacePackage, PythonPackage
11
+ from ..parser.models import PythonModule
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ShadowedNamespacePortion:
18
+ fqn: str
19
+ path: str
20
+ registry_index: int
21
+ detached_ids: tuple[SymbolID, ...]
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class RegularPackageConflict:
26
+ fqn: str
27
+ source_root_ids: tuple[str | None, ...]
28
+
29
+
30
+ def _shadows(regular_fqns: set[str], fqn: str) -> bool:
31
+ return any(
32
+ fqn == regular or fqn.startswith(f"{regular}.") for regular in regular_fqns
33
+ )
34
+
35
+
36
+ def _root_label(root_id: str | None) -> str:
37
+ return root_id if root_id is not None else "<no root id>"
38
+
39
+
40
+ def _log_shadowed(fqn: str, detached: int) -> None:
41
+ logger.warning(
42
+ "namespace portion '%s' is shadowed by a regular package of the "
43
+ "same name in another root; its %d module(s) stay indexed "
44
+ "without a parent package",
45
+ fqn,
46
+ detached,
47
+ )
48
+
49
+
50
+ def find_regular_package_conflicts(
51
+ registries: Sequence[EntityRegistry],
52
+ ) -> list[RegularPackageConflict]:
53
+ by_fqn: dict[str, dict[SymbolID, PythonPackage]] = {}
54
+ for registry in registries:
55
+ for entity in registry.values():
56
+ if isinstance(entity, PythonPackage):
57
+ by_fqn.setdefault(entity.fqn, {})[entity.id] = entity
58
+ return [
59
+ RegularPackageConflict(
60
+ fqn=fqn,
61
+ source_root_ids=tuple(
62
+ sorted(
63
+ (package.source_root_id for package in packages.values()),
64
+ key=lambda root_id: root_id or "",
65
+ )
66
+ ),
67
+ )
68
+ for fqn, packages in sorted(by_fqn.items())
69
+ if len(packages) > 1
70
+ ]
71
+
72
+
73
+ def _log_conflicts(conflicts: Sequence[RegularPackageConflict]) -> None:
74
+ for conflict in conflicts:
75
+ logger.warning(
76
+ "regular package '%s' is defined in more than one root (%s); Python "
77
+ "imports only the first one on its path, and all of them stay indexed",
78
+ conflict.fqn,
79
+ ", ".join(_root_label(root_id) for root_id in conflict.source_root_ids),
80
+ )
81
+
82
+
83
+ def apply_regular_package_precedence(
84
+ registries: Sequence[EntityRegistry],
85
+ ) -> list[ShadowedNamespacePortion]:
86
+ """Apply Python's rule that a regular package wins over a namespace portion.
87
+
88
+ ``registries`` are the per-root link results, before they are merged. A
89
+ namespace portion in one registry is shadowed when a different registry
90
+ holds a regular package (one with ``__init__.py``) of the same name, or of
91
+ an ancestor name. Python then never imports that portion, so its container
92
+ is removed and the modules it held stay in the registry without a parent.
93
+ A warning is logged for each regular package name that more than one
94
+ registry defines; all of them are kept.
95
+ """
96
+ _log_conflicts(find_regular_package_conflicts(registries))
97
+ regular_by_registry = [
98
+ {
99
+ entity.fqn
100
+ for entity in registry.values()
101
+ if isinstance(entity, PythonPackage)
102
+ }
103
+ for registry in registries
104
+ ]
105
+ shadowed: list[ShadowedNamespacePortion] = []
106
+ for index, registry in enumerate(registries):
107
+ foreign_regular = {
108
+ fqn
109
+ for other, fqns in enumerate(regular_by_registry)
110
+ if other != index
111
+ for fqn in fqns
112
+ }
113
+ if not foreign_regular:
114
+ continue
115
+ candidates = sorted(
116
+ (
117
+ entity
118
+ for entity in registry.values()
119
+ if isinstance(entity, PythonNamespacePackage)
120
+ and _shadows(foreign_regular, entity.fqn)
121
+ ),
122
+ key=lambda entity: (entity.fqn, entity.path),
123
+ )
124
+ for container in candidates:
125
+ if container.id not in registry:
126
+ continue
127
+ detached = _drop_portion(registry, container)
128
+ portion = ShadowedNamespacePortion(
129
+ fqn=container.fqn,
130
+ path=container.path,
131
+ registry_index=index,
132
+ detached_ids=tuple(detached),
133
+ )
134
+ shadowed.append(portion)
135
+ _log_shadowed(container.fqn, len(detached))
136
+ return shadowed
137
+
138
+
139
+ def apply_regular_package_precedence_to_registry(
140
+ registry: EntityRegistry,
141
+ ) -> list[ShadowedNamespacePortion]:
142
+ regular: dict[str, list[PythonPackage]] = {}
143
+ for entity in registry.values():
144
+ if isinstance(entity, PythonPackage):
145
+ regular.setdefault(entity.fqn, []).append(entity)
146
+ _log_conflicts(find_regular_package_conflicts([registry]))
147
+ if not regular:
148
+ return []
149
+
150
+ containers = sorted(
151
+ (
152
+ entity
153
+ for entity in registry.values()
154
+ if isinstance(entity, PythonNamespacePackage)
155
+ and _shadows(set(regular), entity.fqn)
156
+ ),
157
+ key=lambda entity: (-entity.fqn.count("."), entity.fqn, entity.path),
158
+ )
159
+ shadowed: list[ShadowedNamespacePortion] = []
160
+ for container in containers:
161
+ if container.id not in registry:
162
+ continue
163
+ exact = container.fqn in regular
164
+ regular_roots = {
165
+ package.source_root_id
166
+ for fqn, packages in regular.items()
167
+ if _shadows({fqn}, container.fqn)
168
+ for package in packages
169
+ }
170
+ owner = (
171
+ min(
172
+ regular[container.fqn],
173
+ key=lambda package: (package.source_root_id or "", package.path),
174
+ )
175
+ if exact
176
+ else None
177
+ )
178
+ kept: list[SymbolID] = []
179
+ detached: list[SymbolID] = []
180
+ for child_id in container.submodule_ids:
181
+ child = registry.get(child_id)
182
+ if child is None:
183
+ continue
184
+ if isinstance(child, PythonNamespacePackage):
185
+ if owner is not None:
186
+ child.parent_id = owner.id
187
+ if child.id not in owner.submodule_ids:
188
+ owner.submodule_ids.append(child.id)
189
+ else:
190
+ kept.append(child_id)
191
+ continue
192
+ if (
193
+ owner is None
194
+ and isinstance(child, PythonModule)
195
+ and child.source_root_id in regular_roots
196
+ ):
197
+ kept.append(child_id)
198
+ continue
199
+ child.parent_id = None
200
+ detached.append(child.id)
201
+ removed = owner is not None or (bool(detached) and not kept)
202
+ if removed:
203
+ parent = registry.get(container.parent_id) if container.parent_id else None
204
+ if isinstance(parent, (PythonNamespacePackage, PythonPackage)):
205
+ parent.submodule_ids = [
206
+ entity_id
207
+ for entity_id in parent.submodule_ids
208
+ if entity_id != container.id
209
+ ]
210
+ registry.remove(container.id)
211
+ else:
212
+ container.submodule_ids = kept
213
+ if removed or detached:
214
+ shadowed.append(
215
+ ShadowedNamespacePortion(
216
+ fqn=container.fqn,
217
+ path=container.path,
218
+ registry_index=0,
219
+ detached_ids=tuple(sorted(detached)),
220
+ )
221
+ )
222
+ _log_shadowed(container.fqn, len(detached))
223
+ shadowed.sort(key=lambda portion: (portion.fqn, portion.path))
224
+ return shadowed
225
+
226
+
227
+ def _drop_portion(
228
+ registry: EntityRegistry, container: PythonNamespacePackage
229
+ ) -> list[SymbolID]:
230
+ detached: list[SymbolID] = []
231
+ pending = [container]
232
+ while pending:
233
+ current = pending.pop()
234
+ parent = registry.get(current.parent_id) if current.parent_id else None
235
+ if isinstance(parent, (PythonNamespacePackage, PythonPackage)):
236
+ parent.submodule_ids = [
237
+ entity_id
238
+ for entity_id in parent.submodule_ids
239
+ if entity_id != current.id
240
+ ]
241
+ registry.remove(current.id)
242
+ for child_id in current.submodule_ids:
243
+ child = registry.get(child_id)
244
+ if child is None:
245
+ continue
246
+ if isinstance(child, PythonNamespacePackage):
247
+ pending.append(child)
248
+ else:
249
+ child.parent_id = None
250
+ detached.append(child.id)
251
+ return sorted(detached)
252
+
253
+
254
+ __all__ = [
255
+ "RegularPackageConflict",
256
+ "ShadowedNamespacePortion",
257
+ "apply_regular_package_precedence",
258
+ "apply_regular_package_precedence_to_registry",
259
+ "find_regular_package_conflicts",
260
+ ]
@@ -190,6 +190,9 @@ def entity_to_record(
190
190
  path = getattr(entity, "path", None)
191
191
  if path is not None:
192
192
  metadata["path"] = path
193
+ source_root_id = getattr(entity, "source_root_id", None)
194
+ if source_root_id:
195
+ metadata["source_root_id"] = source_root_id
193
196
  if isinstance(entity, PythonModule) and entity.all_exports is not None:
194
197
  metadata["all_exports"] = entity.all_exports
195
198
  if isinstance(entity, PythonModule) and entity.exports_dynamic:
@@ -344,6 +347,7 @@ def record_to_entity(record: dict) -> Entity | None:
344
347
  all_exports=meta.get("all_exports"),
345
348
  exports_dynamic=meta.get("exports_dynamic", False),
346
349
  path=meta.get("path", ""),
350
+ source_root_id=meta.get("source_root_id"),
347
351
  source="",
348
352
  docstring_range=None,
349
353
  import_stmt_ids=meta.get("import_stmt_ids", []),
@@ -360,6 +364,7 @@ def record_to_entity(record: dict) -> Entity | None:
360
364
  all_exports=meta.get("all_exports"),
361
365
  exports_dynamic=meta.get("exports_dynamic", False),
362
366
  path=meta.get("path", ""),
367
+ source_root_id=meta.get("source_root_id"),
363
368
  source="",
364
369
  docstring_range=None,
365
370
  import_stmt_ids=meta.get("import_stmt_ids", []),
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deproc-python
3
- Version: 0.2.1
3
+ Version: 0.4.0
4
4
  Summary: Python language plugin for deproc.
5
5
  Author-email: Gurveer Singh Virk <gurveervirk.15517@gmail.com>
6
6
  License: Apache-2.0
@@ -16,7 +16,7 @@ Classifier: Programming Language :: Python :: 3.12
16
16
  Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Topic :: Software Development :: Libraries
18
18
  Requires-Python: >=3.12
19
- Requires-Dist: deproc-core>=0.2.0
20
- Requires-Dist: deproc-utils-tree-sitter>=0.1.2
21
- Requires-Dist: tree-sitter>=0.25.2
19
+ Requires-Dist: deproc-core>=0.4.0
20
+ Requires-Dist: deproc-utils-tree-sitter>=0.1.3
21
+ Requires-Dist: tree-sitter<0.26,>=0.25.2
22
22
  Requires-Dist: tree-sitter-python>=0.25.0
@@ -1,9 +1,9 @@
1
1
  deproc/plugins/python/__init__.py,sha256=JuMffHnYtF82voXTOP4m1hQ-zTGA5OeroWhHuz9v8nk,504
2
2
  deproc/plugins/python/linker/__init__.py,sha256=gQ64CQcNEDHfvyAuYAz81PZ6r2V0ZdnsVOR2YZZvvfU,59
3
- deproc/plugins/python/linker/main.py,sha256=rulxUoRRu4l7RbJKm2oBAxowHYv5KpsKvV36XRmvrjw,3260
4
- deproc/plugins/python/linker/models.py,sha256=Q5_SFhaGyU8-HSNnIj0t00SYXqdnfwChyO6d5OcUNXM,492
3
+ deproc/plugins/python/linker/main.py,sha256=cdaqf4MmaMWiR_7pgSTFy4j8chQs8je3GK0_ouTSGWA,4167
4
+ deproc/plugins/python/linker/models.py,sha256=aXigj6ATiTmM_wQVjSQP_Te8An6wm_XhR3InauqRaMc,1198
5
5
  deproc/plugins/python/parser/__init__.py,sha256=dcfU6uyIOBUOvnz9xM4hX6gc0ldTGavHZCSIv6lbWWk,71
6
- deproc/plugins/python/parser/main.py,sha256=UYJwEODEaHZOZaxqLY_0nmuO3lDsqxnks6-AhnorZvg,31146
6
+ deproc/plugins/python/parser/main.py,sha256=hXODQpsCTOnTmi4xlTbGhl95SyusU5RmYMFZm5obtCI,31197
7
7
  deproc/plugins/python/parser/models.py,sha256=_Fr239_t-v6ET5EA1uUVTUiFHztqbJ03Q7WfdktrQnc,1700
8
8
  deproc/plugins/python/parser/utils/extraction.py,sha256=UE5u6SA_KrrGX6hTbuW1RrlFRvNqrlA-jMpGepHX0z0,7221
9
9
  deproc/plugins/python/parser/utils/misc.py,sha256=vdxTcrNdWndIvaZtC8zGlKYI6XZnZHZ7I7YskuvXdnQ,219
@@ -17,8 +17,9 @@ deproc/plugins/python/symbol_cache/models.py,sha256=1SgqUyhNnwZcITRCL8a-21T26niQ
17
17
  deproc/plugins/python/utils/exports.py,sha256=45dvBfClVEo_ZRN6vCPEx0VH3-eRQiKahv1Qgg074Lo,5218
18
18
  deproc/plugins/python/utils/imports.py,sha256=DWvcN2SdYmhQgRl9RYAc5nxbbijSEtAJ11X_Xrf3x_U,547
19
19
  deproc/plugins/python/utils/mro.py,sha256=6tTC5lHFK2PZWX-454dGKNmiVhFDrMRQhI0bgDJZlrk,1565
20
- deproc/plugins/python/utils/serialization.py,sha256=Lu5L2DLKCBhzCSQOykWq9tlFzqIMesL6JUWvrvZwExY,16657
21
- deproc_python-0.2.1.dist-info/METADATA,sha256=9in_tQx9Za1v6HgNXPN5vi-LwNf9p80jCsSOUQfBICs,949
22
- deproc_python-0.2.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
23
- deproc_python-0.2.1.dist-info/top_level.txt,sha256=qyPIAnJVTLaewuAbLpShmn-777EtCI7b1b5sGgkzO10,7
24
- deproc_python-0.2.1.dist-info/RECORD,,
20
+ deproc/plugins/python/utils/packages.py,sha256=Tdedjc8c7_R9rK9KWtZAOjNuqu55uM3ZRPwId1rsEU4,8857
21
+ deproc/plugins/python/utils/serialization.py,sha256=oiuezQ5XslWBPnQyCidEPHxqOSkBfFS0xFQ6PVsQ-ic,16903
22
+ deproc_python-0.4.0.dist-info/METADATA,sha256=xda6brcG4Bsbj-bnHPx2mudvR98YDvObK6DjF-Rxokg,955
23
+ deproc_python-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
24
+ deproc_python-0.4.0.dist-info/top_level.txt,sha256=qyPIAnJVTLaewuAbLpShmn-777EtCI7b1b5sGgkzO10,7
25
+ deproc_python-0.4.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.0.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5