externum 2.0.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.
- externum-2.0.0/LICENSE +21 -0
- externum-2.0.0/PKG-INFO +7 -0
- externum-2.0.0/README.md +152 -0
- externum-2.0.0/externum/__init__.py +81 -0
- externum-2.0.0/externum/__main__.py +205 -0
- externum-2.0.0/externum/analysis.py +88 -0
- externum-2.0.0/externum/compiler.py +514 -0
- externum-2.0.0/externum/drm.py +192 -0
- externum-2.0.0/externum/lexer.py +252 -0
- externum-2.0.0/externum/parser.py +983 -0
- externum-2.0.0/externum/runtime/__init__.py +209 -0
- externum-2.0.0/externum/runtime/rtlib.py +123 -0
- externum-2.0.0/externum/typesys.py +728 -0
- externum-2.0.0/externum.egg-info/PKG-INFO +7 -0
- externum-2.0.0/externum.egg-info/SOURCES.txt +22 -0
- externum-2.0.0/externum.egg-info/dependency_links.txt +1 -0
- externum-2.0.0/externum.egg-info/entry_points.txt +2 -0
- externum-2.0.0/externum.egg-info/top_level.txt +1 -0
- externum-2.0.0/setup.cfg +4 -0
- externum-2.0.0/setup.py +15 -0
- externum-2.0.0/tests/test_analysis.py +559 -0
- externum-2.0.0/tests/test_drm.py +307 -0
- externum-2.0.0/tests/test_externum.py +565 -0
- externum-2.0.0/tests/test_extra.py +228 -0
externum-2.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bartosz Osiej
|
|
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.
|
externum-2.0.0/PKG-INFO
ADDED
externum-2.0.0/README.md
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# Externum
|
|
2
|
+
|
|
3
|
+
[](https://github.com/BartoszOsiej/externum/actions)
|
|
4
|
+
|
|
5
|
+
**Externum v3.0** — a full programming language blending Python readability,
|
|
6
|
+
binary performance, and Bash system control. A single source compiles to
|
|
7
|
+
**Python**, **Bash**, and a **binary** representation — or runs directly.
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
Externum = Python_readability ⊕ Binary_performance ⊕ Bash_control
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## What it can do (v3)
|
|
14
|
+
|
|
15
|
+
| Area | Support |
|
|
16
|
+
|---|---|
|
|
17
|
+
| **Data types** | lists, dicts, tuples, sets (also multiline), f-strings, binary `0b` and hex `0x` literals |
|
|
18
|
+
| **Control flow** | `if/elif/else`, `while`, `for ... in` (multi-variable), `break`, `continue`, `try/except/else/finally`, `with`, `assert` |
|
|
19
|
+
| **Functions** | default parameters, `*args`/`**kwargs`, type annotations (optional), recursion, lambdas, closures, generators (`yield`) |
|
|
20
|
+
| **OOP** | classes, inheritance, methods, `self`, attributes |
|
|
21
|
+
| **Modules** | `import`/`from ... import`, custom `.ext` modules (loader), standard library |
|
|
22
|
+
| **Expressions** | full operator precedence, chained comparisons, bitwise `& \| ^ ~ << >>`, ternaries, comprehensions (list/dict), tuple unpacking |
|
|
23
|
+
| **Shell** | inline bash `` `cmd` `` and `%% ... %%` blocks |
|
|
24
|
+
| **Tooling** | REPL, compilation to 3 targets, `argv` |
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install -e . # Python 3.10+
|
|
30
|
+
externum --version # Externum 3.0.0
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
# Run a program
|
|
37
|
+
externum run examples/pokedex.ext
|
|
38
|
+
|
|
39
|
+
# REPL
|
|
40
|
+
externum repl
|
|
41
|
+
|
|
42
|
+
# Compile to all targets
|
|
43
|
+
externum examples/hello.ext
|
|
44
|
+
|
|
45
|
+
# Compile to Python / Bash
|
|
46
|
+
externum examples/hello.ext --target python -o hello.py
|
|
47
|
+
externum examples/hello.ext --target bash
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Example (pokedex)
|
|
51
|
+
|
|
52
|
+
`examples/pokedex.ext` uses classes with inheritance, comprehensions,
|
|
53
|
+
lambdas, exceptions, generators, f-strings, and the standard library:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import mathx
|
|
57
|
+
import strings
|
|
58
|
+
|
|
59
|
+
class Fire(Pokemon):
|
|
60
|
+
def __init__(self, name, hp=50):
|
|
61
|
+
Pokemon.__init__(self, name, ["fire"], hp)
|
|
62
|
+
|
|
63
|
+
fire_team = [p.name for p in squad if p.is_type("fire")]
|
|
64
|
+
weakest = min(squad, key=lambda p: p.hp)
|
|
65
|
+
nums = [f for f in fibonacci(10) if f % 2 == 0]
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Standard library (written in Externum)
|
|
69
|
+
|
|
70
|
+
| Module | Contents |
|
|
71
|
+
|---|---|
|
|
72
|
+
| `structs` | `Stack`, `Queue`, `Counter` |
|
|
73
|
+
| `strings` | `reverse`, `is_palindrome`, `slugify`, `word_count`, `capitalize`, `truncate` |
|
|
74
|
+
| `mathx` | `clamp`, `is_even`, `gcd`, `fib`, `factorial`, `sum_of_digits` |
|
|
75
|
+
| `fs` | `read_file`, `write_file`, `append_file`, `file_exists`, `list_dir` |
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
externum run examples/pokedex.ext
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Project structure
|
|
82
|
+
|
|
83
|
+
```
|
|
84
|
+
externum/
|
|
85
|
+
├── lexer.py # Tokenization (bracket-aware, bash, f-strings)
|
|
86
|
+
├── parser.py # Full grammar → AST
|
|
87
|
+
├── compiler.py # Codegen → Python / Bash / binary
|
|
88
|
+
├── typesys.py # NV2.0 type checker (hard mode: static types, ownership)
|
|
89
|
+
├── hardmode.py # NV2.0 macros + hard-mode pipeline
|
|
90
|
+
├── drm.py # NV2.0 DRM: license keys, watermark, tamper-detection, obfuscation
|
|
91
|
+
├── runtime/ # Runtime: exec, import .ext, REPL (+ rtlib.py memory/concurrency helpers)
|
|
92
|
+
└── __main__.py # CLI (run / repl / compile / keygen)
|
|
93
|
+
lib/ # Standard library (.ext) — incl. drm.ext
|
|
94
|
+
lib/drm.ext # NV2.0 DRM stdlib: sign / verify / watermark in Externum
|
|
95
|
+
examples/ # hello, calc, pokedex, hardcore.ext
|
|
96
|
+
tests/ # 167 unit tests
|
|
97
|
+
WIKI.md # Language specification
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## NV2.0 — Hard Mode (`--hard`) — giga trudny
|
|
101
|
+
|
|
102
|
+
Run any program with `externum run program.ext --hard` (or `compile … --hard`)
|
|
103
|
+
to enable the hardcore ruleset. Existing programs that violate it fail loudly:
|
|
104
|
+
|
|
105
|
+
- **Mandatory declarations** — every variable needs `x: Type` before use;
|
|
106
|
+
using an undeclared name is a compile error.
|
|
107
|
+
- **Static typing** — assignment/return mismatches are rejected at compile
|
|
108
|
+
time (`Int` widens to `Float`; everything else must match).
|
|
109
|
+
- **Manual memory** — `alloc(Int)`, `free(p)`, `@p` dereference; double-free
|
|
110
|
+
and use-after-free are **compile errors** (ownership is enforced).
|
|
111
|
+
- **`match`/`case`** — pattern matching with literals, binds, guards, and
|
|
112
|
+
list/tuple destructuring.
|
|
113
|
+
- **Traits** — `trait X:` + `impl X for Y:`; implementations missing
|
|
114
|
+
methods or with wrong return types are rejected.
|
|
115
|
+
- **`unsafe:` blocks** — the escape hatch: checks are skipped inside.
|
|
116
|
+
- **Macros** — `macro NAME(a, b) { … }` compile-time expansion.
|
|
117
|
+
- **Concurrency** — `spawn(f(...))`, `chan()`, `send(ch, v)`, `recv(ch)`.
|
|
118
|
+
- **Esoteric operators** — `≠`, `≈`, `←` work like `!=`, `==`, `=`.
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
externum run examples/hardcore.ext --hard
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## NV2.0 — DRM (`--protect`) — obfuskacja, watermark, licencja
|
|
125
|
+
|
|
126
|
+
Every protected build carries the full defense-in-depth stack:
|
|
127
|
+
|
|
128
|
+
1. **License keys** — HMAC-SHA256 signed; `externum keygen --app-id X
|
|
129
|
+
--secret S` issues keys, the artifact verifies them (env
|
|
130
|
+
`EXTERNUM_LICENSE`), never embedding the secret.
|
|
131
|
+
2. **Watermark** — author/app/build/source-hash header in every file.
|
|
132
|
+
3. **Tamper detection** — source SHA-256 + artifact self-hash embedded;
|
|
133
|
+
modified copies are detected.
|
|
134
|
+
4. **Obfuscation** — string literals encoded through a runtime helper.
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
externum compile app.ext --protect --app-id game --author buffy --secret s3cret
|
|
138
|
+
EXTERNUM_LICENSE=<key> externum run app.ext --protect --app-id game --author buffy --secret s3cret
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Standard-library `drm.ext` provides `sign`/`verify`/`watermark` in-language.
|
|
142
|
+
|
|
143
|
+
## Tests
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
python3 -m unittest discover -s tests -v # 167 tests
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Roadmap
|
|
150
|
+
|
|
151
|
+
Modules reserved in the API (`externum.llm`, `neural`, `distributed`,
|
|
152
|
+
`types`, `spec`, `debug`) remain planned — the package works without them.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Externum - The First LLM-Native Programming Language
|
|
3
|
+
======================================================
|
|
4
|
+
Externum v3 is a complete programming language that fuses:
|
|
5
|
+
- Python readability + dynamic typing
|
|
6
|
+
- Binary performance + SIMD vectorization
|
|
7
|
+
- Bash system control + process orchestration
|
|
8
|
+
|
|
9
|
+
One source compiles to Python, Bash and binary targets, or runs directly
|
|
10
|
+
(``externum run``), with a REPL, a module system and a standard library
|
|
11
|
+
written in the language itself.
|
|
12
|
+
|
|
13
|
+
Roadmap modules (llm, neural, distributed, types, spec, debug) keep their
|
|
14
|
+
reserved API surface below; the package stays fully importable without them.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
__version__ = "3.0.0"
|
|
18
|
+
__codename__ = "Sentient"
|
|
19
|
+
|
|
20
|
+
from .lexer import Lexer
|
|
21
|
+
from .parser import Parser
|
|
22
|
+
from .compiler import Compiler
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
from .runtime import Runtime
|
|
26
|
+
except ImportError: # pragma: no cover
|
|
27
|
+
Runtime = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _guarded(name):
|
|
31
|
+
try:
|
|
32
|
+
return __import__(f"{__name__}.{name}", fromlist=["*"])
|
|
33
|
+
except ImportError:
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_llm = _guarded("llm")
|
|
38
|
+
_neural = _guarded("neural")
|
|
39
|
+
_distributed = _guarded("distributed")
|
|
40
|
+
_types = _guarded("types")
|
|
41
|
+
_spec = _guarded("spec")
|
|
42
|
+
_debug = _guarded("debug")
|
|
43
|
+
|
|
44
|
+
LLMClient = getattr(_llm, "LLMClient", None)
|
|
45
|
+
PromptTemplate = getattr(_llm, "PromptTemplate", None)
|
|
46
|
+
FunctionSchema = getattr(_llm, "FunctionSchema", None)
|
|
47
|
+
|
|
48
|
+
Tensor = getattr(_neural, "Tensor", None)
|
|
49
|
+
Module = getattr(_neural, "Module", None)
|
|
50
|
+
Linear = getattr(_neural, "Linear", None)
|
|
51
|
+
Conv2d = getattr(_neural, "Conv2d", None)
|
|
52
|
+
Attention = getattr(_neural, "Attention", None)
|
|
53
|
+
Autograd = getattr(_neural, "Autograd", None)
|
|
54
|
+
|
|
55
|
+
Actor = getattr(_distributed, "Actor", None)
|
|
56
|
+
Cluster = getattr(_distributed, "Cluster", None)
|
|
57
|
+
Stream = getattr(_distributed, "Stream", None)
|
|
58
|
+
Channel = getattr(_distributed, "Channel", None)
|
|
59
|
+
|
|
60
|
+
Type = getattr(_types, "Type", None)
|
|
61
|
+
DependentType = getattr(_types, "DependentType", None)
|
|
62
|
+
RefinementType = getattr(_types, "RefinementType", None)
|
|
63
|
+
EffectType = getattr(_types, "EffectType", None)
|
|
64
|
+
|
|
65
|
+
Spec = getattr(_spec, "Spec", None)
|
|
66
|
+
Theorem = getattr(_spec, "Theorem", None)
|
|
67
|
+
Proof = getattr(_spec, "Proof", None)
|
|
68
|
+
Verify = getattr(_spec, "Verify", None)
|
|
69
|
+
|
|
70
|
+
TimeTravelDebugger = getattr(_debug, "TimeTravelDebugger", None)
|
|
71
|
+
HotReloader = getattr(_debug, "HotReloader", None)
|
|
72
|
+
|
|
73
|
+
__all__ = [
|
|
74
|
+
"Lexer", "Parser", "Compiler", "Runtime",
|
|
75
|
+
"LLMClient", "PromptTemplate", "FunctionSchema",
|
|
76
|
+
"Tensor", "Module", "Linear", "Conv2d", "Attention", "Autograd",
|
|
77
|
+
"Actor", "Cluster", "Stream", "Channel",
|
|
78
|
+
"Type", "DependentType", "RefinementType", "EffectType",
|
|
79
|
+
"Spec", "Theorem", "Proof", "Verify",
|
|
80
|
+
"TimeTravelDebugger", "HotReloader",
|
|
81
|
+
]
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Main entry point for the Externum compiler, runtime and REPL."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
import argparse
|
|
5
|
+
|
|
6
|
+
from .lexer import Lexer
|
|
7
|
+
from .parser import Parser
|
|
8
|
+
from .compiler import Compiler
|
|
9
|
+
from . import __version__
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
13
|
+
p = argparse.ArgumentParser(
|
|
14
|
+
prog='externum',
|
|
15
|
+
description='Externum - Python + Binary + Bash Language',
|
|
16
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
17
|
+
epilog="""
|
|
18
|
+
Examples:
|
|
19
|
+
externum run program.ext [args...] # execute a program
|
|
20
|
+
externum repl # interactive shell
|
|
21
|
+
externum program.ext --target python # compile to Python
|
|
22
|
+
externum program.ext -o out.py # compile to a file
|
|
23
|
+
""",
|
|
24
|
+
)
|
|
25
|
+
p.add_argument('--version', action='version', version=f'Externum {__version__}')
|
|
26
|
+
sub = p.add_subparsers(dest='command')
|
|
27
|
+
|
|
28
|
+
run_p = sub.add_parser('run', help='Execute an .ext program')
|
|
29
|
+
run_p.add_argument('file', help='Source file to run')
|
|
30
|
+
run_p.add_argument('args', nargs='*', help='Arguments passed to the program')
|
|
31
|
+
run_p.add_argument('--protect', action='store_true',
|
|
32
|
+
help='Apply the DRM stack to the program before running')
|
|
33
|
+
run_p.add_argument('--app-id', default=None, help='Application id for DRM')
|
|
34
|
+
run_p.add_argument('--author', default=None, help='Author name for DRM')
|
|
35
|
+
run_p.add_argument('--secret', default=None, help='DRM signing secret (compile-time only)')
|
|
36
|
+
run_p.add_argument('--build-id', default=None, help='Build id baked into the DRM watermark')
|
|
37
|
+
|
|
38
|
+
sub.add_parser('repl', help='Start the interactive Externum shell')
|
|
39
|
+
|
|
40
|
+
comp = sub.add_parser('compile', help='Compile an .ext program (default)')
|
|
41
|
+
comp.add_argument('file', help='Source file to compile')
|
|
42
|
+
comp.add_argument('--target', choices=['python', 'binary', 'bash', 'all'],
|
|
43
|
+
default='all', help='Output target')
|
|
44
|
+
comp.add_argument('--output', '-o', help='Output file')
|
|
45
|
+
comp.add_argument('--protect', action='store_true',
|
|
46
|
+
help='Embed the full DRM stack (license, watermark, tamper check, obfuscation)')
|
|
47
|
+
comp.add_argument('--app-id', default=None, help='Application id for DRM')
|
|
48
|
+
comp.add_argument('--author', default=None, help='Author name for DRM')
|
|
49
|
+
comp.add_argument('--secret', default=None, help='DRM signing secret (compile-time only)')
|
|
50
|
+
comp.add_argument('--build-id', default=None, help='Build id baked into the DRM watermark')
|
|
51
|
+
|
|
52
|
+
key = sub.add_parser('keygen', help='Generate DRM license keys')
|
|
53
|
+
key.add_argument('--app-id', required=True, help='Application id')
|
|
54
|
+
key.add_argument('--author', default='', help='Author name')
|
|
55
|
+
key.add_argument('--secret', required=True, help='Signing secret')
|
|
56
|
+
key.add_argument('--expires', type=int, default=None,
|
|
57
|
+
help='Unix timestamp expiry (0/absent = never)')
|
|
58
|
+
key.add_argument('--count', type=int, default=1, help='How many keys')
|
|
59
|
+
return p
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _read_source(path: str) -> str:
|
|
63
|
+
try:
|
|
64
|
+
with open(path, 'r', encoding='utf-8') as fh:
|
|
65
|
+
return fh.read()
|
|
66
|
+
except FileNotFoundError:
|
|
67
|
+
print(f"Error: File '{path}' not found", file=sys.stderr)
|
|
68
|
+
sys.exit(1)
|
|
69
|
+
except IOError as exc:
|
|
70
|
+
print(f'Error reading file: {exc}', file=sys.stderr)
|
|
71
|
+
sys.exit(1)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def cmd_run(args) -> None:
|
|
75
|
+
try:
|
|
76
|
+
from .runtime import Runtime
|
|
77
|
+
|
|
78
|
+
protect = None
|
|
79
|
+
if args.protect:
|
|
80
|
+
protect = {
|
|
81
|
+
'app_id': args.app_id or 'externum-app',
|
|
82
|
+
'author': args.author or 'unknown',
|
|
83
|
+
'secret': args.secret or 'externum-drm',
|
|
84
|
+
'build_id': args.build_id,
|
|
85
|
+
}
|
|
86
|
+
Runtime().run_file(args.file, argv=args.args, protect=protect)
|
|
87
|
+
except SyntaxError as exc:
|
|
88
|
+
print(f'Syntax Error: {exc}', file=sys.stderr)
|
|
89
|
+
sys.exit(1)
|
|
90
|
+
except SystemExit:
|
|
91
|
+
raise
|
|
92
|
+
except Exception as exc: # noqa: BLE001 - CLI boundary
|
|
93
|
+
print(f'Runtime Error: {exc}', file=sys.stderr)
|
|
94
|
+
sys.exit(1)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_keygen(args) -> None:
|
|
98
|
+
from .drm import make_license
|
|
99
|
+
from . import __version__
|
|
100
|
+
|
|
101
|
+
print(f'Externum {__version__} — DRM keygen (secret is never stored)')
|
|
102
|
+
for _ in range(args.count):
|
|
103
|
+
print(make_license(args.secret, args.app_id, args.author, args.expires))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def cmd_repl(args) -> None:
|
|
107
|
+
try:
|
|
108
|
+
from .runtime import Runtime
|
|
109
|
+
|
|
110
|
+
Runtime().repl()
|
|
111
|
+
except KeyboardInterrupt:
|
|
112
|
+
print()
|
|
113
|
+
except Exception as exc: # noqa: BLE001
|
|
114
|
+
print(f'Error: {exc}', file=sys.stderr)
|
|
115
|
+
sys.exit(1)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def cmd_compile(args) -> None:
|
|
119
|
+
source = _read_source(args.file)
|
|
120
|
+
try:
|
|
121
|
+
from .runtime import Runtime
|
|
122
|
+
|
|
123
|
+
protect = None
|
|
124
|
+
if args.protect:
|
|
125
|
+
protect = {
|
|
126
|
+
'app_id': args.app_id or 'externum-app',
|
|
127
|
+
'author': args.author or 'unknown',
|
|
128
|
+
'secret': args.secret or 'externum-drm',
|
|
129
|
+
'build_id': args.build_id,
|
|
130
|
+
}
|
|
131
|
+
rt = Runtime()
|
|
132
|
+
py = rt.compile_to_python(source, protect=protect)
|
|
133
|
+
if args.target == 'all':
|
|
134
|
+
# DRM-protected Python plus the raw bash/binary targets
|
|
135
|
+
tokens = Lexer(source).tokenize()
|
|
136
|
+
ast = list(Parser(tokens).parse())
|
|
137
|
+
compiled = Compiler(ast).compile('all')
|
|
138
|
+
result = {
|
|
139
|
+
'python': py,
|
|
140
|
+
'bash': compiled['bash'],
|
|
141
|
+
'binary': compiled['binary'],
|
|
142
|
+
}
|
|
143
|
+
elif args.target == 'python':
|
|
144
|
+
result = py
|
|
145
|
+
else:
|
|
146
|
+
tokens = Lexer(source).tokenize()
|
|
147
|
+
ast = list(Parser(tokens).parse())
|
|
148
|
+
result = Compiler(ast).compile(args.target)
|
|
149
|
+
if args.target == 'bash':
|
|
150
|
+
result = result['bash']
|
|
151
|
+
elif args.target == 'binary':
|
|
152
|
+
result = result['binary']
|
|
153
|
+
except SyntaxError as exc:
|
|
154
|
+
print(f'Syntax Error: {exc}', file=sys.stderr)
|
|
155
|
+
sys.exit(1)
|
|
156
|
+
except Exception as exc: # noqa: BLE001 - CLI boundary
|
|
157
|
+
print(f'Error: {exc}', file=sys.stderr)
|
|
158
|
+
sys.exit(1)
|
|
159
|
+
|
|
160
|
+
if args.target == 'all':
|
|
161
|
+
# bash/binary sections are embedded as comments so the combined
|
|
162
|
+
# artifact stays a valid, runnable Python file
|
|
163
|
+
def _comment(lines: str) -> str:
|
|
164
|
+
return '\n'.join('# ' + ln for ln in lines.splitlines())
|
|
165
|
+
|
|
166
|
+
output = (
|
|
167
|
+
'# Externum Generated Code\n'
|
|
168
|
+
'# Python target:\n'
|
|
169
|
+
f"{result['python']}\n\n"
|
|
170
|
+
'# Bash target (commentary — not Python):\n'
|
|
171
|
+
f"{_comment(result['bash'])}\n\n"
|
|
172
|
+
'# Binary target (commentary — not Python):\n'
|
|
173
|
+
f"{_comment(result['binary'])}\n"
|
|
174
|
+
)
|
|
175
|
+
else:
|
|
176
|
+
output = result if isinstance(result, str) else '\n'.join(result)
|
|
177
|
+
|
|
178
|
+
if args.output:
|
|
179
|
+
with open(args.output, 'w', encoding='utf-8') as fh:
|
|
180
|
+
fh.write(output)
|
|
181
|
+
print(f'Output written to {args.output}')
|
|
182
|
+
else:
|
|
183
|
+
print(output)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def main(argv=None) -> None:
|
|
187
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
188
|
+
|
|
189
|
+
# Backwards compatible form: `externum file.ext [--target ...]`
|
|
190
|
+
if argv and argv[0] not in ('run', 'repl', 'compile', 'keygen') and not argv[0].startswith('-'):
|
|
191
|
+
argv = ['compile'] + argv
|
|
192
|
+
|
|
193
|
+
args = _build_parser().parse_args(argv)
|
|
194
|
+
if args.command == 'run':
|
|
195
|
+
cmd_run(args)
|
|
196
|
+
elif args.command == 'repl':
|
|
197
|
+
cmd_repl(args)
|
|
198
|
+
elif args.command == 'keygen':
|
|
199
|
+
cmd_keygen(args)
|
|
200
|
+
else:
|
|
201
|
+
cmd_compile(args)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
if __name__ == '__main__':
|
|
205
|
+
main()
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Externum — static analysis pipeline.
|
|
2
|
+
|
|
3
|
+
Externum is a strict language by design: every compilation runs the full
|
|
4
|
+
static analysis. There is no "easy mode" — these checks *are* the language.
|
|
5
|
+
|
|
6
|
+
`preprocess()` expands `macro` definitions before lexing (compile-time
|
|
7
|
+
metaprogramming).
|
|
8
|
+
|
|
9
|
+
`check()` runs the static type checker + ownership analyser over a parsed
|
|
10
|
+
AST using the metadata the parser captured (declared variable annotations,
|
|
11
|
+
function signatures, traits, impls, `mut` declarations). Any violation
|
|
12
|
+
raises `ExternumTypeError` with all diagnostics joined.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from typing import List, Optional, Set, Tuple
|
|
17
|
+
|
|
18
|
+
from .parser import ASTNode
|
|
19
|
+
from .typesys import TypeChecker, ExternumTypeError
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_MACRO_DEF = re.compile(
|
|
23
|
+
r'macro\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:\(([^)]*)\))?\s*\{([\s\S]*?)\}',
|
|
24
|
+
re.MULTILINE,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class MacroError(Exception):
|
|
29
|
+
"""Raised when a macro is misused."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _split_args(raw: str) -> List[str]:
|
|
33
|
+
return [p.strip() for p in raw.split(',') if p.strip()]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def preprocess(source: str) -> Tuple[str, dict]:
|
|
37
|
+
"""Expand macro definitions. Returns (processed_source, macros)."""
|
|
38
|
+
macros = {}
|
|
39
|
+
for m in _MACRO_DEF.finditer(source):
|
|
40
|
+
name, params, body = m.group(1), m.group(2), m.group(3)
|
|
41
|
+
macros[name] = {'params': _split_args(params or ''), 'body': body}
|
|
42
|
+
if not macros:
|
|
43
|
+
return source, macros
|
|
44
|
+
|
|
45
|
+
# strip definitions from the source
|
|
46
|
+
cleaned = _MACRO_DEF.sub('', source)
|
|
47
|
+
|
|
48
|
+
# expand NAME(...) and bare NAME invocations
|
|
49
|
+
for name, macro in macros.items():
|
|
50
|
+
cleaned = _expand(cleaned, name, macro)
|
|
51
|
+
return cleaned, macros
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _expand(source: str, name: str, macro: dict) -> str:
|
|
55
|
+
params = macro['params']
|
|
56
|
+
body = macro['body']
|
|
57
|
+
pattern = re.compile(r'\b' + re.escape(name) + r'\s*\(([^()]*)\)')
|
|
58
|
+
pos = 0
|
|
59
|
+
out = []
|
|
60
|
+
for m in pattern.finditer(source):
|
|
61
|
+
out.append(source[pos:m.start()])
|
|
62
|
+
raw_args = m.group(1)
|
|
63
|
+
args = _split_args(raw_args) if raw_args.strip() else []
|
|
64
|
+
if len(args) != len(params):
|
|
65
|
+
raise MacroError(
|
|
66
|
+
f'macro `{name}` expects {len(params)} argument(s), got {len(args)}')
|
|
67
|
+
expanded = body
|
|
68
|
+
for pname, arg in zip(params, args):
|
|
69
|
+
expanded = re.sub(r'\b' + re.escape(pname) + r'\b', arg, expanded)
|
|
70
|
+
out.append(expanded)
|
|
71
|
+
pos = m.end()
|
|
72
|
+
out.append(source[pos:])
|
|
73
|
+
return ''.join(out)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def check(ast: List[ASTNode], annotations: dict, signatures: dict,
|
|
77
|
+
traits: dict, impls: dict, mutable: Set[str] = None) -> List[str]:
|
|
78
|
+
"""Run Externum static analysis. Returns the list of diagnostics."""
|
|
79
|
+
checker = TypeChecker(ast, annotations, signatures, traits, impls, mutable or set())
|
|
80
|
+
return checker.check()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def check_or_raise(ast: List[ASTNode], annotations: dict, signatures: dict,
|
|
84
|
+
traits: dict, impls: dict, mutable: Set[str] = None) -> None:
|
|
85
|
+
errors = check(ast, annotations, signatures, traits, impls, mutable)
|
|
86
|
+
if errors:
|
|
87
|
+
raise ExternumTypeError(
|
|
88
|
+
'Externum: ' + '; '.join(errors))
|