deproc-python 0.3.0__py3-none-any.whl → 0.4.1__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.
@@ -6,10 +6,14 @@ from deproc.core.interfaces import Linker
6
6
  from deproc.core.interfaces.parser.models import SemanticContainer
7
7
 
8
8
  from ..parser.models import PythonModule
9
+ from ..utils.packages import apply_regular_package_precedence_to_registry
9
10
  from .models import Node, PythonNamespacePackage, PythonPackage
10
11
 
11
12
 
12
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
+
13
17
  def _check_skip_patterns(self, path: str, skip_patterns: set[str]) -> bool:
14
18
  return any(fnmatch.fnmatch(path, pattern) for pattern in skip_patterns)
15
19
 
@@ -47,7 +51,16 @@ class PythonLinker(Linker[PythonModule, Node | SemanticContainer]):
47
51
  sub_node.parent_id = None
48
52
  top_level.append(sub_node)
49
53
 
50
- 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
+ ]
51
64
 
52
65
  def validate_path(self, path: str) -> bool:
53
66
  return (
@@ -1,13 +1,14 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import logging
4
- from collections.abc import Sequence
4
+ from collections.abc import Mapping, Sequence
5
5
  from dataclasses import dataclass
6
6
 
7
7
  from deproc.core.interfaces.parser.models import SymbolID
8
8
  from deproc.core.runtime import EntityRegistry
9
9
 
10
10
  from ..linker.models import PythonNamespacePackage, PythonPackage
11
+ from ..parser.models import PythonModule
11
12
 
12
13
  logger = logging.getLogger(__name__)
13
14
 
@@ -20,23 +21,98 @@ class ShadowedNamespacePortion:
20
21
  detached_ids: tuple[SymbolID, ...]
21
22
 
22
23
 
24
+ @dataclass(frozen=True)
25
+ class RegularPackageConflict:
26
+ fqn: str
27
+ source_root_ids: tuple[str | None, ...]
28
+
29
+
23
30
  def _shadows(regular_fqns: set[str], fqn: str) -> bool:
24
31
  return any(
25
32
  fqn == regular or fqn.startswith(f"{regular}.") for regular in regular_fqns
26
33
  )
27
34
 
28
35
 
36
+ def _root_label(
37
+ root_id: str | None, root_labels: Mapping[str | None, str] | None
38
+ ) -> str:
39
+ if root_labels is not None and root_id in root_labels:
40
+ return root_labels[root_id]
41
+ return root_id if root_id is not None else "<no root id>"
42
+
43
+
44
+ def _log_shadowed(fqn: str, detached: int) -> None:
45
+ logger.warning(
46
+ "namespace portion '%s' is shadowed by a regular package of the "
47
+ "same name in another root; its %d module(s) stay indexed "
48
+ "without a parent package",
49
+ fqn,
50
+ detached,
51
+ )
52
+
53
+
54
+ def find_regular_package_conflicts(
55
+ registries: Sequence[EntityRegistry],
56
+ ) -> list[RegularPackageConflict]:
57
+ by_fqn: dict[str, dict[SymbolID, PythonPackage]] = {}
58
+ for registry in registries:
59
+ for entity in registry.values():
60
+ if isinstance(entity, PythonPackage):
61
+ by_fqn.setdefault(entity.fqn, {})[entity.id] = entity
62
+ return [
63
+ RegularPackageConflict(
64
+ fqn=fqn,
65
+ source_root_ids=tuple(
66
+ sorted(
67
+ (package.source_root_id for package in packages.values()),
68
+ key=lambda root_id: root_id or "",
69
+ )
70
+ ),
71
+ )
72
+ for fqn, packages in sorted(by_fqn.items())
73
+ if len(packages) > 1
74
+ ]
75
+
76
+
77
+ def _log_conflicts(
78
+ conflicts: Sequence[RegularPackageConflict],
79
+ root_labels: Mapping[str | None, str] | None,
80
+ ) -> None:
81
+ for conflict in conflicts:
82
+ logger.warning(
83
+ "regular package '%s' is defined in more than one root (%s); Python "
84
+ "imports only the first one on its path, and all of them stay indexed",
85
+ conflict.fqn,
86
+ ", ".join(
87
+ _root_label(root_id, root_labels)
88
+ for root_id in conflict.source_root_ids
89
+ ),
90
+ )
91
+
92
+
29
93
  def apply_regular_package_precedence(
30
94
  registries: Sequence[EntityRegistry],
95
+ *,
96
+ root_labels: Mapping[str | None, str] | None = None,
31
97
  ) -> list[ShadowedNamespacePortion]:
32
98
  """Apply Python's rule that a regular package wins over a namespace portion.
33
99
 
34
- ``registries`` are the per-root link results, before they are merged. A
35
- namespace portion in one registry is shadowed when a different registry
100
+ A namespace portion in one registry is shadowed when a different registry
36
101
  holds a regular package (one with ``__init__.py``) of the same name, or of
37
102
  an ancestor name. Python then never imports that portion, so its container
38
103
  is removed and the modules it held stay in the registry without a parent.
104
+ A warning is logged for each regular package name that more than one
105
+ registry defines; all of them are kept.
106
+
107
+ Args:
108
+ registries: The per-root link results, before they are merged.
109
+ root_labels: Names for roots in the warning, by source root id.
110
+ Unlabelled roots show their id.
111
+
112
+ Returns:
113
+ The shadowed portions, with the module IDs each one detached.
39
114
  """
115
+ _log_conflicts(find_regular_package_conflicts(registries), root_labels)
40
116
  regular_by_registry = [
41
117
  {
42
118
  entity.fqn
@@ -75,13 +151,97 @@ def apply_regular_package_precedence(
75
151
  detached_ids=tuple(detached),
76
152
  )
77
153
  shadowed.append(portion)
78
- logger.warning(
79
- "namespace portion '%s' is shadowed by a regular package of the "
80
- "same name in another root; its %d module(s) stay indexed "
81
- "without a parent package",
82
- container.fqn,
83
- len(detached),
154
+ _log_shadowed(container.fqn, len(detached))
155
+ return shadowed
156
+
157
+
158
+ def apply_regular_package_precedence_to_registry(
159
+ registry: EntityRegistry,
160
+ *,
161
+ root_labels: Mapping[str | None, str] | None = None,
162
+ ) -> list[ShadowedNamespacePortion]:
163
+ regular: dict[str, list[PythonPackage]] = {}
164
+ for entity in registry.values():
165
+ if isinstance(entity, PythonPackage):
166
+ regular.setdefault(entity.fqn, []).append(entity)
167
+ _log_conflicts(find_regular_package_conflicts([registry]), root_labels)
168
+ if not regular:
169
+ return []
170
+
171
+ containers = sorted(
172
+ (
173
+ entity
174
+ for entity in registry.values()
175
+ if isinstance(entity, PythonNamespacePackage)
176
+ and _shadows(set(regular), entity.fqn)
177
+ ),
178
+ key=lambda entity: (-entity.fqn.count("."), entity.fqn, entity.path),
179
+ )
180
+ shadowed: list[ShadowedNamespacePortion] = []
181
+ for container in containers:
182
+ if container.id not in registry:
183
+ continue
184
+ exact = container.fqn in regular
185
+ regular_roots = {
186
+ package.source_root_id
187
+ for fqn, packages in regular.items()
188
+ if _shadows({fqn}, container.fqn)
189
+ for package in packages
190
+ }
191
+ owner = (
192
+ min(
193
+ regular[container.fqn],
194
+ key=lambda package: (package.source_root_id or "", package.path),
195
+ )
196
+ if exact
197
+ else None
198
+ )
199
+ kept: list[SymbolID] = []
200
+ detached: list[SymbolID] = []
201
+ for child_id in container.submodule_ids:
202
+ child = registry.get(child_id)
203
+ if child is None:
204
+ continue
205
+ if isinstance(child, PythonNamespacePackage):
206
+ if owner is not None:
207
+ child.parent_id = owner.id
208
+ if child.id not in owner.submodule_ids:
209
+ owner.submodule_ids.append(child.id)
210
+ else:
211
+ kept.append(child_id)
212
+ continue
213
+ if (
214
+ owner is None
215
+ and isinstance(child, PythonModule)
216
+ and child.source_root_id in regular_roots
217
+ ):
218
+ kept.append(child_id)
219
+ continue
220
+ child.parent_id = None
221
+ detached.append(child.id)
222
+ removed = owner is not None or (bool(detached) and not kept)
223
+ if removed:
224
+ parent = registry.get(container.parent_id) if container.parent_id else None
225
+ if isinstance(parent, (PythonNamespacePackage, PythonPackage)):
226
+ parent.submodule_ids = [
227
+ entity_id
228
+ for entity_id in parent.submodule_ids
229
+ if entity_id != container.id
230
+ ]
231
+ registry.remove(container.id)
232
+ else:
233
+ container.submodule_ids = kept
234
+ if removed or detached:
235
+ shadowed.append(
236
+ ShadowedNamespacePortion(
237
+ fqn=container.fqn,
238
+ path=container.path,
239
+ registry_index=0,
240
+ detached_ids=tuple(sorted(detached)),
241
+ )
84
242
  )
243
+ _log_shadowed(container.fqn, len(detached))
244
+ shadowed.sort(key=lambda portion: (portion.fqn, portion.path))
85
245
  return shadowed
86
246
 
87
247
 
@@ -112,4 +272,10 @@ def _drop_portion(
112
272
  return sorted(detached)
113
273
 
114
274
 
115
- __all__ = ["ShadowedNamespacePortion", "apply_regular_package_precedence"]
275
+ __all__ = [
276
+ "RegularPackageConflict",
277
+ "ShadowedNamespacePortion",
278
+ "apply_regular_package_precedence",
279
+ "apply_regular_package_precedence_to_registry",
280
+ "find_regular_package_conflicts",
281
+ ]
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: deproc-python
3
+ Version: 0.4.1
4
+ Summary: Python language plugin for deproc.
5
+ Author-email: Gurveer Singh Virk <gurveervirk.15517@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/gurveervirk/deproc
8
+ Project-URL: Repository, https://github.com/gurveervirk/deproc
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+ Requires-Dist: deproc-core>=0.4.0
21
+ Requires-Dist: deproc-utils-tree-sitter>=0.1.3
22
+ Requires-Dist: tree-sitter<0.26,>=0.25.2
23
+ Requires-Dist: tree-sitter-python>=0.25.0
24
+
25
+ # deproc-python
26
+
27
+ Python language plugin for [deproc](https://github.com/gurveervirk/deproc).
28
+
29
+ Parses `.py` and `.pyi` files with tree-sitter into the deproc entity model,
30
+ links them into a package hierarchy, and resolves names across modules.
31
+
32
+ ## Features
33
+
34
+ - Modules, classes, functions and methods, constants, type aliases, imports and
35
+ import aliases as deproc entities
36
+ - Regular packages (`__init__.py`) and implicit namespace packages, including a
37
+ namespace package contributed by several roots
38
+ - Python's regular-package precedence across roots: a regular package wins over
39
+ a same-named namespace portion from another root
40
+ - Name resolution through imports, relative imports and wildcard imports
41
+ - Class MRO (C3 linearization) and inherited members
42
+ - Entity serialization to flat records and back
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ python -m pip install deproc-python
48
+ ```
49
+
50
+ `deproc-python` supports Python 3.12 and newer and installs `deproc-core` with it.
51
+
52
+ ## Usage
53
+
54
+ ```python
55
+ from deproc.core.context import Context
56
+ from deproc.core.discovery import find_source_files
57
+ from deproc.plugins.python import (
58
+ PythonLinker,
59
+ PythonResolver,
60
+ PythonSourceParser,
61
+ PythonSymbolCache,
62
+ )
63
+
64
+ ctx = Context(base_path="/path/to/project")
65
+ ctx.set_language("python", [".py", ".pyi"], aliases=["py"])
66
+ ctx.set_parser("python", PythonSourceParser())
67
+ ctx.set_linker("python", PythonLinker())
68
+ ctx.set_resolver("python", PythonResolver())
69
+ ctx.set_symbol_cache(PythonSymbolCache())
70
+
71
+ files = find_source_files(ctx)
72
+ parser = ctx.get_parser("python")
73
+ modules = [parser.parse_file(path, ctx) for path in files]
74
+ ctx.get_linker("python").link_files(modules, ctx)
75
+
76
+ result = ctx.get_resolver("python").resolve("acme_billing.invoice", "TaxRate", ctx)
77
+ print(result.status) # resolved
78
+ for entity_id in result.resolved_ids:
79
+ print(ctx.entity_registry.get(entity_id).fqn) # acme_billing.tax.TaxRate
80
+ ```
81
+
82
+ `result.status` is a `ResolutionStatus` (`RESOLVED`, `UNRESOLVED`, `AMBIGUOUS`, or
83
+ `INACCESSIBLE`) from `deproc.core.interfaces.resolver`. The result also carries
84
+ `unresolved_ids`, `ambiguous_ids`, `inaccessible_ids`, `reason` and `candidates`.
85
+
86
+ `PythonResolver` also provides `resolve_class_mro(class_id, ctx)` and
87
+ `get_inherited_members(class_id, ctx)`.
88
+
89
+ ## Several roots
90
+
91
+ When several roots contribute the same package name, deproc follows Python's
92
+ import rule:
93
+
94
+ - A regular package (`__init__.py`) in one root wins over a same-named namespace
95
+ portion in another root, in any root order. The shadowed container is removed
96
+ and its modules stay indexed with no parent.
97
+ - Namespace portions with the same name in several roots become one namespace
98
+ package.
99
+ - Two regular packages with the same name in different roots are both kept, and a
100
+ warning names the roots, because Python would import whichever comes first on
101
+ its path.
102
+
103
+ `PythonLinker.link_files()` applies this rule automatically when roots share one
104
+ registry; `PythonLinker(apply_package_precedence=False)` turns it off.
105
+ `deproc.plugins.python.utils.packages` provides
106
+ `apply_regular_package_precedence()` for separate per-root registries,
107
+ `apply_regular_package_precedence_to_registry()` for one shared registry, and
108
+ `find_regular_package_conflicts()`. Pass `root_labels` to either precedence
109
+ function to name roots in the warning.
110
+
111
+ ## Package layout
112
+
113
+ ```
114
+ deproc-python/
115
+ ├── deproc/plugins/python/
116
+ │ ├── parser/ PythonSourceParser (tree-sitter AST → entities)
117
+ │ ├── linker/ PythonLinker (modules → package hierarchy)
118
+ │ ├── resolver/ PythonResolver (names, MRO, inherited members)
119
+ │ ├── symbol_cache/ PythonSymbolCache (per-module cache)
120
+ │ └── utils/ imports, exports, MRO, package precedence, serialization
121
+ └── tests/
122
+ ```
123
+
124
+ ## Dependencies
125
+
126
+ - `deproc-core` (entity model, Context, EntityRegistry)
127
+ - `deproc-utils-tree-sitter` (AST walking utilities)
128
+ - `tree-sitter` (`>=0.25.2,<0.26`) and `tree-sitter-python` (Python grammar)
@@ -1,6 +1,6 @@
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=As8K2k1PtxdO7GnFC4cRQXRDzVJOFWqKPLx5O_xj2V4,3641
3
+ deproc/plugins/python/linker/main.py,sha256=cdaqf4MmaMWiR_7pgSTFy4j8chQs8je3GK0_ouTSGWA,4167
4
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
6
  deproc/plugins/python/parser/main.py,sha256=hXODQpsCTOnTmi4xlTbGhl95SyusU5RmYMFZm5obtCI,31197
@@ -17,9 +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/packages.py,sha256=d6gUP1_KE8_r3StPpdRpH5TyWJnaMlpXVqzBOFEm1HI,3861
20
+ deproc/plugins/python/utils/packages.py,sha256=VOOibo76bJwti6BrLlTq3ihW23MQfBALOFEAQ_W2tms,9491
21
21
  deproc/plugins/python/utils/serialization.py,sha256=oiuezQ5XslWBPnQyCidEPHxqOSkBfFS0xFQ6PVsQ-ic,16903
22
- deproc_python-0.3.0.dist-info/METADATA,sha256=UVBExd7lUnv4FpWAe2MuGPP9BdIfdEAG8ERmorq5JjQ,949
23
- deproc_python-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
24
- deproc_python-0.3.0.dist-info/top_level.txt,sha256=qyPIAnJVTLaewuAbLpShmn-777EtCI7b1b5sGgkzO10,7
25
- deproc_python-0.3.0.dist-info/RECORD,,
22
+ deproc_python-0.4.1.dist-info/METADATA,sha256=RD3Uk4xPJ5SqfCj47gUBZMkjRd0sODQLVv-BITzvK7Q,4973
23
+ deproc_python-0.4.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
24
+ deproc_python-0.4.1.dist-info/top_level.txt,sha256=qyPIAnJVTLaewuAbLpShmn-777EtCI7b1b5sGgkzO10,7
25
+ deproc_python-0.4.1.dist-info/RECORD,,
@@ -1,22 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: deproc-python
3
- Version: 0.3.0
4
- Summary: Python language plugin for deproc.
5
- Author-email: Gurveer Singh Virk <gurveervirk.15517@gmail.com>
6
- License: Apache-2.0
7
- Project-URL: Homepage, https://github.com/gurveervirk/deproc
8
- Project-URL: Repository, https://github.com/gurveervirk/deproc
9
- Classifier: Development Status :: 3 - Alpha
10
- Classifier: Intended Audience :: Developers
11
- Classifier: License :: OSI Approved :: Apache Software License
12
- Classifier: Operating System :: OS Independent
13
- Classifier: Programming Language :: Python :: 3
14
- Classifier: Programming Language :: Python :: 3 :: Only
15
- Classifier: Programming Language :: Python :: 3.12
16
- Classifier: Programming Language :: Python :: 3.13
17
- Classifier: Topic :: Software Development :: Libraries
18
- Requires-Python: >=3.12
19
- Requires-Dist: deproc-core>=0.4.0
20
- Requires-Dist: deproc-utils-tree-sitter>=0.1.2
21
- Requires-Dist: tree-sitter>=0.25.2
22
- Requires-Dist: tree-sitter-python>=0.25.0