solpython 0.1.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.
pysol/executor.py ADDED
@@ -0,0 +1,127 @@
1
+ """Execute Python source via the on-chain compiler and VM."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ _ARTIFACTS_DIR = Path(__file__).parent / "contracts" / "artifacts"
7
+
8
+
9
+ def _patch_evm():
10
+ """Disable EIP-3860 contract size limits in py-evm."""
11
+ from eth.vm.forks.shanghai.computation import ShanghaiComputation
12
+ from eth.vm.forks.spurious_dragon.computation import SpuriousDragonComputation
13
+
14
+ @classmethod
15
+ def _no_validate(cls, message):
16
+ pass
17
+
18
+ @classmethod
19
+ def _no_consume(cls, computation):
20
+ pass
21
+
22
+ @classmethod
23
+ def _no_validate_code(cls, code):
24
+ pass
25
+
26
+ ShanghaiComputation.validate_create_message = _no_validate
27
+ ShanghaiComputation.consume_initcode_gas_cost = _no_consume
28
+ SpuriousDragonComputation.validate_contract_code = _no_validate_code
29
+
30
+
31
+ def _load_artifact(name: str) -> dict:
32
+ path = _ARTIFACTS_DIR / f"{name}.json"
33
+ if not path.exists():
34
+ raise FileNotFoundError(
35
+ f"Contract artifacts not found at {path}. "
36
+ f"Run `pysol-compile` or `python -m pysol.build` first."
37
+ )
38
+ return json.loads(path.read_text())
39
+
40
+
41
+ def _setup_evm():
42
+ """Create a local EVM and deploy compiler + VM contracts."""
43
+ _patch_evm()
44
+ from web3 import Web3
45
+ from eth_tester import EthereumTester
46
+ from eth_tester.backends.pyevm.main import PyEVMBackend
47
+
48
+ genesis_params = PyEVMBackend._generate_genesis_params(
49
+ overrides={"gas_limit": 1_000_000_000}
50
+ )
51
+ backend = PyEVMBackend(genesis_parameters=genesis_params)
52
+ tester = EthereumTester(backend=backend)
53
+ w3 = Web3(Web3.EthereumTesterProvider(ethereum_tester=tester))
54
+
55
+ compiler_art = _load_artifact("PythonCompiler")
56
+ vm_art = _load_artifact("VM")
57
+
58
+ sender = w3.eth.accounts[0]
59
+ gas = 1_000_000_000
60
+
61
+ # Deploy PythonCompiler
62
+ Compiler = w3.eth.contract(abi=compiler_art["abi"], bytecode=compiler_art["bytecode"])
63
+ tx_hash = Compiler.constructor().transact({"from": sender, "gas": gas})
64
+ receipt = w3.eth.get_transaction_receipt(tx_hash)
65
+ compiler = w3.eth.contract(address=receipt["contractAddress"], abi=compiler_art["abi"])
66
+
67
+ # Deploy VM
68
+ VM = w3.eth.contract(abi=vm_art["abi"], bytecode=vm_art["bytecode"])
69
+ tx_hash = VM.constructor().transact({"from": sender, "gas": gas})
70
+ receipt = w3.eth.get_transaction_receipt(tx_hash)
71
+ vm = w3.eth.contract(address=receipt["contractAddress"], abi=vm_art["abi"])
72
+
73
+ return w3, compiler, vm, sender, gas
74
+
75
+
76
+ def _decode_output(w3, receipt) -> str:
77
+ """Decode Print and PrintString events from transaction receipt."""
78
+ print_topic = w3.keccak(text="Print(uint256[])").hex()
79
+ print_str_topic = w3.keccak(text="PrintString(string)").hex()
80
+
81
+ parts = []
82
+ for log in receipt["logs"]:
83
+ topic0 = log["topics"][0].hex()
84
+ if topic0 == print_topic:
85
+ decoded = w3.codec.decode(["uint256[]"], log["data"])
86
+ for v in decoded[0]:
87
+ parts.append(str(v))
88
+ elif topic0 == print_str_topic:
89
+ decoded = w3.codec.decode(["string"], log["data"])
90
+ parts.append(decoded[0])
91
+
92
+ return "\n".join(parts)
93
+
94
+
95
+ def run(source: str, *, verbose: bool = False) -> str:
96
+ """Compile and execute Python source, return printed output."""
97
+ w3, compiler, vm, sender, gas = _setup_evm()
98
+
99
+ if verbose:
100
+ print(f"[solpython] Compiling {len(source)} chars of Python...")
101
+
102
+ bytecode = compiler.functions.compile(source).call({"from": sender, "gas": gas})
103
+
104
+ if verbose:
105
+ print(f"[solpython] Generated {len(bytecode)} bytes of bytecode")
106
+
107
+ tx_hash = vm.functions.execute(bytecode).transact({"from": sender, "gas": gas})
108
+ receipt = w3.eth.get_transaction_receipt(tx_hash)
109
+
110
+ return _decode_output(w3, receipt)
111
+
112
+
113
+ def run_with_imports(source: str, modules: dict[str, str], *, verbose: bool = False) -> str:
114
+ """Compile and execute Python source with imported modules."""
115
+ w3, compiler, vm, sender, gas = _setup_evm()
116
+
117
+ names = list(modules.keys())
118
+ sources = [modules[n] for n in names]
119
+
120
+ bytecode = compiler.functions.compileWithImports(source, names, sources).call(
121
+ {"from": sender, "gas": gas}
122
+ )
123
+
124
+ tx_hash = vm.functions.execute(bytecode).transact({"from": sender, "gas": gas})
125
+ receipt = w3.eth.get_transaction_receipt(tx_hash)
126
+
127
+ return _decode_output(w3, receipt)
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.4
2
+ Name: solpython
3
+ Version: 0.1.0
4
+ Summary: Python-to-EVM compiler — run Python on-chain via a Solidity smart contract pipeline
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: web3>=6.0
10
+ Requires-Dist: eth-tester>=0.10.0
11
+ Requires-Dist: py-evm>=0.10.0
12
+ Provides-Extra: build
13
+ Requires-Dist: py-solc-x>=2.0; extra == "build"
14
+ Dynamic: license-file
15
+
16
+ # solpython
17
+
18
+ A Python-to-EVM compiler written entirely in Solidity. Feed it Python source code as a string, get EVM-compatible bytecode out — no off-chain tooling required.
19
+
20
+ 644 tests across 46 test suites.
21
+
22
+ ## Architecture
23
+
24
+ Six-phase compiler pipeline, each phase implemented as a Solidity contract:
25
+
26
+ ```
27
+ Python source (string)
28
+
29
+
30
+ ┌──────────┐
31
+ │ Lexer │ Tokenizes source into token stream
32
+ └────┬─────┘
33
+ │ Token[]
34
+
35
+ ┌──────────┐
36
+ │ Parser │ Recursive descent → AST (struct array in storage)
37
+ └────┬─────┘
38
+ │ ASTNode[]
39
+
40
+ ┌───────────────┐
41
+ │ Semantic │ Symbol table, scope resolution, type inference
42
+ │ Analyzer │
43
+ └────┬──────────┘
44
+
45
+
46
+ ┌───────────────┐
47
+ │ Code │ AST → custom stack-based bytecode
48
+ │ Generator │
49
+ └────┬──────────┘
50
+ │ bytes (bytecode)
51
+
52
+ ┌──────────┐
53
+ │ VM │ Stack machine executes bytecode
54
+ └──────────┘
55
+ ```
56
+
57
+ Alternative backends:
58
+ - **Solidity Backend** — AST → Solidity source code transpiler
59
+ - **Yul Backend** — AST → Yul IR transpiler
60
+
61
+ ## Supported Python Features
62
+
63
+ **Core:**
64
+ - Integer arithmetic (`+`, `-`, `*`, `/`, `//`, `%`, `**`) with negative numbers
65
+ - Augmented assignment (`+=`, `-=`, `*=`, `/=`)
66
+ - Comparisons (`==`, `!=`, `<`, `>`, `<=`, `>=`, `is`, `is not`)
67
+ - Chained comparisons (`a < b < c`)
68
+ - Boolean operators (`and`, `or`, `not`)
69
+ - Ternary expressions (`a if cond else b`)
70
+ - `if` / `elif` / `else`
71
+ - `while` loops
72
+ - `for` loops with `range()`, list iteration, `break`, `continue`
73
+ - `for...else` / `while...else`
74
+ - Function definitions with recursion, default parameters, keyword arguments
75
+ - Nested function definitions
76
+ - `return` statements
77
+ - `pass` statement
78
+
79
+ **Data Types:**
80
+ - Integers (tagged, -2^62 to 2^62-1)
81
+ - Booleans (`True`, `False`) with proper tagging
82
+ - `None` type with safety checks
83
+ - Strings with methods (`upper`, `lower`, `split`, `contains`, `charAt`, slice)
84
+ - Lists with indexing, negative indexing, `len()`, `append()`
85
+ - Dicts with string/int keys, `items()`, `values()`, `get()`, `update()`
86
+ - Sets with `add()`, `remove()`, `in` operator
87
+ - Tuples with unpacking (`a, b = 1, 2`)
88
+ - Float (6-digit fixed-point)
89
+
90
+ **Builtins:**
91
+ - `print()` — integer and string output
92
+ - `len()`, `type()`, `isinstance()`
93
+ - `range()`, `enumerate()`, `zip()`
94
+ - `map()`, `filter()`
95
+ - `sorted()`, `reversed()`
96
+ - `abs()`, `min()`, `max()`
97
+ - f-strings and `%s`/`%d` formatting
98
+
99
+ **Advanced:**
100
+ - `try` / `except` / `finally` / `raise`
101
+ - `class` with methods, `self`, single inheritance
102
+ - `import` / `from...import` with static linking
103
+ - `global` / `nonlocal` keywords
104
+ - Virtual file system (VFS) for module loading
105
+ - Garbage collection (reference counting)
106
+ - Constant folding and dead code elimination
107
+ - Structured error messages with line/column info
108
+
109
+ ## Build & Test
110
+
111
+ Requires [Foundry](https://book.getfoundry.sh/).
112
+
113
+ ```shell
114
+ forge build # compile
115
+ forge test # run all 644 tests
116
+ forge test -vvv # verbose output
117
+ forge test --match-test testFibonacci # run a single test
118
+ ```
119
+
120
+ ## Example
121
+
122
+ ```python
123
+ def fib(n):
124
+ if n <= 1:
125
+ return n
126
+ return fib(n - 1) + fib(n - 2)
127
+
128
+ print(fib(10)) # → 55
129
+ ```
130
+
131
+ This compiles to bytecode that runs entirely on-chain via the Solidity VM contract.
132
+
133
+ ## Project Structure
134
+
135
+ ```
136
+ src/
137
+ types/ AST node, token, and type info structs
138
+ libraries/ String utility library
139
+ phases/
140
+ Lexer.sol Tokenizer
141
+ Parser.sol Recursive descent parser
142
+ SemanticAnalyzer.sol Symbol table, scope resolution
143
+ CodeGenerator.sol AST → bytecode
144
+ VM.sol Stack-based bytecode interpreter
145
+ SolidityBackend.sol AST → Solidity source transpiler
146
+ YulBackend.sol AST → Yul IR transpiler
147
+ optimizer/
148
+ ConstantFolder.sol Compile-time constant folding
149
+ gc/
150
+ RefCounter.sol Reference counting GC
151
+ vfs/
152
+ VFS.sol Virtual file system
153
+ venv/
154
+ Venv.sol Compilation environment
155
+ PythonCompiler.sol Top-level orchestrator
156
+
157
+ test/
158
+ 46 test suites covering lexer, parser, semantic analysis,
159
+ code generation, VM execution, and end-to-end integration.
160
+
161
+ Key files:
162
+ Integration.t.sol End-to-end compiler tests (fibonacci, fizzbuzz, bubble sort)
163
+ E2E.t.sol Feature-specific end-to-end tests
164
+ TypeClassify.t.sol Type system and tagging verification
165
+ Exception.t.sol Exception handling tests
166
+ GC.t.sol Garbage collection tests
167
+ ```
168
+
169
+ ## Value Tagging
170
+
171
+ The VM uses a tagged value system to distinguish types:
172
+
173
+ | Type | Tag | Range |
174
+ |----------|----------------------------|-------------------------------|
175
+ | Integer | (none) | -2^62 to 2^62-1 |
176
+ | Boolean | BOOL_OFFSET (2^66) | 2^66 (False), 2^66+1 (True) |
177
+ | None | NONE_VALUE | Fixed sentinel |
178
+ | Float | Tag at bits 252-255 | 6-digit fixed-point |
179
+ | List | ID 0 to 2^60-1 | GC-tracked |
180
+ | Dict | ID 2^60 to 2^61-1 | GC-tracked |
181
+ | Set | ID 2^61 to 2^62-1 | GC-tracked |
182
+ | String | ID >= 2^62 | Static + runtime |
183
+
184
+ ## Known Limitations
185
+
186
+ - No generators/iterators
187
+ - No class inheritance beyond single-level
188
+ - No closures (inner functions cannot capture outer variables)
189
+ - Float arithmetic uses 6-digit fixed-point, not IEEE 754
190
+ - GC is reference counting only (no cycle detection)
191
+ - Solidity/Yul backends don't support all features (see `BACKEND_LIMITATIONS.md`)
192
+
193
+ ## License
194
+
195
+ MIT
@@ -0,0 +1,14 @@
1
+ pysol/__init__.py,sha256=4Vtm2aieXEP5tMfUHGOMRJi8_oyQWnJe51y1DySdQos,89
2
+ pysol/build.py,sha256=HUF8iFaegQcCY0DP45xsoFUCEWqPqIaXb4YhwXABETk,4483
3
+ pysol/executor.py,sha256=Etb6ORTkbGPQXa5ebhJnIPvMsFyX7XRDYLDR4RdDgVg,4344
4
+ pysol/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ pysol/cli/main.py,sha256=pkIz2rMGX2baxd4-h-VW-JfNjGTc1SmcbjMw_KC_bSE,2852
6
+ pysol/contracts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ pysol/contracts/artifacts/PythonCompiler.json,sha256=01k6L0j8ZBWn2JG6CNdlRmhxpa-cHewJjY86-V3XfnU,437747
8
+ pysol/contracts/artifacts/VM.json,sha256=_qK4oc1KN2Zy0bhRMvrGorYhp2mHbKWGddqjQv4kSEE,91038
9
+ solpython-0.1.0.dist-info/licenses/LICENSE,sha256=GTNYUQJMKq5FV1co1N2BKUIxkAPPa2FCc8sLKO7x9FA,1065
10
+ solpython-0.1.0.dist-info/METADATA,sha256=d_Hw8LDflajFOzuGxjkWeR7drizAosU1Hvdm50VL3cQ,6497
11
+ solpython-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
12
+ solpython-0.1.0.dist-info/entry_points.txt,sha256=_s3EKcXf0MyFyfvA2r3llhjghAuMwS0PNRgFLxERppo,84
13
+ solpython-0.1.0.dist-info/top_level.txt,sha256=rM0iJ3CoB_QH43ATGuXjYgViiQkxBgtslv7tJqxUulM,6
14
+ solpython-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ pysol-compile = pysol.build:build
3
+ solpython = pysol.cli.main:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 taco-jpg
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 @@
1
+ pysol