netherframe.codec.autoid 0.3.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.
@@ -0,0 +1,19 @@
1
+ """Auto-ID source codec and preprocessor."""
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ from netherframe.codec.autoid.codec_registration import register_codec
6
+
7
+ if TYPE_CHECKING:
8
+ from netherframe.codec.autoid.preprocessor import preprocess_source
9
+
10
+ __all__ = ["preprocess_source", "register_codec"]
11
+
12
+
13
+ def __getattr__(name: str) -> Any:
14
+ # The preprocessor imports libcst; load it only when it is actually used.
15
+ if name == "preprocess_source":
16
+ from netherframe.codec.autoid.preprocessor import preprocess_source
17
+
18
+ return preprocess_source
19
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,37 @@
1
+ """Register the nf_autoid source codec without importing the preprocessor.
2
+
3
+ This module is loaded by a .start entry point (or a .pth fallback on Python 3.14)
4
+ at every interpreter start, so it must stay cheap: libcst and the preprocessor
5
+ load only when a source file actually declares ``# coding: nf_autoid``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import codecs
11
+ import threading
12
+
13
+ CODEC_NAME = "nf_autoid"
14
+
15
+ _lock = threading.Lock()
16
+ _registered = False
17
+
18
+
19
+ def _search_function(encoding: str) -> codecs.CodecInfo | None:
20
+ if encoding != CODEC_NAME:
21
+ return None
22
+ from netherframe.codec.autoid.preprocessor import create_autoid_codec
23
+
24
+ return create_autoid_codec()
25
+
26
+
27
+ def register_codec() -> None:
28
+ """Register the nf_autoid codec with Python's codec registry (idempotent)."""
29
+ global _registered # noqa: PLW0603
30
+ with _lock:
31
+ if _registered:
32
+ return
33
+ codecs.register(_search_function)
34
+ _registered = True
35
+
36
+
37
+ register_codec()
@@ -0,0 +1,367 @@
1
+ """Auto-ID preprocessor for automatic variable name injection.
2
+
3
+ This module implements a Python source code preprocessor that automatically
4
+ injects variable names into Netherframe construct instantiations using LibCST
5
+ and registers a custom codec for transparent preprocessing during imports.
6
+ """
7
+
8
+ from collections.abc import Buffer
9
+ import codecs
10
+
11
+ import libcst as cst
12
+
13
+ from netherframe.codec.autoid.codec_registration import register_codec
14
+
15
+
16
+ class LibCSTTransformer(cst.CSTTransformer):
17
+ """Transform AST to inject variable names using LibCST."""
18
+
19
+ def __init__(self) -> None:
20
+ super().__init__()
21
+
22
+ def _has_bind_annotation(self, annotation: cst.Annotation | None) -> bool:
23
+ """Check if annotation indicates Bind."""
24
+ if not annotation:
25
+ return False
26
+
27
+ ann = annotation.annotation
28
+
29
+ # Check for: Bind or Bind[...]
30
+ if isinstance(ann, cst.Name):
31
+ return ann.value == "Bind"
32
+ if isinstance(ann, cst.Subscript) and isinstance(ann.value, cst.Name):
33
+ return ann.value.value == "Bind"
34
+
35
+ return False
36
+
37
+ def _get_type_from_bind_annotation(
38
+ self,
39
+ annotation: cst.Annotation,
40
+ ) -> cst.BaseExpression | None:
41
+ """Extract the type from Bind[Type] annotation, or None for plain Bind."""
42
+ ann = annotation.annotation
43
+
44
+ if isinstance(ann, cst.Subscript):
45
+ # Bind[Type] - extract Type
46
+ if isinstance(ann.value, cst.Name) and ann.value.value == "Bind":
47
+ if ann.slice and isinstance(ann.slice, (list, tuple)) and len(ann.slice) > 0:
48
+ slice_elem = ann.slice[0]
49
+ if isinstance(slice_elem, cst.SubscriptElement):
50
+ if isinstance(slice_elem.slice, cst.Index):
51
+ return slice_elem.slice.value
52
+ return None
53
+
54
+ def _inject_nf_id(self, call: cst.Call, var_name: str) -> cst.Call:
55
+ """Transform Vpc(...) to Vpc(..., nf_id=var_name)."""
56
+ # Check if nf_id parameter already exists
57
+ has_nf_id = False
58
+ for arg in call.args:
59
+ if arg.keyword and isinstance(arg.keyword, cst.Name) and arg.keyword.value == "nf_id":
60
+ has_nf_id = True
61
+ break
62
+
63
+ # Only add nf_id if it doesn't already exist
64
+ if not has_nf_id:
65
+ nf_id_arg = cst.Arg(
66
+ keyword=cst.Name("nf_id"),
67
+ value=cst.SimpleString(f'"{var_name}"'),
68
+ equal=cst.AssignEqual(
69
+ whitespace_before=cst.SimpleWhitespace(""),
70
+ whitespace_after=cst.SimpleWhitespace(""),
71
+ ),
72
+ )
73
+
74
+ # Add nf_id as the last argument
75
+ new_args = list(call.args) + [nf_id_arg]
76
+ return call.with_changes(args=new_args)
77
+
78
+ # If nf_id already exists, return the call as-is
79
+ return call
80
+
81
+ def _process_element_or_call(
82
+ self,
83
+ element: cst.BaseElement | cst.BaseExpression,
84
+ var_name: str,
85
+ ) -> cst.BaseElement | cst.BaseExpression:
86
+ """Process an element that might contain a construct call."""
87
+ # This method is no longer used since we only wrap based on Bind annotation
88
+ return element
89
+
90
+ def _extract_var_name(
91
+ self,
92
+ target: cst.BaseAssignTargetExpression,
93
+ ) -> str | None:
94
+ """Extract variable name from assignment target."""
95
+ if isinstance(target, cst.AssignTarget):
96
+ target_expr = target.target
97
+ if isinstance(target_expr, cst.Name):
98
+ return target_expr.value
99
+ if isinstance(target_expr, cst.Attribute):
100
+ return target_expr.attr.value
101
+ if isinstance(target_expr, cst.Subscript):
102
+ # Handle subscript expressions like dict['key']
103
+ if isinstance(target_expr.slice, (list, tuple)) and len(target_expr.slice) == 1:
104
+ # Get the first element
105
+ slice_elem = target_expr.slice[0]
106
+ if isinstance(slice_elem, cst.SubscriptElement) and isinstance(
107
+ slice_elem.slice,
108
+ cst.Index,
109
+ ):
110
+ if isinstance(slice_elem.slice.value, cst.SimpleString):
111
+ # Remove quotes from string
112
+ return slice_elem.slice.value.value.strip("\"'")
113
+ return None
114
+
115
+ def _extract_asname(self, asname: cst.AsName) -> str | None:
116
+ """Extract variable name from a with-as target."""
117
+ if isinstance(asname.name, cst.Name):
118
+ return asname.name.value
119
+ if isinstance(asname.name, cst.Attribute):
120
+ return asname.name.attr.value
121
+ return None
122
+
123
+ def _is_bind_context(self, expr: cst.BaseExpression) -> bool:
124
+ """Check whether a with-item expression is BindContext."""
125
+ if isinstance(expr, cst.Name):
126
+ return expr.value == "BindContext"
127
+ if isinstance(expr, cst.Attribute):
128
+ return expr.attr.value == "BindContext"
129
+ if isinstance(expr, cst.Call):
130
+ return self._is_bind_context(expr.func)
131
+ return False
132
+
133
+ def leave_Assign(
134
+ self,
135
+ original_node: cst.Assign,
136
+ updated_node: cst.Assign,
137
+ ) -> cst.Assign:
138
+ """Transform assignments - no wrapping without Bind annotation."""
139
+ # Regular assignments without type annotations are not wrapped
140
+ # Users must use Bind annotation for variable name injection
141
+ return updated_node
142
+
143
+ def leave_AnnAssign(
144
+ self,
145
+ original_node: cst.AnnAssign,
146
+ updated_node: cst.AnnAssign,
147
+ ) -> cst.AnnAssign | cst.Assign:
148
+ """Transform annotated assignments with Bind annotation."""
149
+ if updated_node.value is None:
150
+ return updated_node
151
+
152
+ # Check for Bind annotation
153
+ if not self._has_bind_annotation(updated_node.annotation):
154
+ return updated_node
155
+
156
+ # Extract variable name
157
+ var_name = None
158
+ if isinstance(updated_node.target, cst.Name):
159
+ var_name = updated_node.target.value
160
+ elif isinstance(updated_node.target, cst.Attribute):
161
+ var_name = updated_node.target.attr.value
162
+
163
+ if not var_name:
164
+ return updated_node
165
+
166
+ # Check if value is already a deferred call pattern: Vpc(...)(...)
167
+ if isinstance(updated_node.value, cst.Call) and isinstance(
168
+ updated_node.value.func,
169
+ cst.Call,
170
+ ):
171
+ # It's a deferred call pattern - convert to explicit nf_id injection
172
+ inner_call = updated_node.value.func # The Vpc(...) part
173
+ outer_args = updated_node.value.args # The (...) arguments
174
+
175
+ # Extract arguments from the outer call and merge them with inner call
176
+ # Convert outer call args to inner call keyword args where possible
177
+ new_args = list(inner_call.args)
178
+
179
+ for arg in outer_args:
180
+ if not arg.keyword:
181
+ # For positional arguments in deferred calls, try to map them to known params
182
+ # This is complex, so for now let's just handle simple cases
183
+ continue
184
+ # For keyword arguments, add them to the inner call
185
+ # But convert scope -> nf_scope if needed
186
+ keyword_name = arg.keyword.value if isinstance(arg.keyword, cst.Name) else None
187
+ if keyword_name == "scope":
188
+ new_arg = cst.Arg(
189
+ keyword=cst.Name("nf_scope"),
190
+ value=arg.value,
191
+ equal=cst.AssignEqual(
192
+ whitespace_before=cst.SimpleWhitespace(""),
193
+ whitespace_after=cst.SimpleWhitespace(""),
194
+ ),
195
+ )
196
+ new_args.append(new_arg)
197
+ else:
198
+ new_args.append(arg)
199
+
200
+ # Create the new direct-binding call
201
+ new_call = inner_call.with_changes(args=new_args)
202
+ new_value = self._inject_nf_id(new_call, var_name)
203
+
204
+ # Get the type from Bind[Type] if present
205
+ extracted_type = self._get_type_from_bind_annotation(
206
+ updated_node.annotation,
207
+ )
208
+
209
+ if extracted_type:
210
+ # Bind[Type] -> keep annotation as Type
211
+ return updated_node.with_changes(
212
+ annotation=cst.Annotation(annotation=extracted_type),
213
+ value=new_value,
214
+ )
215
+ # Plain Bind -> convert to regular assignment
216
+ return cst.Assign(
217
+ targets=[cst.AssignTarget(target=updated_node.target)],
218
+ value=new_value,
219
+ )
220
+
221
+ # Check if value is a regular call (construct instantiation)
222
+ if isinstance(updated_node.value, cst.Call):
223
+ # Get the type from Bind[Type] if present
224
+ extracted_type = self._get_type_from_bind_annotation(
225
+ updated_node.annotation,
226
+ )
227
+
228
+ # Transform the value: Vpc(...) -> Vpc(..., nf_id=var_name)
229
+ new_value = self._inject_nf_id(updated_node.value, var_name)
230
+
231
+ if extracted_type:
232
+ # Bind[Type] -> keep annotation as Type
233
+ return updated_node.with_changes(
234
+ annotation=cst.Annotation(annotation=extracted_type),
235
+ value=new_value,
236
+ )
237
+ # Plain Bind -> convert to regular assignment
238
+ return cst.Assign(
239
+ targets=[cst.AssignTarget(target=updated_node.target)],
240
+ value=new_value,
241
+ )
242
+
243
+ return updated_node
244
+
245
+ def leave_NamedExpr(
246
+ self,
247
+ original_node: cst.NamedExpr,
248
+ updated_node: cst.NamedExpr,
249
+ ) -> cst.NamedExpr:
250
+ """Transform walrus operator assignments - no automatic wrapping."""
251
+ # Walrus operator doesn't support type annotations
252
+ # So we don't wrap these automatically
253
+ return updated_node
254
+
255
+ def leave_DictElement(
256
+ self,
257
+ original_node: cst.DictElement,
258
+ updated_node: cst.DictElement,
259
+ ) -> cst.DictElement:
260
+ """Transform dictionary element assignments - no automatic wrapping."""
261
+ # Dictionary elements don't have type annotations
262
+ # So we don't wrap these automatically
263
+ return updated_node
264
+
265
+ def leave_With(self, original_node: cst.With, updated_node: cst.With) -> cst.With:
266
+ """Transform context manager assignments when BindContext is present."""
267
+ has_bind_context = any(self._is_bind_context(item.item) for item in updated_node.items)
268
+ if not has_bind_context:
269
+ return updated_node
270
+
271
+ new_items = []
272
+ for item in updated_node.items:
273
+ if item.asname and isinstance(item.item, cst.Call):
274
+ var_name = self._extract_asname(item.asname)
275
+ if var_name:
276
+ new_call = self._inject_nf_id(item.item, var_name)
277
+ item = item.with_changes(item=new_call)
278
+ new_items.append(item)
279
+
280
+ return updated_node.with_changes(items=new_items)
281
+
282
+ def leave_ListComp(
283
+ self,
284
+ original_node: cst.ListComp,
285
+ updated_node: cst.ListComp,
286
+ ) -> cst.ListComp:
287
+ """Transform list comprehensions - pass through element unchanged."""
288
+ # Don't transform construct calls inside list comprehensions
289
+ # They typically use loop variables that don't make good IDs
290
+ return updated_node
291
+
292
+ def leave_DictComp(
293
+ self,
294
+ original_node: cst.DictComp,
295
+ updated_node: cst.DictComp,
296
+ ) -> cst.DictComp:
297
+ """Transform dict comprehensions - pass through unchanged."""
298
+ # Don't transform construct calls inside dict comprehensions
299
+ return updated_node
300
+
301
+
302
+ def preprocess_source(source: str) -> str:
303
+ """Preprocess Python source code to inject variable names using LibCST.
304
+
305
+ Transforms: my_vpc: Bind = Vpc(...) -> my_vpc = Vpc(..., nf_id="my_vpc")
306
+
307
+ Args:
308
+ source: Python source code
309
+
310
+ Returns:
311
+ Transformed source code with injected nf_id values
312
+
313
+ """
314
+ try:
315
+ # Parse the source code
316
+ tree = cst.parse_module(source)
317
+
318
+ # Apply the transformation
319
+ transformer = LibCSTTransformer()
320
+ modified_tree = tree.visit(transformer)
321
+
322
+ # Return the modified code
323
+ return modified_tree.code
324
+ except Exception:
325
+ # On any error, return the original source
326
+ # This ensures imports don't break
327
+ return source
328
+
329
+
330
+ # Codec implementation
331
+ def create_autoid_codec() -> codecs.CodecInfo:
332
+ """Create a codec that uses our preprocessor."""
333
+ from codecs import utf_8_encode
334
+
335
+ class AutoIdIncrementalDecoder(codecs.BufferedIncrementalDecoder):
336
+ def _buffer_decode( # ty: ignore[invalid-method-override]
337
+ self,
338
+ input_data: Buffer,
339
+ errors: str,
340
+ final: bool,
341
+ ) -> tuple[str, int]:
342
+ if not final:
343
+ return "", 0
344
+ # Decode as UTF-8 first
345
+ input_bytes = bytes(input_data)
346
+ data = input_bytes.decode("utf-8", errors)
347
+ # Apply our preprocessing
348
+ processed = preprocess_source(data)
349
+ return processed, len(input_bytes)
350
+
351
+ def autoid_decode(input_data: Buffer, errors: str = "strict") -> tuple[str, int]:
352
+ input_bytes = bytes(input_data)
353
+ data = input_bytes.decode("utf-8", errors)
354
+ processed = preprocess_source(data)
355
+ return processed, len(input_bytes)
356
+
357
+ return codecs.CodecInfo(
358
+ name="nf_autoid",
359
+ encode=utf_8_encode,
360
+ decode=autoid_decode,
361
+ incrementalencoder=None,
362
+ incrementaldecoder=AutoIdIncrementalDecoder,
363
+ )
364
+
365
+
366
+ # Registration lives in codec_registration so the startup .pth can avoid libcst.
367
+ register_codec()
File without changes
@@ -0,0 +1 @@
1
+ import netherframe.codec.autoid.codec_registration
@@ -0,0 +1 @@
1
+ netherframe.codec.autoid.codec_registration:register_codec
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: netherframe.codec.autoid
3
+ Version: 0.3.0
4
+ Summary: Auto-ID codec and preprocessor for Netherframe
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Dist: libcst>=1.9.0
8
+ Requires-Python: >=3.14
9
+ Project-URL: Homepage, https://netherframe.arsenal.sh
10
+ Project-URL: Repository, https://github.com/arsenal-sh/netherframe
11
+ Description-Content-Type: text/markdown
12
+
13
+ # nf.codec.autoid
14
+
15
+ Auto-ID source codec and preprocessor used by Netherframe.
@@ -0,0 +1,14 @@
1
+ netherframe/codec/autoid/__init__.py,sha256=t9I-yQ4e2ke1aw4y8tlfXUV5qHMNZNqZ21ANsJbGTC0,634
2
+ netherframe/codec/autoid/codec_registration.py,sha256=oaYH6u5ncpO5G9meWOHbKabmbV_6h6gAgtvsyT0cPXU,979
3
+ netherframe/codec/autoid/preprocessor.py,sha256=XtXQTFd6YX8tgSM_OegkVD5RcJd_WE-ifdJgBOME9Z0,13984
4
+ netherframe/codec/autoid/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ nf/codec/autoid/__init__.py,sha256=eP5K7imvmfAbxP3T5AxAeVGUVAWPYCEOiOO8oC-Uako,238
6
+ nf/codec/autoid/codec_registration.py,sha256=bCKFpp8tEW_kWPj-Gz0-tPg2Nw_EyHIaRpGezTYxUd8,295
7
+ nf/codec/autoid/preprocessor.py,sha256=xM8cgR0qqIw27lyzDulHlo88Zu2JX2k4tMtE-4Hxhk0,277
8
+ nf/codec/autoid/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ netherframe_codec_autoid-0.3.0.dist-info/licenses/LICENSE,sha256=CmCIBOHbWRqBeux1f3l5G7rXwtrrtVCZwymYiSoAYoE,1068
10
+ netherframe_codec_autoid-0.3.0.data/purelib/nf_codec_autoid_autoregister.pth,sha256=LEpYffgLOmpRNaPPPrPTaF8B95l0N4Bv9TmDBkMsiIk,51
11
+ netherframe_codec_autoid-0.3.0.data/purelib/nf_codec_autoid_autoregister.start,sha256=MumtfJvSQr6yUC0AL7ptBDJwNzt0ynog_P5-nE-SGJI,59
12
+ netherframe_codec_autoid-0.3.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
13
+ netherframe_codec_autoid-0.3.0.dist-info/METADATA,sha256=v5lGjYZWBCdKxcNJFeSgfZLNL81WKRonnFtYQASbfF0,463
14
+ netherframe_codec_autoid-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.9
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Netherframe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ # Generated nf.* alias shim (netherframe.generation.nf_alias_shims); do not edit.
2
+ """Type-checker view of ``nf.codec.autoid``; at runtime it is ``netherframe.codec.autoid`` itself."""
3
+
4
+ from netherframe.codec.autoid import * # noqa: F403
@@ -0,0 +1,4 @@
1
+ # Generated nf.* alias shim (netherframe.generation.nf_alias_shims); do not edit.
2
+ """Type-checker view of ``nf.codec.autoid.codec_registration``; at runtime it is ``netherframe.codec.autoid.codec_registration`` itself."""
3
+
4
+ from netherframe.codec.autoid.codec_registration import * # noqa: F403
@@ -0,0 +1,4 @@
1
+ # Generated nf.* alias shim (netherframe.generation.nf_alias_shims); do not edit.
2
+ """Type-checker view of ``nf.codec.autoid.preprocessor``; at runtime it is ``netherframe.codec.autoid.preprocessor`` itself."""
3
+
4
+ from netherframe.codec.autoid.preprocessor import * # noqa: F403
File without changes