sylix 1.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.
- sylix-1.0.0/PKG-INFO +47 -0
- sylix-1.0.0/README.md +40 -0
- sylix-1.0.0/pyproject.toml +17 -0
- sylix-1.0.0/setup.cfg +4 -0
- sylix-1.0.0/sylix/__init__.py +3 -0
- sylix-1.0.0/sylix/__main__.py +6 -0
- sylix-1.0.0/sylix/ast_nodes.py +179 -0
- sylix-1.0.0/sylix/cli.py +123 -0
- sylix-1.0.0/sylix/errors.py +36 -0
- sylix-1.0.0/sylix/game_lib.py +116 -0
- sylix-1.0.0/sylix/interpreter.py +521 -0
- sylix-1.0.0/sylix/lexer.py +222 -0
- sylix-1.0.0/sylix/optimizer.py +174 -0
- sylix-1.0.0/sylix/parser.py +477 -0
- sylix-1.0.0/sylix/tokens.py +115 -0
- sylix-1.0.0/sylix.egg-info/PKG-INFO +47 -0
- sylix-1.0.0/sylix.egg-info/SOURCES.txt +27 -0
- sylix-1.0.0/sylix.egg-info/dependency_links.txt +1 -0
- sylix-1.0.0/sylix.egg-info/entry_points.txt +2 -0
- sylix-1.0.0/sylix.egg-info/top_level.txt +1 -0
- sylix-1.0.0/tests/test_step01.py +49 -0
- sylix-1.0.0/tests/test_step02.py +79 -0
- sylix-1.0.0/tests/test_step03.py +69 -0
- sylix-1.0.0/tests/test_step04.py +60 -0
- sylix-1.0.0/tests/test_step05.py +54 -0
- sylix-1.0.0/tests/test_step06.py +52 -0
- sylix-1.0.0/tests/test_step07.py +71 -0
- sylix-1.0.0/tests/test_step08.py +72 -0
- sylix-1.0.0/tests/test_step09_game.py +55 -0
sylix-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sylix
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Sylix — Custom personal scripting language with game support and .sylc compilation.
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
|
|
8
|
+
# Sylix (v1.0.0)
|
|
9
|
+
|
|
10
|
+
직접 설계한 독자 문법의 커스텀 스크립트 언어 **Sylix 1.0.0**입니다.
|
|
11
|
+
|
|
12
|
+
## 설치 및 실행
|
|
13
|
+
|
|
14
|
+
```powershell
|
|
15
|
+
# 로컬 설치 (어디서나 `sylix` 명령어 사용 가능)
|
|
16
|
+
pip install -e .
|
|
17
|
+
|
|
18
|
+
# 파일 실행 / 컴파일 / REPL
|
|
19
|
+
sylix run examples/step08.syl
|
|
20
|
+
sylix compile examples/step08.syl
|
|
21
|
+
sylix run examples/step08.sylc
|
|
22
|
+
sylix
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### PyPI 배포 (선택)
|
|
26
|
+
```powershell
|
|
27
|
+
python -m pip install build twine
|
|
28
|
+
python -m build
|
|
29
|
+
twine upload dist/*
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## 전체 문법 요약 (0.1 ~ 1.0)
|
|
35
|
+
|
|
36
|
+
- **0.1 출력 · 변수 · 자료형:** `out("안녕")`, `S: x = 10`, 정수/실수/문자열/`true`/`false`/`null`
|
|
37
|
+
- **0.2 연산자 · 조건문 · 반복문:**
|
|
38
|
+
- 연산자: `+`, `-`, `*`, `/`, `%`, `==`, `!=`, `<`, `<=`, `>`, `>=`, `and`/`&&`, `or`/`||`, `not`/`!`, `x ++ 1`
|
|
39
|
+
- 조건문: `?s 조건 ?o ... n` (참), `?s 조건 ?x ... n` (거짓)
|
|
40
|
+
- 반복문: `f (S: x = 1, t: x = 5); x ++ 1`, `sw t: x < 10 n ... n`, `sw in n ... n`, `stop`
|
|
41
|
+
- **0.3 함수 · 지역변수 · 반환:** `q 이름(a, b) n ... n`, `back 값`
|
|
42
|
+
- **0.4 배열 · 객체 · 문자열:** `<1, 2, 3>` (`get`, `set`, `push`, `pop`, `len`), `{ coin: 100 }` (`obj.coin`)
|
|
43
|
+
- **0.5 파일 입출력 · 오류 처리:** `save(경로, 내용)`, `load(경로)`, `?t ... ?f e ... n`
|
|
44
|
+
- **0.6 모듈 · 라이브러리:** `@S:("파일.syl")`, `@S:("random")`, `@S:("time")`, `@S:("math")`, `@S:("game")`
|
|
45
|
+
- **0.7 클래스 · 객체지향:** `c Player n ... n`, `q init(...) n ... n`, `self`, `S: p1 = Player(...)`
|
|
46
|
+
- **0.8 메모리 관리 · 최적화:** `del(S: x) n`, 상수 접기 최적화, `.sylc` 컴파일
|
|
47
|
+
- **0.9 게임 제작 지원:** `nard("입력: ")`, `to_num()`, `to_str()`, `stop`, `@S:("game")` 2D 창/그리기/키보드 입력
|
sylix-1.0.0/README.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Sylix (v1.0.0)
|
|
2
|
+
|
|
3
|
+
직접 설계한 독자 문법의 커스텀 스크립트 언어 **Sylix 1.0.0**입니다.
|
|
4
|
+
|
|
5
|
+
## 설치 및 실행
|
|
6
|
+
|
|
7
|
+
```powershell
|
|
8
|
+
# 로컬 설치 (어디서나 `sylix` 명령어 사용 가능)
|
|
9
|
+
pip install -e .
|
|
10
|
+
|
|
11
|
+
# 파일 실행 / 컴파일 / REPL
|
|
12
|
+
sylix run examples/step08.syl
|
|
13
|
+
sylix compile examples/step08.syl
|
|
14
|
+
sylix run examples/step08.sylc
|
|
15
|
+
sylix
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
### PyPI 배포 (선택)
|
|
19
|
+
```powershell
|
|
20
|
+
python -m pip install build twine
|
|
21
|
+
python -m build
|
|
22
|
+
twine upload dist/*
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 전체 문법 요약 (0.1 ~ 1.0)
|
|
28
|
+
|
|
29
|
+
- **0.1 출력 · 변수 · 자료형:** `out("안녕")`, `S: x = 10`, 정수/실수/문자열/`true`/`false`/`null`
|
|
30
|
+
- **0.2 연산자 · 조건문 · 반복문:**
|
|
31
|
+
- 연산자: `+`, `-`, `*`, `/`, `%`, `==`, `!=`, `<`, `<=`, `>`, `>=`, `and`/`&&`, `or`/`||`, `not`/`!`, `x ++ 1`
|
|
32
|
+
- 조건문: `?s 조건 ?o ... n` (참), `?s 조건 ?x ... n` (거짓)
|
|
33
|
+
- 반복문: `f (S: x = 1, t: x = 5); x ++ 1`, `sw t: x < 10 n ... n`, `sw in n ... n`, `stop`
|
|
34
|
+
- **0.3 함수 · 지역변수 · 반환:** `q 이름(a, b) n ... n`, `back 값`
|
|
35
|
+
- **0.4 배열 · 객체 · 문자열:** `<1, 2, 3>` (`get`, `set`, `push`, `pop`, `len`), `{ coin: 100 }` (`obj.coin`)
|
|
36
|
+
- **0.5 파일 입출력 · 오류 처리:** `save(경로, 내용)`, `load(경로)`, `?t ... ?f e ... n`
|
|
37
|
+
- **0.6 모듈 · 라이브러리:** `@S:("파일.syl")`, `@S:("random")`, `@S:("time")`, `@S:("math")`, `@S:("game")`
|
|
38
|
+
- **0.7 클래스 · 객체지향:** `c Player n ... n`, `q init(...) n ... n`, `self`, `S: p1 = Player(...)`
|
|
39
|
+
- **0.8 메모리 관리 · 최적화:** `del(S: x) n`, 상수 접기 최적화, `.sylc` 컴파일
|
|
40
|
+
- **0.9 게임 제작 지원:** `nard("입력: ")`, `to_num()`, `to_str()`, `stop`, `@S:("game")` 2D 창/그리기/키보드 입력
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sylix"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Sylix — Custom personal scripting language with game support and .sylc compilation."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = []
|
|
12
|
+
|
|
13
|
+
[project.scripts]
|
|
14
|
+
sylix = "sylix.cli:main"
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.packages.find]
|
|
17
|
+
include = ["sylix*"]
|
sylix-1.0.0/setup.cfg
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""AST nodes for Sylix 0.4."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .errors import SourceLocation
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class Node:
|
|
11
|
+
location: SourceLocation
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Program(Node):
|
|
16
|
+
statements: list["Stmt"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Stmt(Node):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class ExprStmt(Stmt):
|
|
25
|
+
expr: "Expr"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class VarSetStmt(Stmt):
|
|
30
|
+
"""Variable declaration/assignment: S:name = expr"""
|
|
31
|
+
name: str
|
|
32
|
+
value: "Expr"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class MemberSetStmt(Stmt):
|
|
37
|
+
"""Object field assignment: S:obj.field = expr"""
|
|
38
|
+
target: "Expr"
|
|
39
|
+
field: str
|
|
40
|
+
value: "Expr"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class VarAddStmt(Stmt):
|
|
45
|
+
"""Increment statement: name ++ expr"""
|
|
46
|
+
name: str
|
|
47
|
+
delta: "Expr"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class OutStmt(Stmt):
|
|
52
|
+
"""Print statement: out(expr, ...)"""
|
|
53
|
+
args: list["Expr"]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class CondStmt(Stmt):
|
|
58
|
+
"""Conditional: ?s cond ?o ... n or ?s cond ?x ... n"""
|
|
59
|
+
condition: "Expr"
|
|
60
|
+
expect_true: bool
|
|
61
|
+
body: list[Stmt]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class ForStmt(Stmt):
|
|
66
|
+
"""For loop: f (S: x = 1, t: x = 5); x ++ 1"""
|
|
67
|
+
init: VarSetStmt
|
|
68
|
+
stop_cond: "Expr"
|
|
69
|
+
body_stmt: Stmt
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class WhileStmt(Stmt):
|
|
74
|
+
"""While loop: sw t: cond n ... n or sw in n ... n"""
|
|
75
|
+
condition: "Expr | None"
|
|
76
|
+
body: list[Stmt]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class FuncDefStmt(Stmt):
|
|
81
|
+
"""Function definition: q name(params) n ... n or q name n ... n"""
|
|
82
|
+
name: str
|
|
83
|
+
params: list[str]
|
|
84
|
+
body: list[Stmt]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class BackStmt(Stmt):
|
|
89
|
+
"""Return statement: back [expr]"""
|
|
90
|
+
value: "Expr | None"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class TryStmt(Stmt):
|
|
95
|
+
"""Error handling: ?t ... ?f [err_var] ... n"""
|
|
96
|
+
try_body: list[Stmt]
|
|
97
|
+
err_var: str | None
|
|
98
|
+
fail_body: list[Stmt]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass
|
|
102
|
+
class ImportStmt(Stmt):
|
|
103
|
+
"""Module import: @S:("module_or_file")"""
|
|
104
|
+
target: "Expr"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass
|
|
108
|
+
class ClassDefStmt(Stmt):
|
|
109
|
+
"""Class definition: c Name n ... n"""
|
|
110
|
+
name: str
|
|
111
|
+
methods: list[FuncDefStmt]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass
|
|
115
|
+
class DelStmt(Stmt):
|
|
116
|
+
"""Memory/variable deletion: del(S: name) n"""
|
|
117
|
+
name: str
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass
|
|
121
|
+
class StopStmt(Stmt):
|
|
122
|
+
"""Break out of a loop: stop"""
|
|
123
|
+
pass
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class Expr(Node):
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass
|
|
131
|
+
class LiteralExpr(Expr):
|
|
132
|
+
value: Any
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass
|
|
136
|
+
class VarExpr(Expr):
|
|
137
|
+
name: str
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass
|
|
141
|
+
class ArrayExpr(Expr):
|
|
142
|
+
elements: list[Expr]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass
|
|
146
|
+
class ObjectExpr(Expr):
|
|
147
|
+
entries: list[tuple[Expr, Expr]]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass
|
|
151
|
+
class MemberExpr(Expr):
|
|
152
|
+
target: Expr
|
|
153
|
+
field: str
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass
|
|
157
|
+
class CallExpr(Expr):
|
|
158
|
+
name: str
|
|
159
|
+
args: list[Expr]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass
|
|
163
|
+
class MethodCallExpr(Expr):
|
|
164
|
+
target: Expr
|
|
165
|
+
method: str
|
|
166
|
+
args: list[Expr]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass
|
|
170
|
+
class UnaryExpr(Expr):
|
|
171
|
+
op: str
|
|
172
|
+
operand: Expr
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@dataclass
|
|
176
|
+
class BinaryExpr(Expr):
|
|
177
|
+
left: Expr
|
|
178
|
+
op: str
|
|
179
|
+
right: Expr
|
sylix-1.0.0/sylix/cli.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""CLI and REPL for Sylix 0.8."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import pickle
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from .ast_nodes import Program
|
|
9
|
+
from .errors import SylixError
|
|
10
|
+
from .interpreter import Interpreter
|
|
11
|
+
from .lexer import Lexer
|
|
12
|
+
from .optimizer import optimize
|
|
13
|
+
from .parser import Parser
|
|
14
|
+
|
|
15
|
+
SYLC_MAGIC = b"SYLC\x08"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def compile_source(source: str) -> Program:
|
|
19
|
+
tokens = Lexer(source).tokenize()
|
|
20
|
+
ast = Parser(tokens).parse()
|
|
21
|
+
return optimize(ast)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def save_compiled(program: Program, path: Path) -> None:
|
|
25
|
+
with open(path, "wb") as f:
|
|
26
|
+
f.write(SYLC_MAGIC)
|
|
27
|
+
pickle.dump(program, f, protocol=pickle.HIGHEST_PROTOCOL)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load_compiled(path: Path) -> Program:
|
|
31
|
+
with open(path, "rb") as f:
|
|
32
|
+
header = f.read(len(SYLC_MAGIC))
|
|
33
|
+
if header != SYLC_MAGIC:
|
|
34
|
+
raise ValueError(f"Invalid .sylc file: {path}")
|
|
35
|
+
return pickle.load(f)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def run_source(
|
|
39
|
+
source: str, interp: Interpreter | None = None, base_dir: Path | None = None
|
|
40
|
+
) -> Interpreter:
|
|
41
|
+
interp = interp or Interpreter(base_dir=base_dir)
|
|
42
|
+
ast = compile_source(source)
|
|
43
|
+
interp.run(ast)
|
|
44
|
+
return interp
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def cmd_run(path_str: str) -> int:
|
|
48
|
+
path = Path(path_str)
|
|
49
|
+
if not path.exists():
|
|
50
|
+
print(f"File not found: {path}", file=sys.stderr)
|
|
51
|
+
return 1
|
|
52
|
+
try:
|
|
53
|
+
if path.suffix == ".sylc":
|
|
54
|
+
ast = load_compiled(path)
|
|
55
|
+
Interpreter(base_dir=path.resolve().parent).run(ast)
|
|
56
|
+
else:
|
|
57
|
+
run_source(path.read_text(encoding="utf-8"), base_dir=path.resolve().parent)
|
|
58
|
+
return 0
|
|
59
|
+
except (SylixError, ValueError) as err:
|
|
60
|
+
print(err, file=sys.stderr)
|
|
61
|
+
return 1
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def cmd_compile(path_str: str, out_str: str | None) -> int:
|
|
65
|
+
path = Path(path_str)
|
|
66
|
+
if not path.exists():
|
|
67
|
+
print(f"File not found: {path}", file=sys.stderr)
|
|
68
|
+
return 1
|
|
69
|
+
out_path = Path(out_str) if out_str else path.with_suffix(".sylc")
|
|
70
|
+
try:
|
|
71
|
+
ast = compile_source(path.read_text(encoding="utf-8"))
|
|
72
|
+
save_compiled(ast, out_path)
|
|
73
|
+
print(f"Compiled {path} -> {out_path}")
|
|
74
|
+
return 0
|
|
75
|
+
except SylixError as err:
|
|
76
|
+
print(err, file=sys.stderr)
|
|
77
|
+
return 1
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def cmd_repl() -> int:
|
|
81
|
+
print("Sylix 1.0.0 REPL — type :quit to exit.")
|
|
82
|
+
interp = Interpreter()
|
|
83
|
+
while True:
|
|
84
|
+
try:
|
|
85
|
+
line = input("sylix> ")
|
|
86
|
+
except (EOFError, KeyboardInterrupt):
|
|
87
|
+
print()
|
|
88
|
+
break
|
|
89
|
+
stripped = line.strip()
|
|
90
|
+
if not stripped:
|
|
91
|
+
continue
|
|
92
|
+
if stripped in (":quit", ":exit"):
|
|
93
|
+
break
|
|
94
|
+
try:
|
|
95
|
+
run_source(line, interp=interp)
|
|
96
|
+
except SylixError as err:
|
|
97
|
+
print(err, file=sys.stderr)
|
|
98
|
+
return 0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def main(argv: list[str] | None = None) -> int:
|
|
102
|
+
parser = argparse.ArgumentParser(prog="sylix", description="Sylix CLI")
|
|
103
|
+
sub = parser.add_subparsers(dest="command")
|
|
104
|
+
|
|
105
|
+
p_run = sub.add_parser("run", help="Run a .syl or .sylc file")
|
|
106
|
+
p_run.add_argument("file", help="Path to .syl or .sylc file")
|
|
107
|
+
|
|
108
|
+
p_comp = sub.add_parser("compile", help="Compile a .syl file to .sylc")
|
|
109
|
+
p_comp.add_argument("file", help="Path to .syl file")
|
|
110
|
+
p_comp.add_argument("-o", "--output", help="Output .sylc path")
|
|
111
|
+
|
|
112
|
+
sub.add_parser("repl", help="Start interactive REPL")
|
|
113
|
+
|
|
114
|
+
args = parser.parse_args(argv)
|
|
115
|
+
if args.command == "run":
|
|
116
|
+
return cmd_run(args.file)
|
|
117
|
+
if args.command == "compile":
|
|
118
|
+
return cmd_compile(args.file, args.output)
|
|
119
|
+
return cmd_repl()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
if __name__ == "__main__":
|
|
123
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Error types for Sylix."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class SourceLocation:
|
|
8
|
+
line: int
|
|
9
|
+
column: int
|
|
10
|
+
|
|
11
|
+
def __str__(self) -> str:
|
|
12
|
+
return f"line {self.line}, col {self.column}"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SylixError(Exception):
|
|
16
|
+
def __init__(self, message: str, location: SourceLocation | None = None, kind: str = "Error"):
|
|
17
|
+
self.message = message
|
|
18
|
+
self.location = location
|
|
19
|
+
self.kind = kind
|
|
20
|
+
loc_str = f" ({location})" if location else ""
|
|
21
|
+
super().__init__(f"[Sylix {kind}]{loc_str}: {message}")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LexerError(SylixError):
|
|
25
|
+
def __init__(self, message: str, location: SourceLocation | None = None):
|
|
26
|
+
super().__init__(message, location, kind="SyntaxError")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ParseError(SylixError):
|
|
30
|
+
def __init__(self, message: str, location: SourceLocation | None = None):
|
|
31
|
+
super().__init__(message, location, kind="ParseError")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SylixRuntimeError(SylixError):
|
|
35
|
+
def __init__(self, message: str, location: SourceLocation | None = None):
|
|
36
|
+
super().__init__(message, location, kind="RuntimeError")
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Built-in 2D game engine (@S:("game")) for Sylix using standard tkinter."""
|
|
2
|
+
|
|
3
|
+
import tkinter as tk
|
|
4
|
+
from typing import Any, Callable
|
|
5
|
+
|
|
6
|
+
from .errors import SylixRuntimeError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class _GameWindow:
|
|
10
|
+
def __init__(self) -> None:
|
|
11
|
+
self.root: tk.Tk | None = None
|
|
12
|
+
self.canvas: tk.Canvas | None = None
|
|
13
|
+
self.alive: bool = False
|
|
14
|
+
self.keys: set[str] = set()
|
|
15
|
+
self.width: int = 640
|
|
16
|
+
self.height: int = 480
|
|
17
|
+
|
|
18
|
+
def open(self, title: Any, width: Any, height: Any) -> bool:
|
|
19
|
+
self.width = int(width)
|
|
20
|
+
self.height = int(height)
|
|
21
|
+
self.root = tk.Tk()
|
|
22
|
+
self.root.title(str(title))
|
|
23
|
+
self.root.resizable(False, False)
|
|
24
|
+
self.canvas = tk.Canvas(self.root, width=self.width, height=self.height, highlightthickness=0)
|
|
25
|
+
self.canvas.pack()
|
|
26
|
+
self.alive = True
|
|
27
|
+
self.keys.clear()
|
|
28
|
+
|
|
29
|
+
def on_close() -> None:
|
|
30
|
+
self.alive = False
|
|
31
|
+
if self.root is not None:
|
|
32
|
+
self.root.destroy()
|
|
33
|
+
self.root = None
|
|
34
|
+
self.canvas = None
|
|
35
|
+
|
|
36
|
+
def on_key_press(event: tk.Event) -> None: # type: ignore[type-arg]
|
|
37
|
+
if event.keysym:
|
|
38
|
+
self.keys.add(event.keysym)
|
|
39
|
+
|
|
40
|
+
def on_key_release(event: tk.Event) -> None: # type: ignore[type-arg]
|
|
41
|
+
if event.keysym:
|
|
42
|
+
self.keys.discard(event.keysym)
|
|
43
|
+
|
|
44
|
+
self.root.protocol("WM_DELETE_WINDOW", on_close)
|
|
45
|
+
self.root.bind("<KeyPress>", on_key_press)
|
|
46
|
+
self.root.bind("<KeyRelease>", on_key_release)
|
|
47
|
+
self.root.focus_force()
|
|
48
|
+
return True
|
|
49
|
+
|
|
50
|
+
def ensure_open(self) -> tk.Canvas:
|
|
51
|
+
if not self.alive or self.canvas is None or self.root is None:
|
|
52
|
+
raise SylixRuntimeError("Game window is not open (call win_open() first)")
|
|
53
|
+
return self.canvas
|
|
54
|
+
|
|
55
|
+
def clear(self, color: Any = "black") -> None:
|
|
56
|
+
canvas = self.ensure_open()
|
|
57
|
+
canvas.delete("all")
|
|
58
|
+
canvas.configure(bg=str(color))
|
|
59
|
+
|
|
60
|
+
def draw_rect(self, x: Any, y: Any, w: Any, h: Any, color: Any = "white") -> None:
|
|
61
|
+
canvas = self.ensure_open()
|
|
62
|
+
x0, y0 = float(x), float(y)
|
|
63
|
+
canvas.create_rectangle(x0, y0, x0 + float(w), y0 + float(h), fill=str(color), outline="")
|
|
64
|
+
|
|
65
|
+
def draw_circle(self, x: Any, y: Any, r: Any, color: Any = "white") -> None:
|
|
66
|
+
canvas = self.ensure_open()
|
|
67
|
+
cx, cy, rad = float(x), float(y), float(r)
|
|
68
|
+
canvas.create_oval(cx - rad, cy - rad, cx + rad, cy + rad, fill=str(color), outline="")
|
|
69
|
+
|
|
70
|
+
def draw_text(self, x: Any, y: Any, text: Any, color: Any = "white", size: Any = 16) -> None:
|
|
71
|
+
canvas = self.ensure_open()
|
|
72
|
+
canvas.create_text(
|
|
73
|
+
float(x),
|
|
74
|
+
float(y),
|
|
75
|
+
text=str(text),
|
|
76
|
+
fill=str(color),
|
|
77
|
+
font=("Consolas", int(size), "bold"),
|
|
78
|
+
anchor="nw",
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
def key_down(self, key: Any) -> bool:
|
|
82
|
+
return str(key) in self.keys
|
|
83
|
+
|
|
84
|
+
def update(self) -> None:
|
|
85
|
+
if not self.alive or self.root is None:
|
|
86
|
+
return
|
|
87
|
+
try:
|
|
88
|
+
self.root.update_idletasks()
|
|
89
|
+
self.root.update()
|
|
90
|
+
except tk.TclError:
|
|
91
|
+
self.alive = False
|
|
92
|
+
|
|
93
|
+
def close(self) -> None:
|
|
94
|
+
if self.root is not None:
|
|
95
|
+
try:
|
|
96
|
+
self.root.destroy()
|
|
97
|
+
except tk.TclError:
|
|
98
|
+
pass
|
|
99
|
+
self.alive = False
|
|
100
|
+
self.root = None
|
|
101
|
+
self.canvas = None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def get_game_builtins() -> dict[str, Callable[..., Any]]:
|
|
105
|
+
win = _GameWindow()
|
|
106
|
+
return {
|
|
107
|
+
"win_open": win.open,
|
|
108
|
+
"win_alive": lambda: win.alive,
|
|
109
|
+
"win_clear": win.clear,
|
|
110
|
+
"draw_rect": win.draw_rect,
|
|
111
|
+
"draw_circle": win.draw_circle,
|
|
112
|
+
"draw_text": win.draw_text,
|
|
113
|
+
"key_down": win.key_down,
|
|
114
|
+
"win_update": win.update,
|
|
115
|
+
"win_close": win.close,
|
|
116
|
+
}
|