mapFolding 0.9.3__py3-none-any.whl → 0.9.4__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.
- mapFolding/Z0Z_flowControl.py +26 -8
- mapFolding/someAssemblyRequired/Z0Z_makeSomeModules.py +226 -0
- mapFolding/someAssemblyRequired/__init__.py +11 -1
- mapFolding/someAssemblyRequired/_theTypes.py +10 -4
- mapFolding/someAssemblyRequired/_tool_Make.py +8 -0
- mapFolding/someAssemblyRequired/_tool_Then.py +44 -1
- mapFolding/someAssemblyRequired/_toolboxAST.py +57 -0
- mapFolding/someAssemblyRequired/_toolboxAntecedents.py +95 -29
- mapFolding/someAssemblyRequired/_toolboxContainers.py +4 -8
- mapFolding/someAssemblyRequired/_toolboxPython.py +52 -50
- mapFolding/someAssemblyRequired/synthesizeNumbaJob.py +3 -2
- mapFolding/someAssemblyRequired/transformationTools.py +39 -57
- mapFolding/syntheticModules/dataPacking.py +25 -0
- mapFolding/syntheticModules/initializeCount.py +49 -0
- mapFolding/syntheticModules/theorem2.py +49 -0
- mapFolding/syntheticModules/theorem2Numba.py +51 -0
- {mapfolding-0.9.3.dist-info → mapfolding-0.9.4.dist-info}/METADATA +2 -1
- {mapfolding-0.9.3.dist-info → mapfolding-0.9.4.dist-info}/RECORD +24 -18
- {mapfolding-0.9.3.dist-info → mapfolding-0.9.4.dist-info}/WHEEL +1 -1
- tests/test_computations.py +4 -2
- /mapFolding/{theDaoOfMapFolding.py → daoOfMapFolding.py} +0 -0
- {mapfolding-0.9.3.dist-info → mapfolding-0.9.4.dist-info}/entry_points.txt +0 -0
- {mapfolding-0.9.3.dist-info → mapfolding-0.9.4.dist-info}/licenses/LICENSE +0 -0
- {mapfolding-0.9.3.dist-info → mapfolding-0.9.4.dist-info}/top_level.txt +0 -0
|
@@ -1,36 +1,39 @@
|
|
|
1
1
|
"""
|
|
2
2
|
AST Node Predicate and Access Utilities for Pattern Matching and Traversal
|
|
3
3
|
|
|
4
|
-
This module provides utilities for accessing and matching AST nodes in a consistent way.
|
|
5
|
-
|
|
4
|
+
This module provides utilities for accessing and matching AST nodes in a consistent way. It contains three primary
|
|
5
|
+
classes:
|
|
6
6
|
|
|
7
|
-
1. DOT: Provides consistent accessor methods for AST node attributes across different
|
|
8
|
-
|
|
7
|
+
1. DOT: Provides consistent accessor methods for AST node attributes across different node types, simplifying the access
|
|
8
|
+
to node properties.
|
|
9
9
|
|
|
10
|
-
2. be: Offers type-guard functions that verify AST node types, enabling safe type
|
|
11
|
-
|
|
10
|
+
2. be: Offers type-guard functions that verify AST node types, enabling safe type narrowing for static type checking and
|
|
11
|
+
improving code safety.
|
|
12
12
|
|
|
13
|
-
3. ifThis: Contains predicate functions for matching AST nodes based on various criteria,
|
|
14
|
-
|
|
13
|
+
3. ifThis: Contains predicate functions for matching AST nodes based on various criteria, enabling precise targeting of
|
|
14
|
+
nodes for analysis or transformation.
|
|
15
15
|
|
|
16
|
-
These utilities form the foundation of the pattern-matching component in the AST
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
type verification (be), and data access (DOT).
|
|
16
|
+
These utilities form the foundation of the pattern-matching component in the AST manipulation framework, working in
|
|
17
|
+
conjunction with the NodeChanger and NodeTourist classes to enable precise and targeted code transformations. Together,
|
|
18
|
+
they implement a declarative approach to AST manipulation that separates node identification (ifThis), type verification
|
|
19
|
+
(be), and data access (DOT).
|
|
21
20
|
"""
|
|
22
21
|
|
|
23
22
|
from collections.abc import Callable
|
|
24
23
|
from mapFolding.someAssemblyRequired import (
|
|
25
24
|
ast_Identifier,
|
|
25
|
+
astClassHasDOTbody,
|
|
26
|
+
astClassHasDOTbody_expr,
|
|
27
|
+
astClassHasDOTbodyList_stmt,
|
|
26
28
|
astClassHasDOTnameNotName,
|
|
29
|
+
astClassHasDOTnameNotNameAlways,
|
|
30
|
+
astClassHasDOTnameNotNameOptionally,
|
|
31
|
+
astClassHasDOTtarget_expr,
|
|
27
32
|
astClassHasDOTtarget,
|
|
28
33
|
astClassHasDOTtargetAttributeNameSubscript,
|
|
29
|
-
astClassHasDOTtarget_expr,
|
|
30
|
-
astClassHasDOTvalue,
|
|
31
34
|
astClassHasDOTvalue_expr,
|
|
32
|
-
astClassOptionallyHasDOTnameNotName,
|
|
33
35
|
astClassHasDOTvalue_exprNone,
|
|
36
|
+
astClassHasDOTvalue,
|
|
34
37
|
ImaCallToName,
|
|
35
38
|
)
|
|
36
39
|
from typing import Any, overload, TypeGuard
|
|
@@ -72,6 +75,16 @@ class DOT:
|
|
|
72
75
|
def attr(node: ast.Attribute) -> ast_Identifier:
|
|
73
76
|
return node.attr
|
|
74
77
|
|
|
78
|
+
@staticmethod
|
|
79
|
+
@overload
|
|
80
|
+
def body(node: astClassHasDOTbodyList_stmt) -> list[ast.stmt]:...
|
|
81
|
+
@staticmethod
|
|
82
|
+
@overload
|
|
83
|
+
def body(node: astClassHasDOTbody_expr) -> ast.expr:...
|
|
84
|
+
@staticmethod
|
|
85
|
+
def body(node: astClassHasDOTbody) -> ast.expr | list[ast.stmt]:
|
|
86
|
+
return node.body
|
|
87
|
+
|
|
75
88
|
@staticmethod
|
|
76
89
|
@overload
|
|
77
90
|
def func(node: ImaCallToName) -> ast.Name:...
|
|
@@ -88,12 +101,12 @@ class DOT:
|
|
|
88
101
|
|
|
89
102
|
@staticmethod
|
|
90
103
|
@overload
|
|
91
|
-
def name(node:
|
|
104
|
+
def name(node: astClassHasDOTnameNotNameAlways) -> ast_Identifier:...
|
|
92
105
|
@staticmethod
|
|
93
106
|
@overload
|
|
94
|
-
def name(node:
|
|
107
|
+
def name(node: astClassHasDOTnameNotNameOptionally) -> ast_Identifier | None:...
|
|
95
108
|
@staticmethod
|
|
96
|
-
def name(node: astClassHasDOTnameNotName
|
|
109
|
+
def name(node: astClassHasDOTnameNotName) -> ast_Identifier | None:
|
|
97
110
|
return node.name
|
|
98
111
|
|
|
99
112
|
@staticmethod
|
|
@@ -129,18 +142,16 @@ class be:
|
|
|
129
142
|
"""
|
|
130
143
|
Provide type-guard functions for safely verifying AST node types during manipulation.
|
|
131
144
|
|
|
132
|
-
The be class contains static methods that perform runtime type verification of AST nodes,
|
|
133
|
-
|
|
134
|
-
conditional branches. These type-guards:
|
|
145
|
+
The be class contains static methods that perform runtime type verification of AST nodes, returning TypeGuard
|
|
146
|
+
results that enable static type checkers to narrow node types in conditional branches. These type-guards:
|
|
135
147
|
|
|
136
|
-
1. Improve code safety by preventing operations on incompatible node types
|
|
137
|
-
2. Enable IDE tooling to provide better autocompletion and error detection
|
|
138
|
-
3. Document expected node types in a way that's enforced by the type system
|
|
139
|
-
4. Support pattern-matching workflows where node types must be verified before access
|
|
148
|
+
1. Improve code safety by preventing operations on incompatible node types.
|
|
149
|
+
2. Enable IDE tooling to provide better autocompletion and error detection.
|
|
150
|
+
3. Document expected node types in a way that's enforced by the type system.
|
|
151
|
+
4. Support pattern-matching workflows where node types must be verified before access.
|
|
140
152
|
|
|
141
|
-
When used with conditional statements, these type-guards allow for precise,
|
|
142
|
-
|
|
143
|
-
capabilities, even in complex transformation scenarios.
|
|
153
|
+
When used with conditional statements, these type-guards allow for precise, type-safe manipulation of AST nodes
|
|
154
|
+
while maintaining full static type checking capabilities, even in complex transformation scenarios.
|
|
144
155
|
"""
|
|
145
156
|
@staticmethod
|
|
146
157
|
def AnnAssign(node: ast.AST) -> TypeGuard[ast.AnnAssign]:
|
|
@@ -170,6 +181,14 @@ class be:
|
|
|
170
181
|
def ClassDef(node: ast.AST) -> TypeGuard[ast.ClassDef]:
|
|
171
182
|
return isinstance(node, ast.ClassDef)
|
|
172
183
|
|
|
184
|
+
@staticmethod
|
|
185
|
+
def Compare(node: ast.AST) -> TypeGuard[ast.Compare]:
|
|
186
|
+
return isinstance(node, ast.Compare)
|
|
187
|
+
|
|
188
|
+
@staticmethod
|
|
189
|
+
def Constant(node: ast.AST) -> TypeGuard[ast.Constant]:
|
|
190
|
+
return isinstance(node, ast.Constant)
|
|
191
|
+
|
|
173
192
|
@staticmethod
|
|
174
193
|
def FunctionDef(node: ast.AST) -> TypeGuard[ast.FunctionDef]:
|
|
175
194
|
return isinstance(node, ast.FunctionDef)
|
|
@@ -178,6 +197,18 @@ class be:
|
|
|
178
197
|
def keyword(node: ast.AST) -> TypeGuard[ast.keyword]:
|
|
179
198
|
return isinstance(node, ast.keyword)
|
|
180
199
|
|
|
200
|
+
@staticmethod
|
|
201
|
+
def If(node: ast.AST) -> TypeGuard[ast.If]:
|
|
202
|
+
return isinstance(node, ast.If)
|
|
203
|
+
|
|
204
|
+
@staticmethod
|
|
205
|
+
def Gt(node: ast.AST) -> TypeGuard[ast.Gt]:
|
|
206
|
+
return isinstance(node, ast.Gt)
|
|
207
|
+
|
|
208
|
+
@staticmethod
|
|
209
|
+
def LtE(node: ast.AST) -> TypeGuard[ast.LtE]:
|
|
210
|
+
return isinstance(node, ast.LtE)
|
|
211
|
+
|
|
181
212
|
@staticmethod
|
|
182
213
|
def Name(node: ast.AST) -> TypeGuard[ast.Name]:
|
|
183
214
|
return isinstance(node, ast.Name)
|
|
@@ -194,6 +225,14 @@ class be:
|
|
|
194
225
|
def Subscript(node: ast.AST) -> TypeGuard[ast.Subscript]:
|
|
195
226
|
return isinstance(node, ast.Subscript)
|
|
196
227
|
|
|
228
|
+
@staticmethod
|
|
229
|
+
def Tuple(node: ast.AST) -> TypeGuard[ast.Tuple]:
|
|
230
|
+
return isinstance(node, ast.Tuple)
|
|
231
|
+
|
|
232
|
+
@staticmethod
|
|
233
|
+
def While(node: ast.AST) -> TypeGuard[ast.While]:
|
|
234
|
+
return isinstance(node, ast.While)
|
|
235
|
+
|
|
197
236
|
class ifThis:
|
|
198
237
|
"""
|
|
199
238
|
Provide predicate functions for matching and filtering AST nodes based on various criteria.
|
|
@@ -257,6 +296,29 @@ class ifThis:
|
|
|
257
296
|
def isAttributeNamespace_Identifier(namespace: ast_Identifier, identifier: ast_Identifier) -> Callable[[ast.AST], TypeGuard[ast.Attribute] | bool]:
|
|
258
297
|
return lambda node: ifThis.isAttributeName(node) and ifThis.isName_Identifier(namespace)(DOT.value(node)) and ifThis._Identifier(identifier)(DOT.attr(node))
|
|
259
298
|
|
|
299
|
+
@staticmethod
|
|
300
|
+
def isAttributeNamespace_IdentifierGreaterThan0(namespace: ast_Identifier, identifier: ast_Identifier) -> Callable[[ast.AST], TypeGuard[ast.Compare] | bool]:
|
|
301
|
+
return lambda node: (be.Compare(node)
|
|
302
|
+
and ifThis.isAttributeNamespace_Identifier(namespace, identifier)(node.left)
|
|
303
|
+
and be.Gt(node.ops[0])
|
|
304
|
+
and ifThis.isConstant_value(0)(node.comparators[0]))
|
|
305
|
+
|
|
306
|
+
@staticmethod
|
|
307
|
+
def isIfAttributeNamespace_IdentifierGreaterThan0(namespace: ast_Identifier, identifier: ast_Identifier) -> Callable[[ast.AST], TypeGuard[ast.While] | bool]:
|
|
308
|
+
return lambda node: (be.If(node)
|
|
309
|
+
and ifThis.isAttributeNamespace_IdentifierGreaterThan0(namespace, identifier)(node.test))
|
|
310
|
+
|
|
311
|
+
@staticmethod
|
|
312
|
+
def isWhileAttributeNamespace_IdentifierGreaterThan0(namespace: ast_Identifier, identifier: ast_Identifier) -> Callable[[ast.AST], TypeGuard[ast.While] | bool]:
|
|
313
|
+
return lambda node: (be.While(node)
|
|
314
|
+
and ifThis.isAttributeNamespace_IdentifierGreaterThan0(namespace, identifier)(node.test))
|
|
315
|
+
|
|
316
|
+
@staticmethod
|
|
317
|
+
def isAttributeNamespace_IdentifierLessThanOrEqual(namespace: ast_Identifier, identifier: ast_Identifier) -> Callable[[ast.AST], TypeGuard[ast.Compare] | bool]:
|
|
318
|
+
return lambda node: (be.Compare(node)
|
|
319
|
+
and ifThis.isAttributeNamespace_Identifier(namespace, identifier)(node.left)
|
|
320
|
+
and be.LtE(node.ops[0]))
|
|
321
|
+
|
|
260
322
|
@staticmethod
|
|
261
323
|
def isAugAssign_targetIs(targetPredicate: Callable[[ast.expr], TypeGuard[ast.expr] | bool]) -> Callable[[ast.AST], TypeGuard[ast.AugAssign] | bool]:
|
|
262
324
|
def workhorse(node: ast.AST) -> TypeGuard[ast.AugAssign] | bool:
|
|
@@ -282,6 +344,10 @@ class ifThis:
|
|
|
282
344
|
def isClassDef_Identifier(identifier: ast_Identifier) -> Callable[[ast.AST], TypeGuard[ast.ClassDef] | bool]:
|
|
283
345
|
return lambda node: be.ClassDef(node) and ifThis._Identifier(identifier)(DOT.name(node))
|
|
284
346
|
|
|
347
|
+
@staticmethod
|
|
348
|
+
def isConstant_value(value: Any) -> Callable[[ast.AST], TypeGuard[ast.Constant] | bool]:
|
|
349
|
+
return lambda node: be.Constant(node) and DOT.value(node) == value
|
|
350
|
+
|
|
285
351
|
@staticmethod
|
|
286
352
|
def isFunctionDef_Identifier(identifier: ast_Identifier) -> Callable[[ast.AST], TypeGuard[ast.FunctionDef] | bool]:
|
|
287
353
|
return lambda node: be.FunctionDef(node) and ifThis._Identifier(identifier)(DOT.name(node))
|
|
@@ -32,8 +32,7 @@ class LedgerOfImports:
|
|
|
32
32
|
Track and manage import statements for programmatically generated code.
|
|
33
33
|
|
|
34
34
|
LedgerOfImports acts as a registry for import statements, maintaining a clean separation between the logical
|
|
35
|
-
structure of imports and their textual representation.
|
|
36
|
-
It enables:
|
|
35
|
+
structure of imports and their textual representation. It enables:
|
|
37
36
|
|
|
38
37
|
1. Tracking regular imports and import-from statements.
|
|
39
38
|
2. Adding imports programmatically during code transformation.
|
|
@@ -46,8 +45,6 @@ class LedgerOfImports:
|
|
|
46
45
|
"""
|
|
47
46
|
# TODO When resolving the ledger of imports, remove self-referential imports
|
|
48
47
|
|
|
49
|
-
type_ignores: list[ast.TypeIgnore]
|
|
50
|
-
|
|
51
48
|
def __init__(self, startWith: ast.AST | None = None, type_ignores: list[ast.TypeIgnore] | None = None) -> None:
|
|
52
49
|
self.dictionaryImportFrom: dict[str_nameDOTname, list[tuple[ast_Identifier, ast_Identifier | None]]] = defaultdict(list)
|
|
53
50
|
self.listImport: list[str_nameDOTname] = []
|
|
@@ -77,8 +74,6 @@ class LedgerOfImports:
|
|
|
77
74
|
self.type_ignores.extend(type_ignores)
|
|
78
75
|
|
|
79
76
|
def addImportFrom_asStr(self, moduleWithLogicalPath: str_nameDOTname, name: ast_Identifier, asname: ast_Identifier | None = None, type_ignores: list[ast.TypeIgnore] | None = None) -> None:
|
|
80
|
-
if moduleWithLogicalPath not in self.dictionaryImportFrom:
|
|
81
|
-
self.dictionaryImportFrom[moduleWithLogicalPath] = []
|
|
82
77
|
self.dictionaryImportFrom[moduleWithLogicalPath].append((name, asname))
|
|
83
78
|
if type_ignores:
|
|
84
79
|
self.type_ignores.extend(type_ignores)
|
|
@@ -131,7 +126,8 @@ class LedgerOfImports:
|
|
|
131
126
|
Parameters:
|
|
132
127
|
*fromLedger: One or more other `LedgerOfImports` objects from which to merge.
|
|
133
128
|
"""
|
|
134
|
-
|
|
129
|
+
updatedDictionary = updateExtendPolishDictionaryLists(self.dictionaryImportFrom, *(ledger.dictionaryImportFrom for ledger in fromLedger), destroyDuplicates=True, reorderLists=True)
|
|
130
|
+
self.dictionaryImportFrom = defaultdict(list, updatedDictionary)
|
|
135
131
|
for ledger in fromLedger:
|
|
136
132
|
self.listImport.extend(ledger.listImport)
|
|
137
133
|
self.type_ignores.extend(ledger.type_ignores)
|
|
@@ -449,7 +445,7 @@ class ShatteredDataclass:
|
|
|
449
445
|
fragments4AssignmentOrParameters: ast.Tuple = dummyTuple
|
|
450
446
|
"""AST tuple used as target for assignment to capture returned fragments."""
|
|
451
447
|
|
|
452
|
-
|
|
448
|
+
imports: LedgerOfImports = dataclasses.field(default_factory=LedgerOfImports)
|
|
453
449
|
"""Import records for the dataclass and its constituent parts."""
|
|
454
450
|
|
|
455
451
|
list_argAnnotated4ArgumentsSpecification: list[ast.arg] = dataclasses.field(default_factory=list)
|
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
"""
|
|
2
2
|
Core AST Traversal and Transformation Utilities for Python Code Manipulation
|
|
3
3
|
|
|
4
|
-
This module provides the foundation for traversing and modifying Python Abstract
|
|
5
|
-
|
|
4
|
+
This module provides the foundation for traversing and modifying Python Abstract Syntax Trees (ASTs). It contains two
|
|
5
|
+
primary classes:
|
|
6
6
|
|
|
7
|
-
1. NodeTourist: Implements the visitor pattern to traverse an AST and extract information
|
|
8
|
-
|
|
7
|
+
1. NodeTourist: Implements the visitor pattern to traverse an AST and extract information from nodes that match specific
|
|
8
|
+
predicates without modifying the AST.
|
|
9
9
|
|
|
10
|
-
2. NodeChanger: Extends ast.NodeTransformer to selectively transform AST nodes that
|
|
11
|
-
|
|
10
|
+
2. NodeChanger: Extends ast.NodeTransformer to selectively transform AST nodes that match specific predicates, enabling
|
|
11
|
+
targeted code modifications.
|
|
12
12
|
|
|
13
|
-
The module also provides utilities for importing modules, loading callables from files,
|
|
14
|
-
|
|
15
|
-
analysis and transformation.
|
|
13
|
+
The module also provides utilities for importing modules, loading callables from files, and parsing Python code into AST
|
|
14
|
+
structures, creating a complete workflow for code analysis and transformation.
|
|
16
15
|
"""
|
|
17
16
|
|
|
18
17
|
from collections.abc import Callable
|
|
@@ -32,13 +31,12 @@ class NodeTourist(ast.NodeVisitor):
|
|
|
32
31
|
"""
|
|
33
32
|
Visit and extract information from AST nodes that match a predicate.
|
|
34
33
|
|
|
35
|
-
NodeTourist implements the visitor pattern to traverse an AST, applying
|
|
36
|
-
|
|
37
|
-
when they match. Unlike NodeChanger, it doesn't modify the AST but collects
|
|
34
|
+
NodeTourist implements the visitor pattern to traverse an AST, applying a predicate function to each node and
|
|
35
|
+
capturing nodes or their attributes when they match. Unlike NodeChanger, it doesn't modify the AST but collects
|
|
38
36
|
information during traversal.
|
|
39
37
|
|
|
40
|
-
This class is particularly useful for analyzing AST structures, extracting
|
|
41
|
-
|
|
38
|
+
This class is particularly useful for analyzing AST structures, extracting specific nodes or node properties, and
|
|
39
|
+
gathering information about code patterns.
|
|
42
40
|
"""
|
|
43
41
|
def __init__(self, findThis: Callable[..., Any], doThat: Callable[..., Any]) -> None:
|
|
44
42
|
self.findThis = findThis
|
|
@@ -61,12 +59,12 @@ class NodeChanger(ast.NodeTransformer):
|
|
|
61
59
|
"""
|
|
62
60
|
Transform AST nodes that match a predicate by applying a transformation function.
|
|
63
61
|
|
|
64
|
-
NodeChanger is an AST node transformer that applies a targeted transformation
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
NodeChanger is an AST node transformer that applies a targeted transformation to nodes matching a specific
|
|
63
|
+
predicate. It traverses the AST and only modifies nodes that satisfy the predicate condition, leaving other nodes
|
|
64
|
+
unchanged.
|
|
67
65
|
|
|
68
|
-
This class extends ast.NodeTransformer and implements the visitor pattern
|
|
69
|
-
|
|
66
|
+
This class extends ast.NodeTransformer and implements the visitor pattern to systematically process and transform an
|
|
67
|
+
AST tree.
|
|
70
68
|
"""
|
|
71
69
|
def __init__(self, findThis: Callable[..., Any], doThat: Callable[..., Any]) -> None:
|
|
72
70
|
self.findThis = findThis
|
|
@@ -81,18 +79,18 @@ def importLogicalPath2Callable(logicalPathModule: str_nameDOTname, identifier: a
|
|
|
81
79
|
"""
|
|
82
80
|
Import a callable object (function or class) from a module based on its logical path.
|
|
83
81
|
|
|
84
|
-
This function imports a module using `importlib.import_module()` and then retrieves
|
|
85
|
-
|
|
82
|
+
This function imports a module using `importlib.import_module()` and then retrieves a specific attribute (function,
|
|
83
|
+
class, or other object) from that module.
|
|
86
84
|
|
|
87
85
|
Parameters
|
|
88
86
|
----------
|
|
89
|
-
logicalPathModule
|
|
87
|
+
logicalPathModule
|
|
90
88
|
The logical path to the module, using dot notation (e.g., 'package.subpackage.module').
|
|
91
|
-
identifier
|
|
89
|
+
identifier
|
|
92
90
|
The name of the callable object to retrieve from the module.
|
|
93
|
-
packageIdentifierIfRelative :
|
|
94
|
-
The package name to use as the anchor point if `logicalPathModule` is a relative import.
|
|
95
|
-
|
|
91
|
+
packageIdentifierIfRelative : None
|
|
92
|
+
The package name to use as the anchor point if `logicalPathModule` is a relative import. If None, absolute
|
|
93
|
+
import is assumed.
|
|
96
94
|
|
|
97
95
|
Returns
|
|
98
96
|
-------
|
|
@@ -105,16 +103,17 @@ def importLogicalPath2Callable(logicalPathModule: str_nameDOTname, identifier: a
|
|
|
105
103
|
def importPathFilename2Callable(pathFilename: PathLike[Any] | PurePath, identifier: ast_Identifier, moduleIdentifier: ast_Identifier | None = None) -> Callable[..., Any]:
|
|
106
104
|
"""
|
|
107
105
|
Load a callable (function, class, etc.) from a Python file.
|
|
108
|
-
|
|
109
|
-
from it by name, and returns
|
|
106
|
+
|
|
107
|
+
This function imports a specified Python file as a module, extracts a callable object from it by name, and returns
|
|
108
|
+
that callable.
|
|
110
109
|
|
|
111
110
|
Parameters
|
|
112
111
|
----------
|
|
113
|
-
pathFilename
|
|
112
|
+
pathFilename
|
|
114
113
|
Path to the Python file to import.
|
|
115
|
-
identifier
|
|
114
|
+
identifier
|
|
116
115
|
Name of the callable to extract from the imported module.
|
|
117
|
-
moduleIdentifier
|
|
116
|
+
moduleIdentifier
|
|
118
117
|
Name to use for the imported module. If None, the filename stem is used.
|
|
119
118
|
|
|
120
119
|
Returns
|
|
@@ -138,49 +137,52 @@ def importPathFilename2Callable(pathFilename: PathLike[Any] | PurePath, identifi
|
|
|
138
137
|
importlibSpecification.loader.exec_module(moduleImported_jk_hahaha)
|
|
139
138
|
return getattr(moduleImported_jk_hahaha, identifier)
|
|
140
139
|
|
|
141
|
-
def parseLogicalPath2astModule(logicalPathModule: str_nameDOTname, packageIdentifierIfRelative: ast_Identifier|None=None, mode: Literal['exec'] = 'exec') -> ast.Module:
|
|
140
|
+
def parseLogicalPath2astModule(logicalPathModule: str_nameDOTname, packageIdentifierIfRelative: ast_Identifier | None = None, mode: Literal['exec'] = 'exec') -> ast.Module:
|
|
142
141
|
"""
|
|
143
|
-
Parse a logical Python module path into an
|
|
142
|
+
Parse a logical Python module path into an `ast.Module`.
|
|
144
143
|
|
|
145
|
-
This function imports a module using its logical path (e.g., 'package.subpackage.module')
|
|
146
|
-
|
|
144
|
+
This function imports a module using its logical path (e.g., 'package.subpackage.module') and converts its source
|
|
145
|
+
code into an Abstract Syntax Tree (AST) Module object.
|
|
147
146
|
|
|
148
147
|
Parameters
|
|
149
148
|
----------
|
|
150
|
-
logicalPathModule
|
|
149
|
+
logicalPathModule
|
|
151
150
|
The logical path to the module using dot notation (e.g., 'package.module').
|
|
152
|
-
packageIdentifierIfRelative :
|
|
151
|
+
packageIdentifierIfRelative : None
|
|
153
152
|
The package identifier to use if the module path is relative, defaults to None.
|
|
154
|
-
mode : Literal['exec']
|
|
155
|
-
The
|
|
153
|
+
mode : Literal['exec']
|
|
154
|
+
The mode parameter for `ast.parse`. Default is `Literal['exec']`. Options are `Literal['exec']`, `"exec"` (which
|
|
155
|
+
is _not_ the same as `Literal['exec']`), `Literal['eval']`, `Literal['func_type']`, `Literal['single']`. See
|
|
156
|
+
`ast.parse` documentation for some details and much confusion.
|
|
156
157
|
|
|
157
158
|
Returns
|
|
158
159
|
-------
|
|
159
|
-
|
|
160
|
+
astModule
|
|
160
161
|
An AST Module object representing the parsed source code of the imported module.
|
|
161
162
|
"""
|
|
162
163
|
moduleImported: ModuleType = importlib.import_module(logicalPathModule, packageIdentifierIfRelative)
|
|
163
164
|
sourcePython: str = inspect_getsource(moduleImported)
|
|
164
|
-
return ast.parse(sourcePython, mode
|
|
165
|
+
return ast.parse(sourcePython, mode)
|
|
165
166
|
|
|
166
167
|
def parsePathFilename2astModule(pathFilename: PathLike[Any] | PurePath, mode: Literal['exec'] = 'exec') -> ast.Module:
|
|
167
168
|
"""
|
|
168
|
-
Parse a file from a given path into an ast.Module
|
|
169
|
+
Parse a file from a given path into an `ast.Module`.
|
|
169
170
|
|
|
170
|
-
This function reads the content of a file specified by `pathFilename` and parses it into an
|
|
171
|
-
|
|
171
|
+
This function reads the content of a file specified by `pathFilename` and parses it into an Abstract Syntax Tree
|
|
172
|
+
(AST) Module using Python's ast module.
|
|
172
173
|
|
|
173
174
|
Parameters
|
|
174
175
|
----------
|
|
175
|
-
pathFilename
|
|
176
|
+
pathFilename
|
|
176
177
|
The path to the file to be parsed. Can be a string path, PathLike object, or PurePath object.
|
|
177
|
-
mode : Literal['exec']
|
|
178
|
-
The mode parameter for ast.parse
|
|
179
|
-
|
|
178
|
+
mode : Literal['exec']
|
|
179
|
+
The mode parameter for `ast.parse`. Default is `Literal['exec']`. Options are `Literal['exec']`, `"exec"` (which
|
|
180
|
+
is _not_ the same as `Literal['exec']`), `Literal['eval']`, `Literal['func_type']`, `Literal['single']`. See
|
|
181
|
+
`ast.parse` documentation for some details and much confusion.
|
|
180
182
|
|
|
181
183
|
Returns
|
|
182
184
|
-------
|
|
183
|
-
|
|
185
|
+
astModule
|
|
184
186
|
The parsed abstract syntax tree module.
|
|
185
187
|
"""
|
|
186
|
-
return ast.parse(Path(pathFilename).read_text(), mode
|
|
188
|
+
return ast.parse(Path(pathFilename).read_text(), mode)
|
|
@@ -22,6 +22,7 @@ from mapFolding import getPathFilenameFoldsTotal, raiseIfNoneGitHubIssueNumber3,
|
|
|
22
22
|
from mapFolding.someAssemblyRequired import (
|
|
23
23
|
ast_Identifier,
|
|
24
24
|
be,
|
|
25
|
+
extractFunctionDef,
|
|
25
26
|
ifThis,
|
|
26
27
|
IngredientsFunction,
|
|
27
28
|
IngredientsModule,
|
|
@@ -34,7 +35,7 @@ from mapFolding.someAssemblyRequired import (
|
|
|
34
35
|
)
|
|
35
36
|
from mapFolding.someAssemblyRequired.RecipeJob import RecipeJob
|
|
36
37
|
from mapFolding.someAssemblyRequired.toolboxNumba import parametersNumbaLight, SpicesJobNumba, decorateCallableWithNumba
|
|
37
|
-
from mapFolding.someAssemblyRequired.transformationTools import dictionaryEstimates,
|
|
38
|
+
from mapFolding.someAssemblyRequired.transformationTools import dictionaryEstimates, write_astModule, makeInitializedComputationState
|
|
38
39
|
from pathlib import PurePosixPath
|
|
39
40
|
from typing import cast, NamedTuple
|
|
40
41
|
from Z0Z_tools import autoDecodingRLE
|
|
@@ -131,7 +132,7 @@ def move_arg2FunctionDefDOTbodyAndAssignInitialValues(ingredientsFunction: Ingre
|
|
|
131
132
|
Returns:
|
|
132
133
|
The modified function with parameters converted to initialized variables.
|
|
133
134
|
"""
|
|
134
|
-
ingredientsFunction.imports.update(job.shatteredDataclass.
|
|
135
|
+
ingredientsFunction.imports.update(job.shatteredDataclass.imports)
|
|
135
136
|
|
|
136
137
|
list_argCuzMyBrainRefusesToThink = ingredientsFunction.astFunctionDef.args.args + ingredientsFunction.astFunctionDef.args.posonlyargs + ingredientsFunction.astFunctionDef.args.kwonlyargs
|
|
137
138
|
list_arg_arg: list[ast_Identifier] = [ast_arg.arg for ast_arg in list_argCuzMyBrainRefusesToThink]
|
|
@@ -22,11 +22,12 @@ from autoflake import fix_code as autoflake_fix_code
|
|
|
22
22
|
from collections.abc import Callable, Mapping
|
|
23
23
|
from copy import deepcopy
|
|
24
24
|
from mapFolding.beDRY import outfitCountFolds
|
|
25
|
-
from mapFolding.toolboxFilesystem import getPathFilenameFoldsTotal, writeStringToHere
|
|
26
25
|
from mapFolding.someAssemblyRequired import (
|
|
27
26
|
ast_Identifier,
|
|
27
|
+
astModuleToIngredientsFunction,
|
|
28
28
|
be,
|
|
29
29
|
DOT,
|
|
30
|
+
extractClassDef,
|
|
30
31
|
grab,
|
|
31
32
|
ifThis,
|
|
32
33
|
importLogicalPath2Callable,
|
|
@@ -44,6 +45,7 @@ from mapFolding.someAssemblyRequired import (
|
|
|
44
45
|
个,
|
|
45
46
|
)
|
|
46
47
|
from mapFolding.theSSOT import ComputationState, raiseIfNoneGitHubIssueNumber3, The
|
|
48
|
+
from mapFolding.toolboxFilesystem import getPathFilenameFoldsTotal, writeStringToHere
|
|
47
49
|
from os import PathLike
|
|
48
50
|
from pathlib import Path, PurePath
|
|
49
51
|
from typing import Any, Literal, overload
|
|
@@ -52,59 +54,6 @@ import dataclasses
|
|
|
52
54
|
import pickle
|
|
53
55
|
import python_minifier
|
|
54
56
|
|
|
55
|
-
def astModuleToIngredientsFunction(astModule: ast.AST, identifierFunctionDef: ast_Identifier) -> IngredientsFunction:
|
|
56
|
-
"""
|
|
57
|
-
Extract a function definition from an AST module and create an IngredientsFunction.
|
|
58
|
-
|
|
59
|
-
This function finds a function definition with the specified identifier in the given
|
|
60
|
-
AST module and wraps it in an IngredientsFunction object along with its import context.
|
|
61
|
-
|
|
62
|
-
Parameters:
|
|
63
|
-
astModule: The AST module containing the function definition.
|
|
64
|
-
identifierFunctionDef: The name of the function to extract.
|
|
65
|
-
|
|
66
|
-
Returns:
|
|
67
|
-
An IngredientsFunction object containing the function definition and its imports.
|
|
68
|
-
|
|
69
|
-
Raises:
|
|
70
|
-
raiseIfNoneGitHubIssueNumber3: If the function definition is not found.
|
|
71
|
-
"""
|
|
72
|
-
astFunctionDef = extractFunctionDef(astModule, identifierFunctionDef)
|
|
73
|
-
if not astFunctionDef: raise raiseIfNoneGitHubIssueNumber3
|
|
74
|
-
return IngredientsFunction(astFunctionDef, LedgerOfImports(astModule))
|
|
75
|
-
|
|
76
|
-
def extractClassDef(module: ast.AST, identifier: ast_Identifier) -> ast.ClassDef | None:
|
|
77
|
-
"""
|
|
78
|
-
Extract a class definition with a specific name from an AST module.
|
|
79
|
-
|
|
80
|
-
This function searches through an AST module for a class definition that
|
|
81
|
-
matches the provided identifier and returns it if found.
|
|
82
|
-
|
|
83
|
-
Parameters:
|
|
84
|
-
module: The AST module to search within.
|
|
85
|
-
identifier: The name of the class to find.
|
|
86
|
-
|
|
87
|
-
Returns:
|
|
88
|
-
The matching class definition AST node, or None if not found.
|
|
89
|
-
"""
|
|
90
|
-
return NodeTourist(ifThis.isClassDef_Identifier(identifier), Then.extractIt).captureLastMatch(module)
|
|
91
|
-
|
|
92
|
-
def extractFunctionDef(module: ast.AST, identifier: ast_Identifier) -> ast.FunctionDef | None:
|
|
93
|
-
"""
|
|
94
|
-
Extract a function definition with a specific name from an AST module.
|
|
95
|
-
|
|
96
|
-
This function searches through an AST module for a function definition that
|
|
97
|
-
matches the provided identifier and returns it if found.
|
|
98
|
-
|
|
99
|
-
Parameters:
|
|
100
|
-
module: The AST module to search within.
|
|
101
|
-
identifier: The name of the function to find.
|
|
102
|
-
|
|
103
|
-
Returns:
|
|
104
|
-
astFunctionDef: The matching function definition AST node, or None if not found.
|
|
105
|
-
"""
|
|
106
|
-
return NodeTourist(ifThis.isFunctionDef_Identifier(identifier), Then.extractIt).captureLastMatch(module)
|
|
107
|
-
|
|
108
57
|
def makeDictionaryFunctionDef(module: ast.Module) -> dict[ast_Identifier, ast.FunctionDef]:
|
|
109
58
|
"""
|
|
110
59
|
Create a dictionary mapping function names to their AST definitions.
|
|
@@ -404,8 +353,8 @@ def shatter_dataclassesDOTdataclass(logicalPathModule: str_nameDOTname, dataclas
|
|
|
404
353
|
shatteredDataclass.repack = Make.Assign(listTargets=[Make.Name(instance_Identifier)], value=Make.Call(Make.Name(dataclass_Identifier), list_astKeywords=shatteredDataclass.list_keyword_field__field4init))
|
|
405
354
|
shatteredDataclass.signatureReturnAnnotation = Make.Subscript(Make.Name('tuple'), Make.Tuple(shatteredDataclass.listAnnotations))
|
|
406
355
|
|
|
407
|
-
shatteredDataclass.
|
|
408
|
-
shatteredDataclass.
|
|
356
|
+
shatteredDataclass.imports.update(*(dictionaryDeReConstruction[field].ledger for field in Official_fieldOrder))
|
|
357
|
+
shatteredDataclass.imports.addImportFrom_asStr(logicalPathModule, dataclass_Identifier)
|
|
409
358
|
|
|
410
359
|
return shatteredDataclass
|
|
411
360
|
|
|
@@ -448,6 +397,27 @@ def write_astModule(ingredients: IngredientsModule, pathFilename: PathLike[Any]
|
|
|
448
397
|
|
|
449
398
|
# END of acceptable classes and functions ======================================================
|
|
450
399
|
def removeUnusedParameters(ingredientsFunction: IngredientsFunction) -> IngredientsFunction:
|
|
400
|
+
"""
|
|
401
|
+
Removes unused parameters from a function's AST definition, return statement, and annotation.
|
|
402
|
+
|
|
403
|
+
This function analyzes the Abstract Syntax Tree (AST) of a given function and removes
|
|
404
|
+
any parameters that are not referenced within the function body. It updates the
|
|
405
|
+
function signature, the return statement (if it's a tuple containing unused variables),
|
|
406
|
+
and the return type annotation accordingly.
|
|
407
|
+
|
|
408
|
+
Parameters
|
|
409
|
+
----------
|
|
410
|
+
ingredientsFunction : IngredientsFunction
|
|
411
|
+
An object containing the AST representation of a function to be processed.
|
|
412
|
+
|
|
413
|
+
Returns
|
|
414
|
+
-------
|
|
415
|
+
IngredientsFunction
|
|
416
|
+
The modified IngredientsFunction object with unused parameters and corresponding
|
|
417
|
+
return elements/annotations removed from its AST.
|
|
418
|
+
|
|
419
|
+
The modification is done in-place on the original AST nodes within the IngredientsFunction object.
|
|
420
|
+
"""
|
|
451
421
|
list_argCuzMyBrainRefusesToThink = ingredientsFunction.astFunctionDef.args.args + ingredientsFunction.astFunctionDef.args.posonlyargs + ingredientsFunction.astFunctionDef.args.kwonlyargs
|
|
452
422
|
list_arg_arg: list[ast_Identifier] = [ast_arg.arg for ast_arg in list_argCuzMyBrainRefusesToThink]
|
|
453
423
|
listName: list[ast.Name] = []
|
|
@@ -459,6 +429,18 @@ def removeUnusedParameters(ingredientsFunction: IngredientsFunction) -> Ingredie
|
|
|
459
429
|
for arg_Identifier in list_IdentifiersNotUsed:
|
|
460
430
|
remove_arg = NodeChanger(ifThis.is_arg_Identifier(arg_Identifier), Then.removeIt)
|
|
461
431
|
remove_arg.visit(ingredientsFunction.astFunctionDef)
|
|
432
|
+
|
|
433
|
+
list_argCuzMyBrainRefusesToThink = ingredientsFunction.astFunctionDef.args.args + ingredientsFunction.astFunctionDef.args.posonlyargs + ingredientsFunction.astFunctionDef.args.kwonlyargs
|
|
434
|
+
|
|
435
|
+
listName: list[ast.Name] = [Make.Name(ast_arg.arg) for ast_arg in list_argCuzMyBrainRefusesToThink]
|
|
436
|
+
replaceReturn = NodeChanger(be.Return, Then.replaceWith(Make.Return(Make.Tuple(listName))))
|
|
437
|
+
replaceReturn.visit(ingredientsFunction.astFunctionDef)
|
|
438
|
+
|
|
439
|
+
list_annotation: list[ast.expr] = [ast_arg.annotation for ast_arg in list_argCuzMyBrainRefusesToThink if ast_arg.annotation is not None]
|
|
440
|
+
ingredientsFunction.astFunctionDef.returns = Make.Subscript(Make.Name('tuple'), Make.Tuple(list_annotation))
|
|
441
|
+
|
|
442
|
+
ast.fix_missing_locations(ingredientsFunction.astFunctionDef)
|
|
443
|
+
|
|
462
444
|
return ingredientsFunction
|
|
463
445
|
|
|
464
446
|
def makeNewFlow(recipeFlow: RecipeSynthesizeFlow) -> IngredientsModule:
|
|
@@ -514,7 +496,7 @@ def makeNewFlow(recipeFlow: RecipeSynthesizeFlow) -> IngredientsModule:
|
|
|
514
496
|
instance_Identifier = recipeFlow.dataclassInstance
|
|
515
497
|
getTheOtherRecord_damn = recipeFlow.dataclassInstanceTaskDistribution
|
|
516
498
|
shatteredDataclass = shatter_dataclassesDOTdataclass(recipeFlow.logicalPathModuleDataclass, recipeFlow.sourceDataclassIdentifier, instance_Identifier)
|
|
517
|
-
ingredientsDispatcher.imports.update(shatteredDataclass.
|
|
499
|
+
ingredientsDispatcher.imports.update(shatteredDataclass.imports)
|
|
518
500
|
|
|
519
501
|
# How can I use dataclass settings as the SSOT for specific actions? https://github.com/hunterhogan/mapFolding/issues/16
|
|
520
502
|
# Change callable parameters and Call to the callable at the same time ====
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from mapFolding.dataBaskets import Array1DElephino, Array1DLeavesTotal, Array3D, DatatypeElephino, DatatypeFoldsTotal, DatatypeLeavesTotal, MapFoldingState
|
|
2
|
+
from mapFolding.syntheticModules.theorem2Numba import count
|
|
3
|
+
|
|
4
|
+
def doTheNeedful(state: MapFoldingState) -> MapFoldingState:
|
|
5
|
+
mapShape: tuple[DatatypeLeavesTotal, ...] = state.mapShape
|
|
6
|
+
groupsOfFolds: DatatypeFoldsTotal = state.groupsOfFolds
|
|
7
|
+
gap1ndex: DatatypeElephino = state.gap1ndex
|
|
8
|
+
gap1ndexCeiling: DatatypeElephino = state.gap1ndexCeiling
|
|
9
|
+
indexDimension: DatatypeLeavesTotal = state.indexDimension
|
|
10
|
+
indexLeaf: DatatypeLeavesTotal = state.indexLeaf
|
|
11
|
+
indexMiniGap: DatatypeElephino = state.indexMiniGap
|
|
12
|
+
leaf1ndex: DatatypeLeavesTotal = state.leaf1ndex
|
|
13
|
+
leafConnectee: DatatypeLeavesTotal = state.leafConnectee
|
|
14
|
+
dimensionsUnconstrained: DatatypeLeavesTotal = state.dimensionsUnconstrained
|
|
15
|
+
countDimensionsGapped: Array1DLeavesTotal = state.countDimensionsGapped
|
|
16
|
+
gapRangeStart: Array1DElephino = state.gapRangeStart
|
|
17
|
+
gapsWhere: Array1DLeavesTotal = state.gapsWhere
|
|
18
|
+
leafAbove: Array1DLeavesTotal = state.leafAbove
|
|
19
|
+
leafBelow: Array1DLeavesTotal = state.leafBelow
|
|
20
|
+
connectionGraph: Array3D = state.connectionGraph
|
|
21
|
+
dimensionsTotal: DatatypeLeavesTotal = state.dimensionsTotal
|
|
22
|
+
leavesTotal: DatatypeLeavesTotal = state.leavesTotal
|
|
23
|
+
groupsOfFolds, gap1ndex, gap1ndexCeiling, indexDimension, indexLeaf, indexMiniGap, leaf1ndex, leafConnectee, dimensionsUnconstrained, countDimensionsGapped, gapRangeStart, gapsWhere, leafAbove, leafBelow, connectionGraph, dimensionsTotal, leavesTotal = count(groupsOfFolds, gap1ndex, gap1ndexCeiling, indexDimension, indexLeaf, indexMiniGap, leaf1ndex, leafConnectee, dimensionsUnconstrained, countDimensionsGapped, gapRangeStart, gapsWhere, leafAbove, leafBelow, connectionGraph, dimensionsTotal, leavesTotal)
|
|
24
|
+
state = MapFoldingState(mapShape=mapShape, groupsOfFolds=groupsOfFolds, gap1ndex=gap1ndex, gap1ndexCeiling=gap1ndexCeiling, indexDimension=indexDimension, indexLeaf=indexLeaf, indexMiniGap=indexMiniGap, leaf1ndex=leaf1ndex, leafConnectee=leafConnectee, dimensionsUnconstrained=dimensionsUnconstrained, countDimensionsGapped=countDimensionsGapped, gapRangeStart=gapRangeStart, gapsWhere=gapsWhere, leafAbove=leafAbove, leafBelow=leafBelow)
|
|
25
|
+
return state
|