mapFolding 0.12.0__py3-none-any.whl → 0.12.2__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/__init__.py +42 -18
- mapFolding/_theSSOT.py +137 -0
- mapFolding/basecamp.py +28 -18
- mapFolding/beDRY.py +21 -19
- mapFolding/dataBaskets.py +170 -18
- mapFolding/datatypes.py +109 -1
- mapFolding/filesystemToolkit.py +38 -33
- mapFolding/oeis.py +209 -93
- mapFolding/someAssemblyRequired/RecipeJob.py +120 -9
- mapFolding/someAssemblyRequired/__init__.py +35 -38
- mapFolding/someAssemblyRequired/_toolIfThis.py +80 -18
- mapFolding/someAssemblyRequired/_toolkitContainers.py +123 -45
- mapFolding/someAssemblyRequired/infoBooth.py +37 -2
- mapFolding/someAssemblyRequired/makeAllModules.py +712 -0
- mapFolding/someAssemblyRequired/makeJobTheorem2Numba.py +111 -48
- mapFolding/someAssemblyRequired/toolkitNumba.py +171 -19
- mapFolding/someAssemblyRequired/transformationTools.py +93 -49
- mapfolding-0.12.2.dist-info/METADATA +167 -0
- mapfolding-0.12.2.dist-info/RECORD +53 -0
- {mapfolding-0.12.0.dist-info → mapfolding-0.12.2.dist-info}/WHEEL +1 -1
- tests/__init__.py +28 -44
- tests/conftest.py +66 -61
- tests/test_computations.py +39 -82
- tests/test_filesystem.py +25 -1
- tests/test_oeis.py +30 -1
- tests/test_other.py +27 -0
- tests/test_tasks.py +31 -1
- mapFolding/someAssemblyRequired/Z0Z_makeAllModules.py +0 -433
- mapFolding/theSSOT.py +0 -34
- mapfolding-0.12.0.dist-info/METADATA +0 -184
- mapfolding-0.12.0.dist-info/RECORD +0 -53
- {mapfolding-0.12.0.dist-info → mapfolding-0.12.2.dist-info}/entry_points.txt +0 -0
- {mapfolding-0.12.0.dist-info → mapfolding-0.12.2.dist-info}/licenses/LICENSE +0 -0
- {mapfolding-0.12.0.dist-info → mapfolding-0.12.2.dist-info}/top_level.txt +0 -0
|
@@ -1,6 +1,39 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
"""
|
|
2
|
+
Map folding AST transformation system: Configuration management and transformation orchestration.
|
|
3
|
+
|
|
4
|
+
This module provides the configuration orchestration layer of the map folding AST transformation
|
|
5
|
+
system, implementing comprehensive recipes that coordinate the entire transformation process from
|
|
6
|
+
abstract mathematical algorithms to optimized computational modules. The `RecipeJobTheorem2Numba`
|
|
7
|
+
dataclass serves as the central configuration blueprint that bridges pattern recognition, dataclass
|
|
8
|
+
decomposition, function optimization, and Numba compilation into a unified transformation process.
|
|
9
|
+
|
|
10
|
+
The recipe system addresses the complexity of managing transformation parameters across multiple
|
|
11
|
+
stages while maintaining consistency between source algorithm metadata and target optimization
|
|
12
|
+
requirements. The orchestration layer coordinates the systematic extraction of mathematical
|
|
13
|
+
functions from source modules, embedding of concrete parameter values, elimination of dead code
|
|
14
|
+
paths, and generation of standalone Python modules optimized for specific map dimensions through
|
|
15
|
+
the complete transformation process.
|
|
16
|
+
|
|
17
|
+
Configuration management separates source analysis capabilities from target generation parameters,
|
|
18
|
+
enabling systematic exploration of computational spaces through automated generation of optimized
|
|
19
|
+
solvers. Source analysis encompasses parsing and analysis of abstract syntax trees from generic
|
|
20
|
+
algorithm modules, extraction of specific mathematical functions for specialization, and
|
|
21
|
+
identification of dataclass structures for parameter embedding. Target generation coordinates
|
|
22
|
+
creation of standalone Python modules with optimized implementations, integration of Numba
|
|
23
|
+
optimization directives, and preservation of mathematical correctness throughout optimization.
|
|
24
|
+
|
|
25
|
+
The recipe system enables the broader map folding research framework by providing systematic
|
|
26
|
+
control over the transformation process while ensuring that generated modules achieve maximum
|
|
27
|
+
performance through compile-time specialization and runtime optimization strategies.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from ast import Module
|
|
31
|
+
from astToolkit import identifierDotAttribute, parseLogicalPath2astModule
|
|
32
|
+
from mapFolding import (
|
|
33
|
+
DatatypeElephino as TheDatatypeElephino, DatatypeFoldsTotal as TheDatatypeFoldsTotal,
|
|
34
|
+
DatatypeLeavesTotal as TheDatatypeLeavesTotal, getPathFilenameFoldsTotal, getPathRootJobDEFAULT,
|
|
35
|
+
MapFoldingState, packageSettings,
|
|
36
|
+
)
|
|
4
37
|
from mapFolding.someAssemblyRequired import dataclassInstanceIdentifierDEFAULT, ShatteredDataclass
|
|
5
38
|
from mapFolding.someAssemblyRequired.transformationTools import shatter_dataclassesDOTdataclass
|
|
6
39
|
from pathlib import Path, PurePosixPath
|
|
@@ -9,6 +42,50 @@ import dataclasses
|
|
|
9
42
|
|
|
10
43
|
@dataclasses.dataclass
|
|
11
44
|
class RecipeJobTheorem2Numba:
|
|
45
|
+
"""Configuration recipe for generating Numba-optimized map folding computation jobs.
|
|
46
|
+
|
|
47
|
+
This dataclass serves as the central configuration hub for the code transformation
|
|
48
|
+
pipeline that converts generic map folding algorithms into highly optimized,
|
|
49
|
+
specialized computation modules. The recipe encapsulates all parameters required
|
|
50
|
+
for source code analysis, target file generation, datatype mapping, and compilation
|
|
51
|
+
optimization settings.
|
|
52
|
+
|
|
53
|
+
The transformation process operates by extracting functions from source modules,
|
|
54
|
+
embedding concrete parameter values, eliminating dead code paths, and generating
|
|
55
|
+
standalone Python modules optimized for specific map dimensions. These generated
|
|
56
|
+
modules achieve maximum performance through Numba just-in-time compilation and
|
|
57
|
+
embedded compile-time constants.
|
|
58
|
+
|
|
59
|
+
The recipe maintains both source configuration (where to find the generic algorithm)
|
|
60
|
+
and target configuration (where to write the optimized module), along with the
|
|
61
|
+
computational state that provides concrete values for the transformation process.
|
|
62
|
+
|
|
63
|
+
Attributes:
|
|
64
|
+
state: The map folding computation state containing dimensions and initial values.
|
|
65
|
+
foldsTotalEstimated: Estimated total number of folds for progress tracking (0).
|
|
66
|
+
shatteredDataclass: Deconstructed dataclass metadata for code transformation.
|
|
67
|
+
source_astModule: Parsed AST of the source module containing the generic algorithm.
|
|
68
|
+
sourceCountCallable: Name of the counting function to extract ('count').
|
|
69
|
+
sourceLogicalPathModuleDataclass: Logical path to the dataclass module.
|
|
70
|
+
sourceDataclassIdentifier: Name of the source dataclass ('MapFoldingState').
|
|
71
|
+
sourceDataclassInstance: Instance identifier for the dataclass.
|
|
72
|
+
sourcePathPackage: Path to the source package.
|
|
73
|
+
sourcePackageIdentifier: Name of the source package.
|
|
74
|
+
pathPackage: Override path for the target package (None).
|
|
75
|
+
pathModule: Override path for the target module directory.
|
|
76
|
+
fileExtension: File extension for generated modules.
|
|
77
|
+
pathFilenameFoldsTotal: Path for writing fold count results.
|
|
78
|
+
packageIdentifier: Target package identifier (None).
|
|
79
|
+
logicalPathRoot: Logical path root corresponding to filesystem directory.
|
|
80
|
+
moduleIdentifier: Target module identifier.
|
|
81
|
+
countCallable: Name of the counting function in generated module.
|
|
82
|
+
dataclassIdentifier: Target dataclass identifier.
|
|
83
|
+
dataclassInstance: Target dataclass instance identifier.
|
|
84
|
+
logicalPathModuleDataclass: Logical path to target dataclass module.
|
|
85
|
+
DatatypeFoldsTotal: Type alias for fold count datatype.
|
|
86
|
+
DatatypeElephino: Type alias for intermediate computation datatype.
|
|
87
|
+
DatatypeLeavesTotal: Type alias for leaf count datatype.
|
|
88
|
+
"""
|
|
12
89
|
state: MapFoldingState
|
|
13
90
|
# TODO create function to calculate `foldsTotalEstimated`
|
|
14
91
|
foldsTotalEstimated: int = 0
|
|
@@ -16,10 +93,10 @@ class RecipeJobTheorem2Numba:
|
|
|
16
93
|
|
|
17
94
|
# ========================================
|
|
18
95
|
# Source
|
|
19
|
-
source_astModule = parseLogicalPath2astModule('mapFolding.syntheticModules.theorem2Numba')
|
|
96
|
+
source_astModule: Module = parseLogicalPath2astModule('mapFolding.syntheticModules.theorem2Numba')
|
|
20
97
|
sourceCountCallable: str = 'count'
|
|
21
98
|
|
|
22
|
-
sourceLogicalPathModuleDataclass:
|
|
99
|
+
sourceLogicalPathModuleDataclass: identifierDotAttribute = 'mapFolding.dataBaskets'
|
|
23
100
|
sourceDataclassIdentifier: str = 'MapFoldingState'
|
|
24
101
|
sourceDataclassInstance: str = dataclassInstanceIdentifierDEFAULT
|
|
25
102
|
|
|
@@ -37,13 +114,13 @@ class RecipeJobTheorem2Numba:
|
|
|
37
114
|
# ========================================
|
|
38
115
|
# Logical identifiers (as opposed to physical identifiers)
|
|
39
116
|
packageIdentifier: str | None = None
|
|
40
|
-
logicalPathRoot:
|
|
117
|
+
logicalPathRoot: identifierDotAttribute | None = None
|
|
41
118
|
""" `logicalPathRoot` likely corresponds to a physical filesystem directory."""
|
|
42
119
|
moduleIdentifier: str = dataclasses.field(default=None, init=True) # pyright: ignore[reportAssignmentType]
|
|
43
120
|
countCallable: str = sourceCountCallable
|
|
44
121
|
dataclassIdentifier: str | None = sourceDataclassIdentifier
|
|
45
122
|
dataclassInstance: str | None = sourceDataclassInstance
|
|
46
|
-
logicalPathModuleDataclass:
|
|
123
|
+
logicalPathModuleDataclass: identifierDotAttribute | None = sourceLogicalPathModuleDataclass
|
|
47
124
|
|
|
48
125
|
# ========================================
|
|
49
126
|
# Datatypes
|
|
@@ -53,10 +130,25 @@ class RecipeJobTheorem2Numba:
|
|
|
53
130
|
|
|
54
131
|
def _makePathFilename(self,
|
|
55
132
|
pathRoot: PurePosixPath | None = None,
|
|
56
|
-
logicalPathINFIX:
|
|
133
|
+
logicalPathINFIX: identifierDotAttribute | None = None,
|
|
57
134
|
filenameStem: str | None = None,
|
|
58
135
|
fileExtension: str | None = None,
|
|
59
136
|
) -> PurePosixPath:
|
|
137
|
+
"""Construct a complete file path from component parts.
|
|
138
|
+
|
|
139
|
+
This helper method builds filesystem paths by combining a root directory,
|
|
140
|
+
optional subdirectory structure, filename stem, and file extension. It provides
|
|
141
|
+
sensible defaults for missing components based on the recipe configuration.
|
|
142
|
+
|
|
143
|
+
Parameters:
|
|
144
|
+
pathRoot: Base directory path. Defaults to package path or current directory.
|
|
145
|
+
logicalPathINFIX: Dot-separated path segments to insert between root and filename.
|
|
146
|
+
filenameStem: Base filename without extension. Defaults to module identifier.
|
|
147
|
+
fileExtension: File extension including dot. Defaults to configured extension.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
Complete file path as a PurePosixPath object.
|
|
151
|
+
"""
|
|
60
152
|
if pathRoot is None:
|
|
61
153
|
pathRoot = self.pathPackage or PurePosixPath(Path.cwd())
|
|
62
154
|
if logicalPathINFIX:
|
|
@@ -71,12 +163,31 @@ class RecipeJobTheorem2Numba:
|
|
|
71
163
|
|
|
72
164
|
@property
|
|
73
165
|
def pathFilenameModule(self) -> PurePosixPath:
|
|
166
|
+
"""Generate the complete path and filename for the output module.
|
|
167
|
+
|
|
168
|
+
This property computes the target location where the generated computation
|
|
169
|
+
module will be written. It respects the pathModule override if specified,
|
|
170
|
+
otherwise constructs the path using the default package structure.
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
Complete path to the target module file.
|
|
174
|
+
"""
|
|
74
175
|
if self.pathModule is None:
|
|
75
176
|
return self._makePathFilename()
|
|
76
177
|
else:
|
|
77
178
|
return self._makePathFilename(pathRoot=self.pathModule, logicalPathINFIX=None)
|
|
78
179
|
|
|
79
|
-
def __post_init__(self):
|
|
180
|
+
def __post_init__(self) -> None:
|
|
181
|
+
"""Initialize computed fields and validate configuration after dataclass creation.
|
|
182
|
+
|
|
183
|
+
This method performs post-initialization setup including:
|
|
184
|
+
1. Deriving module identifier from map shape if not explicitly provided
|
|
185
|
+
2. Setting default paths for fold total output files
|
|
186
|
+
3. Creating shattered dataclass metadata for code transformations
|
|
187
|
+
|
|
188
|
+
The initialization ensures all computed fields are properly set based on
|
|
189
|
+
the provided configuration and sensible defaults.
|
|
190
|
+
"""
|
|
80
191
|
pathFilenameFoldsTotal = PurePosixPath(getPathFilenameFoldsTotal(self.state.mapShape))
|
|
81
192
|
|
|
82
193
|
if self.moduleIdentifier is None: # pyright: ignore[reportUnnecessaryComparison]
|
|
@@ -1,52 +1,54 @@
|
|
|
1
1
|
"""
|
|
2
|
-
|
|
2
|
+
Map folding AST transformation system: Comprehensive framework for converting dataclass-based algorithms to optimized implementations.
|
|
3
3
|
|
|
4
|
-
This
|
|
5
|
-
Python code. It serves as the algorithmic optimization engine for the mapFolding package, enabling the conversion of
|
|
6
|
-
readable, functional implementations into highly-optimized variants with verified correctness.
|
|
4
|
+
This subpackage implements a sophisticated Abstract Syntax Tree (AST) transformation system specifically designed to convert high-level dataclass-based map folding algorithms into highly optimized, Numba-compatible implementations. The transformation system addresses a fundamental challenge in high-performance scientific computing: bridging the gap between maintainable, object-oriented algorithm implementations and the performance requirements of computationally intensive mathematical research.
|
|
7
5
|
|
|
8
|
-
|
|
6
|
+
The map folding problem domain involves complex combinatorial calculations that can require hours or days to complete for specific dimensional configurations. While dataclass-based implementations provide clean, maintainable interfaces for managing complex mathematical state, these objects cannot be directly processed by Numba's just-in-time compiler, which excels at optimizing operations on primitive values and tuples. This subpackage resolves this architectural tension through systematic AST manipulation that preserves algorithmic correctness while enabling dramatic performance improvements.
|
|
9
7
|
|
|
10
|
-
|
|
11
|
-
- Pattern recognition with composable predicates (ifThis)
|
|
12
|
-
- Node access with consistent interfaces (DOT)
|
|
13
|
-
- AST traversal and transformation (NodeChanger, NodeTourist)
|
|
14
|
-
- AST construction with sane defaults (Make)
|
|
15
|
-
- Node transformation operations (grab, Then)
|
|
8
|
+
## System Architecture
|
|
16
9
|
|
|
17
|
-
|
|
18
|
-
- Import tracking and management (LedgerOfImports)
|
|
19
|
-
- Function packaging with dependencies (IngredientsFunction)
|
|
20
|
-
- Module assembly with structured components (IngredientsModule)
|
|
21
|
-
- Recipe configuration for generating optimized code (RecipeSynthesizeFlow)
|
|
22
|
-
- Dataclass decomposition for compatibility (ShatteredDataclass)
|
|
10
|
+
The transformation system operates through a carefully orchestrated sequence of specialized modules, each contributing essential capabilities to the complete transformation process:
|
|
23
11
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
- Specialized component transformation (decorateCallableWithNumba)
|
|
12
|
+
### Foundation Layer: Pattern Recognition and Structural Analysis
|
|
13
|
+
- `_toolIfThis`: Extended predicate functions for identifying specific code patterns in AST nodes, particularly conditional expressions and control flow structures essential to map folding computations
|
|
14
|
+
- `_toolkitContainers`: Dataclass decomposition containers that extract individual fields, type annotations, and reconstruction logic from dataclass definitions into manipulatable AST components
|
|
28
15
|
|
|
29
|
-
|
|
16
|
+
### Operational Core: Transformation Implementation
|
|
17
|
+
- `transformationTools`: Core functions executing dataclass decomposition, function signature transformation, and calling convention adaptation that convert dataclass-accepting functions into primitive-parameter equivalents
|
|
18
|
+
- `toolkitNumba`: Numba integration tools providing just-in-time compilation optimization with configurable performance parameters and strategic compiler directive application
|
|
30
19
|
|
|
31
|
-
|
|
32
|
-
|
|
20
|
+
### Configuration and Orchestration
|
|
21
|
+
- `infoBooth`: Configuration constants, computational complexity estimates, and default identifiers for systematic module generation and optimization decision-making
|
|
22
|
+
- `RecipeJob`: Configuration management dataclasses that coordinate transformation parameters across multiple stages while maintaining consistency between source algorithms and target optimizations
|
|
23
|
+
- `makeAllModules`: Comprehensive transformation orchestration tools that execute complete transformation processes for diverse computational strategies and performance characteristics
|
|
24
|
+
- `makeJobTheorem2Numba`: Specialized job generation implementing the complete transformation sequence to produce standalone, highly optimized computation modules
|
|
33
25
|
|
|
34
|
-
|
|
35
|
-
|
|
26
|
+
### Utility Extensions
|
|
27
|
+
- `getLLVMforNoReason`: Standalone utility for extracting LLVM Intermediate Representation from compiled modules for debugging and optimization analysis
|
|
36
28
|
|
|
37
|
-
|
|
29
|
+
## Transformation Process
|
|
38
30
|
|
|
39
|
-
|
|
40
|
-
documentation in tests/__init__.py for details on extending the test suite for custom implementations.
|
|
31
|
+
The complete transformation follows a systematic three-stage pattern:
|
|
41
32
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
33
|
+
1. **Analysis and Decomposition**: Pattern recognition identifies dataclass structures and dependencies, followed by decomposition into constituent AST components including field definitions, type annotations, and initialization patterns.
|
|
34
|
+
|
|
35
|
+
2. **Function Optimization**: Core transformations convert functions accepting dataclass parameters into functions accepting individual primitive parameters, with systematic updates to signatures, return types, and calling conventions.
|
|
36
|
+
|
|
37
|
+
3. **Compilation Integration**: Numba decorators with carefully configured optimization parameters are applied to transformed functions, enabling aggressive just-in-time compilation with performance characteristics suitable for large-scale computational research.
|
|
38
|
+
|
|
39
|
+
## Generated Module Characteristics
|
|
40
|
+
|
|
41
|
+
The transformation system produces standalone Python modules with embedded constants replacing parameterized values, eliminated dead code paths, optimized data structures, Numba compilation directives, progress feedback for long-running calculations, and consistent naming conventions with systematic filesystem organization. These modules maintain mathematical correctness while providing significant performance improvements essential to map folding research computational demands.
|
|
42
|
+
|
|
43
|
+
## Usage Guidance
|
|
44
|
+
|
|
45
|
+
Begin exploration with `infoBooth` for understanding configuration options and complexity estimates. Proceed to `transformationTools` for core transformation capabilities, then examine `RecipeJob` for orchestration patterns. Advanced users developing custom transformations should study `_toolIfThis` and `_toolkitContainers` for foundational pattern recognition and structural manipulation capabilities.
|
|
46
|
+
|
|
47
|
+
The transformation system represents the culmination of systematic AST manipulation research, enabling previously intractable calculations through the strategic application of compiler optimization techniques to abstract mathematical algorithms.
|
|
45
48
|
"""
|
|
46
49
|
|
|
47
50
|
from mapFolding.someAssemblyRequired.infoBooth import (
|
|
48
51
|
dataclassInstanceIdentifierDEFAULT as dataclassInstanceIdentifierDEFAULT,
|
|
49
|
-
raiseIfNoneGitHubIssueNumber3 as raiseIfNoneGitHubIssueNumber3,
|
|
50
52
|
sourceCallableDispatcherDEFAULT as sourceCallableDispatcherDEFAULT,
|
|
51
53
|
)
|
|
52
54
|
|
|
@@ -56,8 +58,3 @@ from mapFolding.someAssemblyRequired._toolkitContainers import (
|
|
|
56
58
|
DeReConstructField2ast as DeReConstructField2ast,
|
|
57
59
|
ShatteredDataclass as ShatteredDataclass,
|
|
58
60
|
)
|
|
59
|
-
|
|
60
|
-
def raiseIfNone[TypeSansNone](returnTarget: TypeSansNone | None) -> TypeSansNone:
|
|
61
|
-
if returnTarget is None:
|
|
62
|
-
raise ValueError('Return is None.')
|
|
63
|
-
return returnTarget
|
|
@@ -1,22 +1,27 @@
|
|
|
1
1
|
"""
|
|
2
|
-
|
|
2
|
+
Map folding AST transformation system: Foundation pattern matching and filtering predicates.
|
|
3
3
|
|
|
4
|
-
This module
|
|
5
|
-
|
|
4
|
+
This module establishes the foundational layer of the map folding AST transformation system by
|
|
5
|
+
providing specialized predicate functions for identifying specific code patterns in Abstract
|
|
6
|
+
Syntax Trees. The transformation system converts high-level dataclass-based map folding algorithms
|
|
7
|
+
into optimized computational modules through systematic AST manipulation, beginning with precise
|
|
8
|
+
pattern recognition capabilities defined here.
|
|
6
9
|
|
|
7
|
-
|
|
8
|
-
|
|
10
|
+
The predicates extend `astToolkit.IfThis` with domain-specific functions that recognize conditional
|
|
11
|
+
expressions and control flow structures essential to map folding computations. These patterns include
|
|
12
|
+
attribute comparisons against specific values, loop termination conditions based on counting variables,
|
|
13
|
+
and bounds checking operations that characterize map folding algorithm structures.
|
|
9
14
|
|
|
10
|
-
|
|
11
|
-
|
|
15
|
+
Pattern recognition serves as the entry point for the broader transformation system that decomposes
|
|
16
|
+
dataclass-dependent algorithms, applies performance optimizations, and generates specialized modules
|
|
17
|
+
optimized for Numba just-in-time compilation. The precise identification of these structural patterns
|
|
18
|
+
enables subsequent transformation stages to apply targeted optimizations while preserving mathematical
|
|
19
|
+
correctness.
|
|
12
20
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
+
Classes:
|
|
22
|
+
IfThis: Extended predicate class with specialized methods for matching attribute comparisons
|
|
23
|
+
and control flow patterns involving namespaced identifiers essential to map folding
|
|
24
|
+
algorithm transformations.
|
|
20
25
|
"""
|
|
21
26
|
|
|
22
27
|
from astToolkit import Be, DOT, IfThis as astToolkit_IfThis
|
|
@@ -28,31 +33,88 @@ class IfThis(astToolkit_IfThis):
|
|
|
28
33
|
"""
|
|
29
34
|
Provide predicate functions for matching and filtering AST nodes based on various criteria.
|
|
30
35
|
|
|
31
|
-
The
|
|
36
|
+
The IfThis class contains static methods that generate predicate functions used to test whether AST nodes match
|
|
32
37
|
specific criteria. These predicates can be used with NodeChanger and NodeTourist to identify and process specific
|
|
33
38
|
patterns in the AST.
|
|
34
39
|
|
|
35
40
|
The class provides predicates for matching various node types, attributes, identifiers, and structural patterns,
|
|
36
41
|
enabling precise targeting of AST elements for analysis or transformation.
|
|
37
42
|
"""
|
|
43
|
+
|
|
38
44
|
@staticmethod
|
|
39
45
|
def isAttributeNamespaceIdentifierGreaterThan0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeGuard[ast.Compare] | bool]:
|
|
46
|
+
"""
|
|
47
|
+
Generate a predicate that matches comparison expressions testing if a namespaced attribute is greater than 0.
|
|
48
|
+
|
|
49
|
+
This function creates a predicate that identifies AST nodes representing comparisons
|
|
50
|
+
of the form `namespace.identifier > 0`. It's commonly used to identify conditional
|
|
51
|
+
expressions that test positive values of counting variables or similar constructs.
|
|
52
|
+
|
|
53
|
+
Parameters:
|
|
54
|
+
namespace: The namespace or object name containing the attribute
|
|
55
|
+
identifier: The attribute name to test
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
A predicate function that returns True for Compare nodes matching the pattern
|
|
59
|
+
"""
|
|
40
60
|
return lambda node: (Be.Compare(node)
|
|
41
|
-
and IfThis.
|
|
61
|
+
and IfThis.isAttributeNamespaceIdentifier(namespace, identifier)(DOT.left(node))
|
|
42
62
|
and Be.Gt(node.ops[0])
|
|
43
63
|
and IfThis.isConstant_value(0)(node.comparators[0]))
|
|
64
|
+
|
|
44
65
|
@staticmethod
|
|
45
66
|
def isIfAttributeNamespaceIdentifierGreaterThan0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeGuard[ast.If] | bool]:
|
|
67
|
+
"""
|
|
68
|
+
Generate a predicate that matches If statements testing if a namespaced attribute is greater than 0.
|
|
69
|
+
|
|
70
|
+
This function creates a predicate that identifies AST nodes representing conditional
|
|
71
|
+
statements of the form `if namespace.identifier > 0:`. It's used to find control
|
|
72
|
+
flow structures that depend on positive values of specific attributes.
|
|
73
|
+
|
|
74
|
+
Parameters:
|
|
75
|
+
namespace: The namespace or object name containing the attribute
|
|
76
|
+
identifier: The attribute name to test
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
A predicate function that returns True for If nodes with the specified test condition
|
|
80
|
+
"""
|
|
46
81
|
return lambda node: (Be.If(node)
|
|
47
82
|
and IfThis.isAttributeNamespaceIdentifierGreaterThan0(namespace, identifier)(DOT.test(node)))
|
|
48
83
|
|
|
49
84
|
@staticmethod
|
|
50
85
|
def isWhileAttributeNamespaceIdentifierGreaterThan0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeGuard[ast.While] | bool]:
|
|
86
|
+
"""
|
|
87
|
+
Generate a predicate that matches While loops testing if a namespaced attribute is greater than 0.
|
|
88
|
+
|
|
89
|
+
This function creates a predicate that identifies AST nodes representing loop
|
|
90
|
+
statements of the form `while namespace.identifier > 0:`. It's used to find
|
|
91
|
+
iteration constructs that continue while specific attributes remain positive.
|
|
92
|
+
|
|
93
|
+
Parameters:
|
|
94
|
+
namespace: The namespace or object name containing the attribute
|
|
95
|
+
identifier: The attribute name to test
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
A predicate function that returns True for While nodes with the specified test condition
|
|
99
|
+
"""
|
|
51
100
|
return lambda node: (Be.While(node)
|
|
52
101
|
and IfThis.isAttributeNamespaceIdentifierGreaterThan0(namespace, identifier)(DOT.test(node)))
|
|
53
|
-
|
|
54
102
|
@staticmethod
|
|
55
103
|
def isAttributeNamespaceIdentifierLessThanOrEqual0(namespace: str, identifier: str) -> Callable[[ast.AST], TypeGuard[ast.Compare] | bool]:
|
|
104
|
+
"""
|
|
105
|
+
Generate a predicate that matches comparison expressions testing if a namespaced attribute is less than or equal to 0.
|
|
106
|
+
|
|
107
|
+
This function creates a predicate that identifies AST nodes representing comparisons
|
|
108
|
+
of the form `namespace.identifier <= 0`. It's used to identify conditional
|
|
109
|
+
expressions that test non-positive values of counting variables or similar constructs.
|
|
110
|
+
|
|
111
|
+
Parameters:
|
|
112
|
+
namespace: The namespace or object name containing the attribute
|
|
113
|
+
identifier: The attribute name to test
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
A predicate function that returns True for Compare nodes matching the pattern
|
|
117
|
+
"""
|
|
56
118
|
return lambda node: (Be.Compare(node)
|
|
57
|
-
and IfThis.
|
|
119
|
+
and IfThis.isAttributeNamespaceIdentifier(namespace, identifier)(DOT.left(node))
|
|
58
120
|
and Be.LtE(node.ops[0]))
|