externum 2.0.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.
externum/__init__.py ADDED
@@ -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
+ ]
externum/__main__.py ADDED
@@ -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()
externum/analysis.py ADDED
@@ -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))