solpython 0.1.0__tar.gz

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,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,3 @@
1
+ include README.md
2
+ include LICENSE
3
+ recursive-include pysol/contracts/artifacts *.json
@@ -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,180 @@
1
+ # solpython
2
+
3
+ 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.
4
+
5
+ 644 tests across 46 test suites.
6
+
7
+ ## Architecture
8
+
9
+ Six-phase compiler pipeline, each phase implemented as a Solidity contract:
10
+
11
+ ```
12
+ Python source (string)
13
+
14
+
15
+ ┌──────────┐
16
+ │ Lexer │ Tokenizes source into token stream
17
+ └────┬─────┘
18
+ │ Token[]
19
+
20
+ ┌──────────┐
21
+ │ Parser │ Recursive descent → AST (struct array in storage)
22
+ └────┬─────┘
23
+ │ ASTNode[]
24
+
25
+ ┌───────────────┐
26
+ │ Semantic │ Symbol table, scope resolution, type inference
27
+ │ Analyzer │
28
+ └────┬──────────┘
29
+
30
+
31
+ ┌───────────────┐
32
+ │ Code │ AST → custom stack-based bytecode
33
+ │ Generator │
34
+ └────┬──────────┘
35
+ │ bytes (bytecode)
36
+
37
+ ┌──────────┐
38
+ │ VM │ Stack machine executes bytecode
39
+ └──────────┘
40
+ ```
41
+
42
+ Alternative backends:
43
+ - **Solidity Backend** — AST → Solidity source code transpiler
44
+ - **Yul Backend** — AST → Yul IR transpiler
45
+
46
+ ## Supported Python Features
47
+
48
+ **Core:**
49
+ - Integer arithmetic (`+`, `-`, `*`, `/`, `//`, `%`, `**`) with negative numbers
50
+ - Augmented assignment (`+=`, `-=`, `*=`, `/=`)
51
+ - Comparisons (`==`, `!=`, `<`, `>`, `<=`, `>=`, `is`, `is not`)
52
+ - Chained comparisons (`a < b < c`)
53
+ - Boolean operators (`and`, `or`, `not`)
54
+ - Ternary expressions (`a if cond else b`)
55
+ - `if` / `elif` / `else`
56
+ - `while` loops
57
+ - `for` loops with `range()`, list iteration, `break`, `continue`
58
+ - `for...else` / `while...else`
59
+ - Function definitions with recursion, default parameters, keyword arguments
60
+ - Nested function definitions
61
+ - `return` statements
62
+ - `pass` statement
63
+
64
+ **Data Types:**
65
+ - Integers (tagged, -2^62 to 2^62-1)
66
+ - Booleans (`True`, `False`) with proper tagging
67
+ - `None` type with safety checks
68
+ - Strings with methods (`upper`, `lower`, `split`, `contains`, `charAt`, slice)
69
+ - Lists with indexing, negative indexing, `len()`, `append()`
70
+ - Dicts with string/int keys, `items()`, `values()`, `get()`, `update()`
71
+ - Sets with `add()`, `remove()`, `in` operator
72
+ - Tuples with unpacking (`a, b = 1, 2`)
73
+ - Float (6-digit fixed-point)
74
+
75
+ **Builtins:**
76
+ - `print()` — integer and string output
77
+ - `len()`, `type()`, `isinstance()`
78
+ - `range()`, `enumerate()`, `zip()`
79
+ - `map()`, `filter()`
80
+ - `sorted()`, `reversed()`
81
+ - `abs()`, `min()`, `max()`
82
+ - f-strings and `%s`/`%d` formatting
83
+
84
+ **Advanced:**
85
+ - `try` / `except` / `finally` / `raise`
86
+ - `class` with methods, `self`, single inheritance
87
+ - `import` / `from...import` with static linking
88
+ - `global` / `nonlocal` keywords
89
+ - Virtual file system (VFS) for module loading
90
+ - Garbage collection (reference counting)
91
+ - Constant folding and dead code elimination
92
+ - Structured error messages with line/column info
93
+
94
+ ## Build & Test
95
+
96
+ Requires [Foundry](https://book.getfoundry.sh/).
97
+
98
+ ```shell
99
+ forge build # compile
100
+ forge test # run all 644 tests
101
+ forge test -vvv # verbose output
102
+ forge test --match-test testFibonacci # run a single test
103
+ ```
104
+
105
+ ## Example
106
+
107
+ ```python
108
+ def fib(n):
109
+ if n <= 1:
110
+ return n
111
+ return fib(n - 1) + fib(n - 2)
112
+
113
+ print(fib(10)) # → 55
114
+ ```
115
+
116
+ This compiles to bytecode that runs entirely on-chain via the Solidity VM contract.
117
+
118
+ ## Project Structure
119
+
120
+ ```
121
+ src/
122
+ types/ AST node, token, and type info structs
123
+ libraries/ String utility library
124
+ phases/
125
+ Lexer.sol Tokenizer
126
+ Parser.sol Recursive descent parser
127
+ SemanticAnalyzer.sol Symbol table, scope resolution
128
+ CodeGenerator.sol AST → bytecode
129
+ VM.sol Stack-based bytecode interpreter
130
+ SolidityBackend.sol AST → Solidity source transpiler
131
+ YulBackend.sol AST → Yul IR transpiler
132
+ optimizer/
133
+ ConstantFolder.sol Compile-time constant folding
134
+ gc/
135
+ RefCounter.sol Reference counting GC
136
+ vfs/
137
+ VFS.sol Virtual file system
138
+ venv/
139
+ Venv.sol Compilation environment
140
+ PythonCompiler.sol Top-level orchestrator
141
+
142
+ test/
143
+ 46 test suites covering lexer, parser, semantic analysis,
144
+ code generation, VM execution, and end-to-end integration.
145
+
146
+ Key files:
147
+ Integration.t.sol End-to-end compiler tests (fibonacci, fizzbuzz, bubble sort)
148
+ E2E.t.sol Feature-specific end-to-end tests
149
+ TypeClassify.t.sol Type system and tagging verification
150
+ Exception.t.sol Exception handling tests
151
+ GC.t.sol Garbage collection tests
152
+ ```
153
+
154
+ ## Value Tagging
155
+
156
+ The VM uses a tagged value system to distinguish types:
157
+
158
+ | Type | Tag | Range |
159
+ |----------|----------------------------|-------------------------------|
160
+ | Integer | (none) | -2^62 to 2^62-1 |
161
+ | Boolean | BOOL_OFFSET (2^66) | 2^66 (False), 2^66+1 (True) |
162
+ | None | NONE_VALUE | Fixed sentinel |
163
+ | Float | Tag at bits 252-255 | 6-digit fixed-point |
164
+ | List | ID 0 to 2^60-1 | GC-tracked |
165
+ | Dict | ID 2^60 to 2^61-1 | GC-tracked |
166
+ | Set | ID 2^61 to 2^62-1 | GC-tracked |
167
+ | String | ID >= 2^62 | Static + runtime |
168
+
169
+ ## Known Limitations
170
+
171
+ - No generators/iterators
172
+ - No class inheritance beyond single-level
173
+ - No closures (inner functions cannot capture outer variables)
174
+ - Float arithmetic uses 6-digit fixed-point, not IEEE 754
175
+ - GC is reference counting only (no cycle detection)
176
+ - Solidity/Yul backends don't support all features (see `BACKEND_LIMITATIONS.md`)
177
+
178
+ ## License
179
+
180
+ MIT
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "solpython"
7
+ version = "0.1.0"
8
+ description = "Python-to-EVM compiler — run Python on-chain via a Solidity smart contract pipeline"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ dependencies = [
14
+ "web3>=6.0",
15
+ "eth-tester>=0.10.0",
16
+ "py-evm>=0.10.0",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ build = ["py-solc-x>=2.0"]
21
+
22
+ [project.scripts]
23
+ solpython = "pysol.cli.main:main"
24
+ pysol-compile = "pysol.build:build"
25
+
26
+ [tool.setuptools.packages.find]
27
+ include = ["pysol*"]
28
+
29
+ [tool.setuptools.package-data]
30
+ pysol = ["contracts/artifacts/*.json"]
@@ -0,0 +1,3 @@
1
+ """solpython — Python-to-EVM compiler, runs Python on-chain."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,144 @@
1
+ """Compile Solidity contracts and produce JSON artifacts for the Python package."""
2
+
3
+ import json
4
+ import os
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ SOLC_VERSION = "0.8.20"
10
+ SRC_DIR = Path(__file__).parent.parent / "src"
11
+ ARTIFACTS_DIR = Path(__file__).parent / "contracts" / "artifacts"
12
+
13
+ # Contracts we need to deploy from Python
14
+ TARGET_CONTRACTS = ["PythonCompiler", "VM"]
15
+
16
+
17
+ def _find_solc() -> str:
18
+ """Find solc binary — try solcx, then system solc, then forge."""
19
+ try:
20
+ import solcx
21
+ solcx.install_solc(SOLC_VERSION)
22
+ return str(Path(solcx.get_solcx_install_folder()) / f"solc-{SOLC_VERSION}")
23
+ except ImportError:
24
+ pass
25
+
26
+ # Try system solc
27
+ result = subprocess.run(["which", "solc"], capture_output=True, text=True)
28
+ if result.returncode == 0:
29
+ return result.stdout.strip()
30
+
31
+ # Try forge
32
+ result = subprocess.run(["which", "forge"], capture_output=True, text=True)
33
+ if result.returncode == 0:
34
+ # Use forge to compile, then extract artifacts
35
+ return "forge"
36
+
37
+ print("Error: No Solidity compiler found.")
38
+ print("Install one of:")
39
+ print(" pip install py-solc-x")
40
+ print(" brew install solidity (or equivalent)")
41
+ print(" curl -L https://foundry.paradigm.xyz | bash && foundryup")
42
+ sys.exit(1)
43
+
44
+
45
+ def _compile_with_forge():
46
+ """Compile using Foundry and extract artifacts."""
47
+ project_dir = Path(__file__).parent.parent
48
+ result = subprocess.run(
49
+ ["forge", "build"],
50
+ cwd=project_dir,
51
+ capture_output=True,
52
+ text=True,
53
+ )
54
+ if result.returncode != 0:
55
+ print(f"Forge build failed:\n{result.stderr}")
56
+ sys.exit(1)
57
+
58
+ ARTIFACTS_DIR.mkdir(parents=True, exist_ok=True)
59
+
60
+ for name in TARGET_CONTRACTS:
61
+ # Foundry stores artifacts in out/ContractName.sol/ContractName.json
62
+ artifact_path = project_dir / "out" / f"{name}.sol" / f"{name}.json"
63
+ if not artifact_path.exists():
64
+ print(f"Warning: artifact not found at {artifact_path}")
65
+ continue
66
+
67
+ data = json.loads(artifact_path.read_text())
68
+ # Extract just abi and bytecode
69
+ output = {
70
+ "abi": data.get("abi", []),
71
+ "bytecode": data.get("bytecode", {}).get("object", ""),
72
+ }
73
+ out_path = ARTIFACTS_DIR / f"{name}.json"
74
+ out_path.write_text(json.dumps(output, indent=2))
75
+ print(f" Wrote {out_path}")
76
+
77
+
78
+ def _compile_with_solcx(solc_path: str):
79
+ """Compile using solcx."""
80
+ import solcx
81
+
82
+ sources = {}
83
+ src_dir = SRC_DIR
84
+
85
+ # Collect all .sol files
86
+ for sol_file in src_dir.rglob("*.sol"):
87
+ rel = sol_file.relative_to(src_dir.parent)
88
+ sources[str(rel)] = {"content": sol_file.read_text()}
89
+
90
+ # Need to also find OpenZeppelin or other deps if used
91
+ # For now, our contracts are self-contained
92
+
93
+ output = solcx.compile_standard(
94
+ {
95
+ "language": "Solidity",
96
+ "sources": {k: {"content": v["content"]} for k, v in sources.items()},
97
+ "settings": {
98
+ "outputSelection": {
99
+ "*": {
100
+ "*": ["abi", "evm.bytecode.object"],
101
+ }
102
+ },
103
+ "remappings": [],
104
+ },
105
+ },
106
+ solc_binary=solc_path,
107
+ allow_paths=[str(src_dir.parent)],
108
+ )
109
+
110
+ ARTIFACTS_DIR.mkdir(parents=True, exist_ok=True)
111
+
112
+ for name in TARGET_CONTRACTS:
113
+ # Find the contract in the output
114
+ for source_path, contracts in output.get("contracts", {}).items():
115
+ if name in contracts:
116
+ contract = contracts[name]
117
+ artifact = {
118
+ "abi": contract.get("abi", []),
119
+ "bytecode": contract.get("evm", {}).get("bytecode", {}).get("object", ""),
120
+ }
121
+ if artifact["bytecode"]:
122
+ out_path = ARTIFACTS_DIR / f"{name}.json"
123
+ out_path.write_text(json.dumps(artifact, indent=2))
124
+ print(f" Wrote {out_path}")
125
+ break
126
+ else:
127
+ print(f"Warning: contract '{name}' not found in compilation output")
128
+
129
+
130
+ def build():
131
+ """Compile Solidity contracts and generate artifacts."""
132
+ print("Compiling Solidity contracts...")
133
+ solc = _find_solc()
134
+
135
+ if solc == "forge":
136
+ _compile_with_forge()
137
+ else:
138
+ _compile_with_solcx(solc)
139
+
140
+ print("Done!")
141
+
142
+
143
+ if __name__ == "__main__":
144
+ build()
File without changes
@@ -0,0 +1,104 @@
1
+ """CLI entry point — mimics CPython's interface."""
2
+
3
+ import argparse
4
+ import sys
5
+ import os
6
+ from pathlib import Path
7
+
8
+
9
+ def main():
10
+ parser = argparse.ArgumentParser(
11
+ prog="solpython",
12
+ description="Python-to-EVM compiler — run Python on-chain",
13
+ )
14
+ parser.add_argument("script", nargs="?", help="Python script file to run")
15
+ parser.add_argument("-c", dest="command", help="Python command to execute")
16
+ parser.add_argument("-v", "--verbose", action="store_true", help="Show compilation details")
17
+ parser.add_argument("--version", action="store_true", help="Show version and exit")
18
+ parser.add_argument("--build", action="store_true", help="Compile Solidity contracts and exit")
19
+
20
+ args = parser.parse_args()
21
+
22
+ if args.version:
23
+ from pysol import __version__
24
+ print(f"solpython {__version__}")
25
+ return
26
+
27
+ if args.build:
28
+ from pysol.build import build
29
+ build()
30
+ return
31
+
32
+ if args.command:
33
+ source = args.command
34
+ if not source.endswith("\n"):
35
+ source += "\n"
36
+ _execute(source, verbose=args.verbose)
37
+ return
38
+
39
+ if args.script:
40
+ if not os.path.exists(args.script):
41
+ print(f"solpython: can't open file '{args.script}': No such file or directory")
42
+ sys.exit(1)
43
+ source = Path(args.script).read_text()
44
+ _execute(source, verbose=args.verbose)
45
+ return
46
+
47
+ _repl(verbose=args.verbose)
48
+
49
+
50
+ def _execute(source: str, *, verbose: bool = False):
51
+ from pysol.executor import run
52
+ try:
53
+ output = run(source, verbose=verbose)
54
+ if output:
55
+ print(output)
56
+ except FileNotFoundError as e:
57
+ print(str(e))
58
+ sys.exit(1)
59
+ except Exception as e:
60
+ print(f"solpython: error: {e}", file=sys.stderr)
61
+ if verbose:
62
+ import traceback
63
+ traceback.print_exc()
64
+ sys.exit(1)
65
+
66
+
67
+ def _repl(*, verbose: bool = False):
68
+ from pysol import __version__
69
+ print(f"solpython {__version__}")
70
+ print('Type "exit()" or Ctrl-D to exit.')
71
+ print()
72
+
73
+ while True:
74
+ try:
75
+ line = input(">>> ")
76
+ except (EOFError, KeyboardInterrupt):
77
+ print()
78
+ break
79
+
80
+ if not line.strip():
81
+ continue
82
+ if line.strip() in ("exit()", "quit()"):
83
+ break
84
+
85
+ source = line + "\n"
86
+ if line.rstrip().endswith(":"):
87
+ while True:
88
+ try:
89
+ cont = input("... ")
90
+ except (EOFError, KeyboardInterrupt):
91
+ print()
92
+ break
93
+ if not cont.strip():
94
+ break
95
+ source += cont + "\n"
96
+
97
+ try:
98
+ _execute(source, verbose=verbose)
99
+ except SystemExit:
100
+ pass
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
File without changes