phyx 1.6.1__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.
- phyx/__init__.py +37 -0
- phyx/__main__.py +5 -0
- phyx/ast.py +139 -0
- phyx/builtins.py +485 -0
- phyx/cli.py +619 -0
- phyx/compiler.py +879 -0
- phyx/conjugation.py +142 -0
- phyx/errors.py +84 -0
- phyx/fmt.py +93 -0
- phyx/fonts.py +141 -0
- phyx/hints.py +358 -0
- phyx/interpreter.py +379 -0
- phyx/lexer.py +260 -0
- phyx/lib/as/311/231r/316/270.phyx +26 -0
- phyx/lib/compleat.phyx +4 -0
- phyx/lib//305/245ewn.phyx +37 -0
- phyx/lint.py +193 -0
- phyx/numerals.py +55 -0
- phyx/parser.py +574 -0
- phyx/paths.py +116 -0
- phyx/render.py +214 -0
- phyx/repl.py +232 -0
- phyx/testing.py +123 -0
- phyx/values.py +176 -0
- phyx/vertical.py +66 -0
- phyx/vocabulary.py +140 -0
- phyx-1.6.1.dist-info/METADATA +154 -0
- phyx-1.6.1.dist-info/RECORD +32 -0
- phyx-1.6.1.dist-info/WHEEL +5 -0
- phyx-1.6.1.dist-info/entry_points.txt +5 -0
- phyx-1.6.1.dist-info/licenses/LICENSE +21 -0
- phyx-1.6.1.dist-info/top_level.txt +1 -0
phyx/cli.py
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
"""Command line interface for φyrx (PhyrxScript / PhyrexianScript).
|
|
2
|
+
|
|
3
|
+
``python -m phyx <command> …``, or ``phyx`` / ``phyrx`` / ``phyrxscript`` /
|
|
4
|
+
``phyrexianscript`` once installed. A path with no subcommand is a program::
|
|
5
|
+
|
|
6
|
+
phyx examples/01_welcome.phyx
|
|
7
|
+
phyx run examples/10_command.phyx red blue
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import io
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
import urllib.request
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Iterable
|
|
20
|
+
|
|
21
|
+
from . import LANGUAGE, LANGUAGE_ALIASES, __version__
|
|
22
|
+
from .errors import PhyrexianError, format_error
|
|
23
|
+
from .compiler import compile_to_python
|
|
24
|
+
from .interpreter import Interpreter, run_source
|
|
25
|
+
from .values import format_number
|
|
26
|
+
from .lexer import transliterate, untransliterate
|
|
27
|
+
from .parser import parse
|
|
28
|
+
from .fonts import (
|
|
29
|
+
FONT_FAMILY,
|
|
30
|
+
ensure_basilica,
|
|
31
|
+
ensure_font,
|
|
32
|
+
install_user_font,
|
|
33
|
+
is_font_file,
|
|
34
|
+
local_font,
|
|
35
|
+
)
|
|
36
|
+
from .render import render_html
|
|
37
|
+
from .repl import Repl
|
|
38
|
+
from .vertical import from_vertical, to_vertical
|
|
39
|
+
from .fmt import format_source
|
|
40
|
+
from .hints import explain_missing, explain_word, search_lexicon
|
|
41
|
+
from .lint import format_notes, lint_program
|
|
42
|
+
from .paths import stdlib_dir
|
|
43
|
+
from .testing import run_suite
|
|
44
|
+
from .vocabulary import CONSTANTS, MARKERS, VERBS
|
|
45
|
+
from . import ast as phyx_ast
|
|
46
|
+
|
|
47
|
+
SUBCOMMANDS = {
|
|
48
|
+
"run", "check", "render", "transpose", "translit",
|
|
49
|
+
"fetch", "lookup", "words", "repl", "eval", "bench", "dis",
|
|
50
|
+
"explain", "fmt", "lint", "test", "lib",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
DICT_REMOTE = "https://raw.githubusercontent.com/fxbuson/PhyrexianDictionary/gh-pages/_data/PhyrexianAPI.json"
|
|
54
|
+
VERTICAL_EXT = ".vphyx"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def assets_dir() -> Path:
|
|
58
|
+
env = os.environ.get("PHYX_ASSETS")
|
|
59
|
+
if env:
|
|
60
|
+
return Path(env)
|
|
61
|
+
return Path(__file__).resolve().parent.parent / "assets"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def local_dictionary() -> Path:
|
|
65
|
+
return assets_dir() / "dictionary.json"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _utf8_streams() -> None:
|
|
69
|
+
for stream in (sys.stdout, sys.stderr, sys.stdin):
|
|
70
|
+
try:
|
|
71
|
+
stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined]
|
|
72
|
+
except Exception: # pragma: no cover
|
|
73
|
+
try:
|
|
74
|
+
stream.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
|
|
75
|
+
except Exception:
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def load_source(path: str, ascii_mode: bool, vertical: bool | None) -> str:
|
|
80
|
+
p = Path(path)
|
|
81
|
+
text = p.read_text(encoding="utf-8")
|
|
82
|
+
if vertical is None:
|
|
83
|
+
vertical = p.suffix == VERTICAL_EXT
|
|
84
|
+
if vertical:
|
|
85
|
+
text = from_vertical(text)
|
|
86
|
+
if ascii_mode:
|
|
87
|
+
text = transliterate(text)
|
|
88
|
+
return text
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _exit_code(err: SystemExit) -> int:
|
|
92
|
+
code = err.code
|
|
93
|
+
if code is None:
|
|
94
|
+
return 0
|
|
95
|
+
if isinstance(code, int):
|
|
96
|
+
return code
|
|
97
|
+
return 1
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _run_program(source: str, root: Path, ascii_mode: bool, argv: list[str]) -> int:
|
|
101
|
+
try:
|
|
102
|
+
program = parse(source, base_dir=root)
|
|
103
|
+
Interpreter(
|
|
104
|
+
base_dir=root,
|
|
105
|
+
ascii_mode=ascii_mode,
|
|
106
|
+
argv=argv,
|
|
107
|
+
).run(program)
|
|
108
|
+
except PhyrexianError as err:
|
|
109
|
+
print(format_error(err, source), file=sys.stderr)
|
|
110
|
+
return 1
|
|
111
|
+
except SystemExit as err:
|
|
112
|
+
return _exit_code(err)
|
|
113
|
+
return 0
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# ----------------------------------------------------------------- commands
|
|
117
|
+
def cmd_run(args: argparse.Namespace) -> int:
|
|
118
|
+
source = load_source(args.file, args.ascii, args.vertical)
|
|
119
|
+
root = Path(args.file).resolve().parent
|
|
120
|
+
return _run_program(source, root, bool(args.ascii), list(args.script_args or []))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cmd_eval(args: argparse.Namespace) -> int:
|
|
124
|
+
source = args.code
|
|
125
|
+
if args.ascii:
|
|
126
|
+
source = transliterate(source)
|
|
127
|
+
return _run_program(source, Path.cwd(), bool(args.ascii), list(args.script_args or []))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def cmd_check(args: argparse.Namespace) -> int:
|
|
131
|
+
source = load_source(args.file, args.ascii, args.vertical)
|
|
132
|
+
try:
|
|
133
|
+
program = parse(source, base_dir=Path(args.file).resolve().parent)
|
|
134
|
+
except PhyrexianError as err:
|
|
135
|
+
print(format_error(err, source), file=sys.stderr)
|
|
136
|
+
return 1
|
|
137
|
+
print(f"{args.file}: {len(program)} top-level sentence{'s' if len(program) != 1 else ''}, grammar is sound")
|
|
138
|
+
return 0
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def cmd_explain(args: argparse.Namespace) -> int:
|
|
142
|
+
unknown = 0
|
|
143
|
+
for word in args.words:
|
|
144
|
+
text = explain_word(word)
|
|
145
|
+
if text is None:
|
|
146
|
+
print(explain_missing(word), file=sys.stderr)
|
|
147
|
+
unknown += 1
|
|
148
|
+
else:
|
|
149
|
+
print(text)
|
|
150
|
+
print()
|
|
151
|
+
return 1 if unknown else 0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def cmd_fmt(args: argparse.Namespace) -> int:
|
|
155
|
+
source = Path(args.file).read_text(encoding="utf-8")
|
|
156
|
+
try:
|
|
157
|
+
formatted = format_source(source)
|
|
158
|
+
except PhyrexianError as err:
|
|
159
|
+
print(format_error(err, source), file=sys.stderr)
|
|
160
|
+
return 1
|
|
161
|
+
if args.in_place:
|
|
162
|
+
Path(args.file).write_text(formatted, encoding="utf-8")
|
|
163
|
+
if formatted != source:
|
|
164
|
+
print(f"rewrote {args.file}")
|
|
165
|
+
return 0
|
|
166
|
+
if args.output:
|
|
167
|
+
Path(args.output).write_text(formatted, encoding="utf-8")
|
|
168
|
+
print(f"wrote {args.output}")
|
|
169
|
+
return 0
|
|
170
|
+
sys.stdout.write(formatted)
|
|
171
|
+
return 0
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def cmd_lint(args: argparse.Namespace) -> int:
|
|
175
|
+
source = load_source(args.file, args.ascii, args.vertical)
|
|
176
|
+
try:
|
|
177
|
+
program = parse(source, base_dir=Path(args.file).resolve().parent)
|
|
178
|
+
except PhyrexianError as err:
|
|
179
|
+
print(format_error(err, source), file=sys.stderr)
|
|
180
|
+
return 1
|
|
181
|
+
notes = lint_program(program)
|
|
182
|
+
if not notes:
|
|
183
|
+
print(f"{args.file}: no notes")
|
|
184
|
+
return 0
|
|
185
|
+
print(format_notes(notes, args.file))
|
|
186
|
+
return 1
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def cmd_dis(args: argparse.Namespace) -> int:
|
|
190
|
+
source = load_source(args.file, args.ascii, args.vertical)
|
|
191
|
+
try:
|
|
192
|
+
program = parse(source, base_dir=Path(args.file).resolve().parent)
|
|
193
|
+
sys.stdout.write(compile_to_python(program))
|
|
194
|
+
except PhyrexianError as err:
|
|
195
|
+
print(format_error(err, source), file=sys.stderr)
|
|
196
|
+
return 1
|
|
197
|
+
return 0
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def cmd_render(args: argparse.Namespace) -> int:
|
|
201
|
+
source = load_source(args.file, args.ascii, args.vertical)
|
|
202
|
+
title = args.title or Path(args.file).name
|
|
203
|
+
try:
|
|
204
|
+
font = ensure_font()
|
|
205
|
+
except OSError as err:
|
|
206
|
+
font = local_font()
|
|
207
|
+
print(f"warning: could not fetch Phyrexian Regular ({err})", file=sys.stderr)
|
|
208
|
+
page = render_html(source, title=title, local_font=font, size=args.size)
|
|
209
|
+
out = Path(args.output) if args.output else Path(args.file).with_suffix(".html")
|
|
210
|
+
out.write_text(page, encoding="utf-8")
|
|
211
|
+
note = (
|
|
212
|
+
f"embedded {FONT_FAMILY}"
|
|
213
|
+
if is_font_file(font)
|
|
214
|
+
else "font loaded from the Phyrexian Dictionary CDN"
|
|
215
|
+
)
|
|
216
|
+
print(f"wrote {out} ({note})")
|
|
217
|
+
return 0
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def cmd_transpose(args: argparse.Namespace) -> int:
|
|
221
|
+
p = Path(args.file)
|
|
222
|
+
text = p.read_text(encoding="utf-8")
|
|
223
|
+
to_vert = args.to_vertical or (not args.to_horizontal and p.suffix != VERTICAL_EXT)
|
|
224
|
+
result = to_vertical(text, gap=args.gap) if to_vert else from_vertical(text, gap=args.gap)
|
|
225
|
+
if args.output:
|
|
226
|
+
Path(args.output).write_text(result, encoding="utf-8")
|
|
227
|
+
print(f"wrote {args.output}")
|
|
228
|
+
else:
|
|
229
|
+
sys.stdout.write(result)
|
|
230
|
+
return 0
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def cmd_translit(args: argparse.Namespace) -> int:
|
|
234
|
+
text = Path(args.file).read_text(encoding="utf-8")
|
|
235
|
+
result = untransliterate(text) if args.reverse else transliterate(text)
|
|
236
|
+
if args.output:
|
|
237
|
+
Path(args.output).write_text(result, encoding="utf-8")
|
|
238
|
+
print(f"wrote {args.output}")
|
|
239
|
+
else:
|
|
240
|
+
sys.stdout.write(result)
|
|
241
|
+
return 0
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def cmd_fetch(args: argparse.Namespace) -> int:
|
|
245
|
+
print("fetching Phyrexian Regular (official card font, family name: Phyrexian)")
|
|
246
|
+
font = ensure_font()
|
|
247
|
+
print(f" -> {font}")
|
|
248
|
+
print("fetching Basilica (native hexadecimal glyphs)")
|
|
249
|
+
basilica = ensure_basilica()
|
|
250
|
+
print(f" -> {basilica}")
|
|
251
|
+
dest = local_dictionary()
|
|
252
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
253
|
+
print(f"fetching {DICT_REMOTE}")
|
|
254
|
+
req = urllib.request.Request(DICT_REMOTE, headers={"User-Agent": "phyx-font-fetch"})
|
|
255
|
+
with urllib.request.urlopen(req, timeout=60) as resp: # noqa: S310 - fixed https URLs
|
|
256
|
+
dest.write_bytes(resp.read())
|
|
257
|
+
print(f" -> {dest}")
|
|
258
|
+
for path, family in ((font, FONT_FAMILY), (basilica, "Basilica")):
|
|
259
|
+
installed = install_user_font(path, family)
|
|
260
|
+
if installed:
|
|
261
|
+
print(f"installed {family} for this user: {installed}")
|
|
262
|
+
print("done. Phyrexian Regular is GPL-3.0 (Wizards / dictionary repo); Basilica is CC-BY.")
|
|
263
|
+
return 0
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def cmd_bench(args: argparse.Namespace) -> int:
|
|
267
|
+
"""Time compiled abilities against the same Python (parse/compile once)."""
|
|
268
|
+
import time
|
|
269
|
+
|
|
270
|
+
n = max(8, int(args.size))
|
|
271
|
+
loops = max(1000, int(args.loops))
|
|
272
|
+
hex_n = format_number(n)
|
|
273
|
+
hex_loops = format_number(loops)
|
|
274
|
+
fib_src = (
|
|
275
|
+
"^ťe-n-fib:\n"
|
|
276
|
+
" ^ba-n-ķu-grmɒɣg:lo-n-'iţpənn.\n"
|
|
277
|
+
" ^lo-n-'ii-mɒɣg-fib-n-ķu-mɒɣg-fib-babg-'iţpənn.\n"
|
|
278
|
+
f"!{hex_n}-fib.\n"
|
|
279
|
+
)
|
|
280
|
+
loop_src = (
|
|
281
|
+
"^ťe-k-sum:\n"
|
|
282
|
+
" ^xe-0-s-ţə''.\n"
|
|
283
|
+
" ^xe-0-i-ţə''.\n"
|
|
284
|
+
" ^baxuφ-i-k-grmɒɣg:\n"
|
|
285
|
+
" ^xe-s-i-babg-s-ţə''.\n"
|
|
286
|
+
" ^xe-i-1-babg-i-ţə''.\n"
|
|
287
|
+
" ^lo-s-'iţpənn.\n"
|
|
288
|
+
f"!{hex_loops}-sum.\n"
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
def py_fib(k):
|
|
292
|
+
if k < 2:
|
|
293
|
+
return k
|
|
294
|
+
return py_fib(k - 1) + py_fib(k - 2)
|
|
295
|
+
|
|
296
|
+
def py_loop(k):
|
|
297
|
+
s = i = 0
|
|
298
|
+
while i < k:
|
|
299
|
+
s += i
|
|
300
|
+
i += 1
|
|
301
|
+
return s
|
|
302
|
+
|
|
303
|
+
def best(fn, repeats=4):
|
|
304
|
+
fn()
|
|
305
|
+
t = 1e9
|
|
306
|
+
for _ in range(repeats):
|
|
307
|
+
t0 = time.perf_counter()
|
|
308
|
+
fn()
|
|
309
|
+
t = min(t, time.perf_counter() - t0)
|
|
310
|
+
return t
|
|
311
|
+
|
|
312
|
+
def load_ability(src, name):
|
|
313
|
+
interp = Interpreter(stdout=io.StringIO())
|
|
314
|
+
interp.run(parse(src))
|
|
315
|
+
ability = interp.globals.vars[name]
|
|
316
|
+
return interp, ability.impl
|
|
317
|
+
|
|
318
|
+
fib_rt, fib_impl = load_ability(fib_src, "fib")
|
|
319
|
+
sum_rt, sum_impl = load_ability(loop_src, "sum")
|
|
320
|
+
|
|
321
|
+
pf = best(lambda: py_fib(n))
|
|
322
|
+
cf = best(lambda: fib_impl(fib_rt, n))
|
|
323
|
+
pl = best(lambda: py_loop(loops))
|
|
324
|
+
cl = best(lambda: sum_impl(sum_rt, loops))
|
|
325
|
+
print(f"φyrx {__version__} (compiles to CPython; timed after compile)")
|
|
326
|
+
print(f"fib({n}) python {pf*1000:7.2f} ms φyrx {cf*1000:7.2f} ms {cf/pf:4.1f}×")
|
|
327
|
+
print(f"loop {loops} python {pl*1000:7.2f} ms φyrx {cl*1000:7.2f} ms {cl/pl:4.1f}×")
|
|
328
|
+
print("Set PHYX_TREEWALK=1 to time the old AST walker.")
|
|
329
|
+
return 0
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def cmd_lookup(args: argparse.Namespace) -> int:
|
|
333
|
+
lex_hits: list[tuple[str, str, str, str]] = []
|
|
334
|
+
for query in args.words:
|
|
335
|
+
lex_hits.extend(search_lexicon(query))
|
|
336
|
+
|
|
337
|
+
dict_hits: list[dict] = []
|
|
338
|
+
path = local_dictionary()
|
|
339
|
+
if path.is_file():
|
|
340
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
341
|
+
entries = list(data["dictionary"].values())
|
|
342
|
+
for query in args.words:
|
|
343
|
+
q = query.lower()
|
|
344
|
+
q_phy = transliterate(query)
|
|
345
|
+
for e in entries:
|
|
346
|
+
phy = e.get("phyrexian") or ""
|
|
347
|
+
tr = (e.get("translation") or "").lower()
|
|
348
|
+
if q in tr or q in phy or q_phy in phy:
|
|
349
|
+
dict_hits.append(e)
|
|
350
|
+
|
|
351
|
+
if not lex_hits and not dict_hits:
|
|
352
|
+
print("nothing found")
|
|
353
|
+
return 1
|
|
354
|
+
|
|
355
|
+
seen_lex: set[tuple[str, str]] = set()
|
|
356
|
+
for word, gloss, kind, extra in lex_hits:
|
|
357
|
+
key = (word, kind)
|
|
358
|
+
if key in seen_lex:
|
|
359
|
+
continue
|
|
360
|
+
seen_lex.add(key)
|
|
361
|
+
print(f"{word:<18} {gloss:<28} {kind:<14} {extra}")
|
|
362
|
+
|
|
363
|
+
if dict_hits:
|
|
364
|
+
if lex_hits:
|
|
365
|
+
print()
|
|
366
|
+
print("dictionary")
|
|
367
|
+
seen_dict: set[tuple[str, str]] = set()
|
|
368
|
+
for e in dict_hits:
|
|
369
|
+
key = (e["phyrexian"], e["translation"])
|
|
370
|
+
if key in seen_dict:
|
|
371
|
+
continue
|
|
372
|
+
seen_dict.add(key)
|
|
373
|
+
plural = e.get("plural")
|
|
374
|
+
plural_s = "" if plural in (None, "FALSE") else f" pl. {plural}"
|
|
375
|
+
print(
|
|
376
|
+
f"{e['phyrexian']:<18} {e['translation']:<28} {e.get('class') or '':<14} "
|
|
377
|
+
f"{e.get('type') or '':<10} {e.get('confidence') or ''}{plural_s}"
|
|
378
|
+
)
|
|
379
|
+
return 0
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def cmd_repl(args: argparse.Namespace) -> int:
|
|
383
|
+
ascii_mode = bool(getattr(args, "ascii", False))
|
|
384
|
+
return Repl(ascii_mode=ascii_mode).run()
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def cmd_words(args: argparse.Namespace) -> int:
|
|
388
|
+
print("MOOD MARKERS (first word of a phrase)")
|
|
389
|
+
for w, (kind, gloss) in MARKERS.items():
|
|
390
|
+
print(f" {w:<10} {kind:<8} {gloss}")
|
|
391
|
+
print("\nVERBS (objects first, verb last)")
|
|
392
|
+
for v in VERBS.values():
|
|
393
|
+
ar = "N…" if v.arity == -1 else str(v.arity)
|
|
394
|
+
print(f" {v.word:<16} {ar:<3} {v.gloss:<14} {v.doc}")
|
|
395
|
+
print("\nCONSTANTS")
|
|
396
|
+
for w, val in CONSTANTS.items():
|
|
397
|
+
print(f" {w:<10} {val!r}")
|
|
398
|
+
return 0
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def cmd_test(args: argparse.Namespace) -> int:
|
|
402
|
+
paths = list(args.paths) if getattr(args, "paths", None) else ["tests"]
|
|
403
|
+
roots = [Path(p) for p in paths]
|
|
404
|
+
if not any(r.exists() for r in roots):
|
|
405
|
+
roots = [Path(".")]
|
|
406
|
+
return run_suite(roots, ascii_mode=bool(getattr(args, "ascii", False)))
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _walk_stmts(stmts: list) -> Iterable:
|
|
410
|
+
for stmt in stmts:
|
|
411
|
+
yield stmt
|
|
412
|
+
body = getattr(stmt, "body", None)
|
|
413
|
+
if body:
|
|
414
|
+
yield from _walk_stmts(body)
|
|
415
|
+
orelse = getattr(stmt, "orelse", None)
|
|
416
|
+
if orelse:
|
|
417
|
+
yield from _walk_stmts(orelse)
|
|
418
|
+
handler = getattr(stmt, "handler", None)
|
|
419
|
+
if handler:
|
|
420
|
+
yield from _walk_stmts(handler)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def cmd_lib(args: argparse.Namespace) -> int:
|
|
424
|
+
folder = stdlib_dir()
|
|
425
|
+
print(f"standard library: {folder}")
|
|
426
|
+
print("bukð looks in: the file's directory, the working directory, PHYX_PATH, then here.")
|
|
427
|
+
print('A name without a suffix is tried as .phyx then .vphyx: ^lo-"asərθ"-bukð.')
|
|
428
|
+
if not folder.is_dir():
|
|
429
|
+
print("no phyx/lib directory in this install", file=sys.stderr)
|
|
430
|
+
return 1
|
|
431
|
+
for path in sorted(folder.glob("*.phyx")):
|
|
432
|
+
program = parse(path.read_text(encoding="utf-8"), base_dir=path.parent)
|
|
433
|
+
defs: list[str] = []
|
|
434
|
+
casts: list[str] = []
|
|
435
|
+
for stmt in _walk_stmts(program):
|
|
436
|
+
if isinstance(stmt, phyx_ast.FuncDef):
|
|
437
|
+
defs.append(f"{stmt.name}/{len(stmt.params)}")
|
|
438
|
+
exprs = getattr(stmt, "exprs", None) or []
|
|
439
|
+
for expr in exprs:
|
|
440
|
+
if (
|
|
441
|
+
isinstance(expr, phyx_ast.Call)
|
|
442
|
+
and expr.verb.word == "bukð"
|
|
443
|
+
and expr.args
|
|
444
|
+
and isinstance(expr.args[0], phyx_ast.Literal)
|
|
445
|
+
):
|
|
446
|
+
casts.append(str(expr.args[0].value))
|
|
447
|
+
print(f"\n {path.name}")
|
|
448
|
+
if casts:
|
|
449
|
+
print(f" casts {', '.join(casts)}")
|
|
450
|
+
for name in defs:
|
|
451
|
+
print(f" {name}")
|
|
452
|
+
if not defs and not casts:
|
|
453
|
+
print(" (empty)")
|
|
454
|
+
return 0
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
# ----------------------------------------------------------------- main
|
|
458
|
+
def normalize_argv(argv: list[str]) -> list[str]:
|
|
459
|
+
"""``phyx FILE`` runs a program; ``phyx -c CODE`` evaluates a string."""
|
|
460
|
+
if not argv:
|
|
461
|
+
return ["repl"]
|
|
462
|
+
if argv[0] in ("-h", "--help", "-V", "--version"):
|
|
463
|
+
return argv
|
|
464
|
+
if argv[0] == "-c":
|
|
465
|
+
return ["eval", *argv[1:]]
|
|
466
|
+
if argv[0] == "--ascii":
|
|
467
|
+
rest = argv[1:]
|
|
468
|
+
if not rest:
|
|
469
|
+
return ["repl", "--ascii"]
|
|
470
|
+
if rest[0] == "-c":
|
|
471
|
+
return ["eval", "--ascii", *rest[1:]]
|
|
472
|
+
if rest[0] in SUBCOMMANDS:
|
|
473
|
+
return [rest[0], "--ascii", *rest[1:]]
|
|
474
|
+
return ["run", "--ascii", *rest]
|
|
475
|
+
if argv[0] not in SUBCOMMANDS and not argv[0].startswith("-"):
|
|
476
|
+
return ["run", *argv]
|
|
477
|
+
return argv
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
481
|
+
also = " / ".join(LANGUAGE_ALIASES)
|
|
482
|
+
prog = Path(sys.argv[0]).stem or "phyx"
|
|
483
|
+
ap = argparse.ArgumentParser(
|
|
484
|
+
prog=prog,
|
|
485
|
+
description=f"{LANGUAGE} ({also}) — a programming language written in Phyrexian.",
|
|
486
|
+
)
|
|
487
|
+
ap.add_argument(
|
|
488
|
+
"-V", "--version",
|
|
489
|
+
action="version",
|
|
490
|
+
version=f"{LANGUAGE} {__version__} ({also})",
|
|
491
|
+
)
|
|
492
|
+
sub = ap.add_subparsers(dest="command")
|
|
493
|
+
|
|
494
|
+
def source_opts(p: argparse.ArgumentParser) -> None:
|
|
495
|
+
p.add_argument("file", help="program file (.phyx, or .vphyx for vertical layout)")
|
|
496
|
+
p.add_argument("--ascii", action="store_true",
|
|
497
|
+
help="source uses ASCII capitals for special letters (see `translit`)")
|
|
498
|
+
grp = p.add_mutually_exclusive_group()
|
|
499
|
+
grp.add_argument("--vertical", dest="vertical", action="store_true", default=None,
|
|
500
|
+
help="source is laid out vertically (columns)")
|
|
501
|
+
grp.add_argument("--horizontal", dest="vertical", action="store_false",
|
|
502
|
+
help="source is laid out as text rows (default for .phyx)")
|
|
503
|
+
|
|
504
|
+
p = sub.add_parser("run", help="run a program")
|
|
505
|
+
source_opts(p)
|
|
506
|
+
p.add_argument("script_args", nargs="*", metavar="ARG",
|
|
507
|
+
help="bound to the verb 'uxq (command) inside the program")
|
|
508
|
+
p.set_defaults(fn=cmd_run)
|
|
509
|
+
|
|
510
|
+
p = sub.add_parser("eval", help="run a program from a string (also: phyx -c CODE)")
|
|
511
|
+
p.add_argument("--ascii", action="store_true",
|
|
512
|
+
help="source uses ASCII capitals for special letters")
|
|
513
|
+
p.add_argument("code", help="complete φyrx sentences")
|
|
514
|
+
p.add_argument("script_args", nargs="*", metavar="ARG",
|
|
515
|
+
help="bound to 'uxq")
|
|
516
|
+
p.set_defaults(fn=cmd_eval)
|
|
517
|
+
|
|
518
|
+
p = sub.add_parser("check", help="parse a program without running it")
|
|
519
|
+
source_opts(p)
|
|
520
|
+
p.set_defaults(fn=cmd_check)
|
|
521
|
+
|
|
522
|
+
p = sub.add_parser("dis", help="print the CPython a φyrx program compiles to")
|
|
523
|
+
source_opts(p)
|
|
524
|
+
p.set_defaults(fn=cmd_dis)
|
|
525
|
+
|
|
526
|
+
p = sub.add_parser("explain", help="describe a marker, verb, constant, or English word")
|
|
527
|
+
p.add_argument("words", nargs="+")
|
|
528
|
+
p.set_defaults(fn=cmd_explain)
|
|
529
|
+
|
|
530
|
+
p = sub.add_parser("fmt", help="rewrite a program with canonical separators and 4-space indent")
|
|
531
|
+
p.add_argument("file")
|
|
532
|
+
p.add_argument("-o", "--output")
|
|
533
|
+
p.add_argument("-i", "--in-place", action="store_true")
|
|
534
|
+
p.set_defaults(fn=cmd_fmt)
|
|
535
|
+
|
|
536
|
+
p = sub.add_parser("lint", help="name traps (dropped return, unused objects, English words)")
|
|
537
|
+
source_opts(p)
|
|
538
|
+
p.set_defaults(fn=cmd_lint)
|
|
539
|
+
|
|
540
|
+
p = sub.add_parser("render", help="render a program as vertical Phyrexian script (HTML)")
|
|
541
|
+
source_opts(p)
|
|
542
|
+
p.add_argument("-o", "--output", help="output .html (default: next to the source)")
|
|
543
|
+
p.add_argument("--title", help="page title")
|
|
544
|
+
p.add_argument("--size", type=int, default=34, help="glyph size in px (default 34)")
|
|
545
|
+
p.set_defaults(fn=cmd_render)
|
|
546
|
+
|
|
547
|
+
p = sub.add_parser("transpose", help="convert between row layout (.phyx) and column layout (.vphyx)")
|
|
548
|
+
p.add_argument("file")
|
|
549
|
+
p.add_argument("-o", "--output")
|
|
550
|
+
p.add_argument("--gap", type=int, default=1, help="blank columns between lines (default 1)")
|
|
551
|
+
grp = p.add_mutually_exclusive_group()
|
|
552
|
+
grp.add_argument("--to-vertical", action="store_true")
|
|
553
|
+
grp.add_argument("--to-horizontal", action="store_true")
|
|
554
|
+
p.set_defaults(fn=cmd_transpose)
|
|
555
|
+
|
|
556
|
+
p = sub.add_parser("translit", help="ASCII capitals -> Phyrexian letters (or back with --reverse)")
|
|
557
|
+
p.add_argument("file")
|
|
558
|
+
p.add_argument("-o", "--output")
|
|
559
|
+
p.add_argument("--reverse", action="store_true")
|
|
560
|
+
p.set_defaults(fn=cmd_translit)
|
|
561
|
+
|
|
562
|
+
p = sub.add_parser(
|
|
563
|
+
"fetch",
|
|
564
|
+
help="download Phyrexian Regular + Basilica + dictionary (installs the font for this user on Windows)",
|
|
565
|
+
)
|
|
566
|
+
p.set_defaults(fn=cmd_fetch)
|
|
567
|
+
|
|
568
|
+
p = sub.add_parser("lookup", help="search the lexicon (and the fetched dictionary if present)")
|
|
569
|
+
p.add_argument("words", nargs="+")
|
|
570
|
+
p.set_defaults(fn=cmd_lookup)
|
|
571
|
+
|
|
572
|
+
p = sub.add_parser("words", help="list the markers, verbs and constants of the language")
|
|
573
|
+
p.set_defaults(fn=cmd_words)
|
|
574
|
+
|
|
575
|
+
p = sub.add_parser("bench", help="time φyrx against the same algorithm in Python")
|
|
576
|
+
p.add_argument("--size", type=int, default=16, help="fibonacci argument (decimal, default 16)")
|
|
577
|
+
p.add_argument("--loops", type=int, default=20000, help="tight-loop iterations (default 20000)")
|
|
578
|
+
p.set_defaults(fn=cmd_bench)
|
|
579
|
+
|
|
580
|
+
p = sub.add_parser("repl", help="interactive session (default when no command is given)")
|
|
581
|
+
p.add_argument("--ascii", action="store_true",
|
|
582
|
+
help="type special letters as ASCII capitals")
|
|
583
|
+
p.set_defaults(fn=cmd_repl)
|
|
584
|
+
|
|
585
|
+
p = sub.add_parser("test", help="run φyrx tests (test_*.phyx; ǩaπa and optional .expected)")
|
|
586
|
+
p.add_argument("paths", nargs="*", help="files or directories (default: tests/)")
|
|
587
|
+
p.add_argument("--ascii", action="store_true",
|
|
588
|
+
help="source uses ASCII capitals for special letters")
|
|
589
|
+
p.set_defaults(fn=cmd_test)
|
|
590
|
+
|
|
591
|
+
p = sub.add_parser("lib", help="list the shipped standard herds")
|
|
592
|
+
p.set_defaults(fn=cmd_lib)
|
|
593
|
+
return ap
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def main(argv: list[str] | None = None) -> int:
|
|
597
|
+
_utf8_streams()
|
|
598
|
+
if argv is None:
|
|
599
|
+
argv = sys.argv[1:]
|
|
600
|
+
argv = normalize_argv(list(argv))
|
|
601
|
+
try:
|
|
602
|
+
args = build_parser().parse_args(argv)
|
|
603
|
+
if getattr(args, "command", None) is None:
|
|
604
|
+
return cmd_repl(argparse.Namespace(ascii=False))
|
|
605
|
+
return args.fn(args)
|
|
606
|
+
except PhyrexianError as err:
|
|
607
|
+
print(str(err), file=sys.stderr)
|
|
608
|
+
return 1
|
|
609
|
+
except FileNotFoundError as err:
|
|
610
|
+
print(f"ɬšeɴazv: no such file: {err.filename}", file=sys.stderr)
|
|
611
|
+
return 1
|
|
612
|
+
except ValueError as err:
|
|
613
|
+
print(f"ɬšeɴazv: {err}", file=sys.stderr)
|
|
614
|
+
return 1
|
|
615
|
+
except SystemExit as err:
|
|
616
|
+
return _exit_code(err)
|
|
617
|
+
except KeyboardInterrupt:
|
|
618
|
+
print("\nɬšeɴazv: stopped", file=sys.stderr)
|
|
619
|
+
return 130
|