sipl-kit 0.4.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.
- sipl/__init__.py +7 -0
- sipl/__main__.py +5 -0
- sipl/ast.py +270 -0
- sipl/cli.py +276 -0
- sipl/diagnostics.py +64 -0
- sipl/grammar/__init__.py +0 -0
- sipl/grammar/sipl.lark +77 -0
- sipl/interpreter/__init__.py +27 -0
- sipl/interpreter/events.py +43 -0
- sipl/interpreter/runtime.py +201 -0
- sipl/parser.py +203 -0
- sipl/printer.py +65 -0
- sipl/semantics/__init__.py +35 -0
- sipl/semantics/terms.py +258 -0
- sipl_kit-0.4.0.dist-info/METADATA +184 -0
- sipl_kit-0.4.0.dist-info/RECORD +19 -0
- sipl_kit-0.4.0.dist-info/WHEEL +4 -0
- sipl_kit-0.4.0.dist-info/entry_points.txt +2 -0
- sipl_kit-0.4.0.dist-info/licenses/LICENSE +21 -0
sipl/__init__.py
ADDED
sipl/__main__.py
ADDED
sipl/ast.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""Typed AST of SIPL. Every node keeps its SourceSpan."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class SourceSpan:
|
|
12
|
+
# lines and columns are 1-based, end_column points past the last char
|
|
13
|
+
line: int
|
|
14
|
+
column: int
|
|
15
|
+
end_line: int
|
|
16
|
+
end_column: int
|
|
17
|
+
start: int
|
|
18
|
+
end: int
|
|
19
|
+
|
|
20
|
+
def to_dict(self) -> dict[str, int]:
|
|
21
|
+
return {
|
|
22
|
+
"line": self.line,
|
|
23
|
+
"column": self.column,
|
|
24
|
+
"end_line": self.end_line,
|
|
25
|
+
"end_column": self.end_column,
|
|
26
|
+
"start": self.start,
|
|
27
|
+
"end": self.end,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
def contains_line(self, line: int) -> bool:
|
|
31
|
+
return self.line <= line <= self.end_line
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
UNKNOWN_SPAN = SourceSpan(0, 0, 0, 0, 0, 0)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class Node:
|
|
39
|
+
span: SourceSpan = field(compare=False, repr=False, kw_only=True)
|
|
40
|
+
|
|
41
|
+
def children(self) -> Iterator[Node]:
|
|
42
|
+
return iter(())
|
|
43
|
+
|
|
44
|
+
def to_dict(self) -> dict[str, Any]:
|
|
45
|
+
raise NotImplementedError
|
|
46
|
+
|
|
47
|
+
def walk(self) -> Iterator[Node]:
|
|
48
|
+
yield self
|
|
49
|
+
for child in self.children():
|
|
50
|
+
yield from child.walk()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# arithmetic expressions (Aexp)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Num(Node):
|
|
58
|
+
value: int
|
|
59
|
+
|
|
60
|
+
def to_dict(self) -> dict[str, Any]:
|
|
61
|
+
return {"type": "Num", "value": self.value, "span": self.span.to_dict()}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Var(Node):
|
|
66
|
+
name: str
|
|
67
|
+
|
|
68
|
+
def to_dict(self) -> dict[str, Any]:
|
|
69
|
+
return {"type": "Var", "name": self.name, "span": self.span.to_dict()}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
ARITH_OPS = ("+", "-", "*", "div", "mod")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class BinOp(Node):
|
|
77
|
+
op: str
|
|
78
|
+
left: Aexp
|
|
79
|
+
right: Aexp
|
|
80
|
+
|
|
81
|
+
def children(self) -> Iterator[Node]:
|
|
82
|
+
yield self.left
|
|
83
|
+
yield self.right
|
|
84
|
+
|
|
85
|
+
def to_dict(self) -> dict[str, Any]:
|
|
86
|
+
return {
|
|
87
|
+
"type": "BinOp",
|
|
88
|
+
"op": self.op,
|
|
89
|
+
"left": self.left.to_dict(),
|
|
90
|
+
"right": self.right.to_dict(),
|
|
91
|
+
"span": self.span.to_dict(),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
Aexp = Num | Var | BinOp
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# conditions (Bexp)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class Compare(Node):
|
|
103
|
+
op: str # "=" or ">"
|
|
104
|
+
left: Aexp
|
|
105
|
+
right: Aexp
|
|
106
|
+
|
|
107
|
+
def children(self) -> Iterator[Node]:
|
|
108
|
+
yield self.left
|
|
109
|
+
yield self.right
|
|
110
|
+
|
|
111
|
+
def to_dict(self) -> dict[str, Any]:
|
|
112
|
+
return {
|
|
113
|
+
"type": "Compare",
|
|
114
|
+
"op": self.op,
|
|
115
|
+
"left": self.left.to_dict(),
|
|
116
|
+
"right": self.right.to_dict(),
|
|
117
|
+
"span": self.span.to_dict(),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass(frozen=True)
|
|
122
|
+
class Or(Node):
|
|
123
|
+
left: Bexp
|
|
124
|
+
right: Bexp
|
|
125
|
+
|
|
126
|
+
def children(self) -> Iterator[Node]:
|
|
127
|
+
yield self.left
|
|
128
|
+
yield self.right
|
|
129
|
+
|
|
130
|
+
def to_dict(self) -> dict[str, Any]:
|
|
131
|
+
return {
|
|
132
|
+
"type": "Or",
|
|
133
|
+
"left": self.left.to_dict(),
|
|
134
|
+
"right": self.right.to_dict(),
|
|
135
|
+
"span": self.span.to_dict(),
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True)
|
|
140
|
+
class Not(Node):
|
|
141
|
+
operand: Bexp
|
|
142
|
+
|
|
143
|
+
def children(self) -> Iterator[Node]:
|
|
144
|
+
yield self.operand
|
|
145
|
+
|
|
146
|
+
def to_dict(self) -> dict[str, Any]:
|
|
147
|
+
return {"type": "Not", "operand": self.operand.to_dict(), "span": self.span.to_dict()}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
Bexp = Compare | Or | Not
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# statements (Stm)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass(frozen=True)
|
|
157
|
+
class Assign(Node):
|
|
158
|
+
target: str
|
|
159
|
+
value: Aexp
|
|
160
|
+
target_span: SourceSpan = field(compare=False, repr=False, kw_only=True)
|
|
161
|
+
|
|
162
|
+
def children(self) -> Iterator[Node]:
|
|
163
|
+
yield self.value
|
|
164
|
+
|
|
165
|
+
def to_dict(self) -> dict[str, Any]:
|
|
166
|
+
return {
|
|
167
|
+
"type": "Assign",
|
|
168
|
+
"target": self.target,
|
|
169
|
+
"value": self.value.to_dict(),
|
|
170
|
+
"span": self.span.to_dict(),
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@dataclass(frozen=True)
|
|
175
|
+
class Seq(Node):
|
|
176
|
+
first: Stm
|
|
177
|
+
second: Stm
|
|
178
|
+
|
|
179
|
+
def children(self) -> Iterator[Node]:
|
|
180
|
+
yield self.first
|
|
181
|
+
yield self.second
|
|
182
|
+
|
|
183
|
+
def to_dict(self) -> dict[str, Any]:
|
|
184
|
+
return {
|
|
185
|
+
"type": "Seq",
|
|
186
|
+
"first": self.first.to_dict(),
|
|
187
|
+
"second": self.second.to_dict(),
|
|
188
|
+
"span": self.span.to_dict(),
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@dataclass(frozen=True)
|
|
193
|
+
class If(Node):
|
|
194
|
+
cond: Bexp
|
|
195
|
+
then_branch: Stm
|
|
196
|
+
else_branch: Stm
|
|
197
|
+
|
|
198
|
+
def children(self) -> Iterator[Node]:
|
|
199
|
+
yield self.cond
|
|
200
|
+
yield self.then_branch
|
|
201
|
+
yield self.else_branch
|
|
202
|
+
|
|
203
|
+
def to_dict(self) -> dict[str, Any]:
|
|
204
|
+
return {
|
|
205
|
+
"type": "If",
|
|
206
|
+
"cond": self.cond.to_dict(),
|
|
207
|
+
"then": self.then_branch.to_dict(),
|
|
208
|
+
"else": self.else_branch.to_dict(),
|
|
209
|
+
"span": self.span.to_dict(),
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@dataclass(frozen=True)
|
|
214
|
+
class While(Node):
|
|
215
|
+
cond: Bexp
|
|
216
|
+
body: Stm
|
|
217
|
+
|
|
218
|
+
def children(self) -> Iterator[Node]:
|
|
219
|
+
yield self.cond
|
|
220
|
+
yield self.body
|
|
221
|
+
|
|
222
|
+
def to_dict(self) -> dict[str, Any]:
|
|
223
|
+
return {
|
|
224
|
+
"type": "While",
|
|
225
|
+
"cond": self.cond.to_dict(),
|
|
226
|
+
"body": self.body.to_dict(),
|
|
227
|
+
"span": self.span.to_dict(),
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclass(frozen=True)
|
|
232
|
+
class Block(Node):
|
|
233
|
+
body: Stm
|
|
234
|
+
|
|
235
|
+
def children(self) -> Iterator[Node]:
|
|
236
|
+
yield self.body
|
|
237
|
+
|
|
238
|
+
def to_dict(self) -> dict[str, Any]:
|
|
239
|
+
return {"type": "Block", "body": self.body.to_dict(), "span": self.span.to_dict()}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@dataclass(frozen=True)
|
|
243
|
+
class Skip(Node):
|
|
244
|
+
def to_dict(self) -> dict[str, Any]:
|
|
245
|
+
return {"type": "Skip", "span": self.span.to_dict()}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
Stm = Assign | Seq | If | While | Block | Skip
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
@dataclass(frozen=True)
|
|
252
|
+
class Program(Node):
|
|
253
|
+
body: Stm
|
|
254
|
+
|
|
255
|
+
def children(self) -> Iterator[Node]:
|
|
256
|
+
yield self.body
|
|
257
|
+
|
|
258
|
+
def to_dict(self) -> dict[str, Any]:
|
|
259
|
+
return {"type": "Program", "body": self.body.to_dict(), "span": self.span.to_dict()}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def variables(node: Node) -> list[str]:
|
|
263
|
+
"""Variables in order of first occurrence."""
|
|
264
|
+
seen: dict[str, None] = {}
|
|
265
|
+
for n in node.walk():
|
|
266
|
+
if isinstance(n, Assign):
|
|
267
|
+
seen.setdefault(n.target)
|
|
268
|
+
elif isinstance(n, Var):
|
|
269
|
+
seen.setdefault(n.name)
|
|
270
|
+
return list(seen)
|
sipl/cli.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""Command line interface: sipl parse | check | run | trace | term."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Any, NoReturn, TextIO
|
|
9
|
+
|
|
10
|
+
from . import __version__, ast
|
|
11
|
+
from .diagnostics import SiplError, SiplSyntaxError
|
|
12
|
+
from .interpreter import DEFAULT_MAX_STEPS, Event, EventKind, ExecutionResult, format_state, run, trace
|
|
13
|
+
from .parser import parse
|
|
14
|
+
from .semantics import derive
|
|
15
|
+
|
|
16
|
+
SCHEMA_VERSION = 1
|
|
17
|
+
|
|
18
|
+
EXIT_OK = 0
|
|
19
|
+
EXIT_SYNTAX = 1
|
|
20
|
+
EXIT_RUNTIME = 2
|
|
21
|
+
EXIT_STEP_LIMIT = 3
|
|
22
|
+
EXIT_USAGE = 4
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class UsageError(Exception):
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _ArgParser(argparse.ArgumentParser):
|
|
30
|
+
def error(self, message: str) -> NoReturn:
|
|
31
|
+
self.print_usage(sys.stderr)
|
|
32
|
+
self.exit(EXIT_USAGE, f"{self.prog}: error: {message}\n")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _read_source(path: str) -> str:
|
|
36
|
+
if path == "-":
|
|
37
|
+
return sys.stdin.read()
|
|
38
|
+
try:
|
|
39
|
+
with open(path, encoding="utf-8") as f:
|
|
40
|
+
return f.read()
|
|
41
|
+
except OSError as e:
|
|
42
|
+
raise UsageError(f"cannot read {path}: {e.strerror}") from None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def parse_state(items: list[str]) -> dict[str, int]:
|
|
46
|
+
"""Parse ["X=5", "Y=2,Z=-1"] into a state."""
|
|
47
|
+
state: dict[str, int] = {}
|
|
48
|
+
for item in items:
|
|
49
|
+
for part in item.split(","):
|
|
50
|
+
part = part.strip()
|
|
51
|
+
if not part:
|
|
52
|
+
continue
|
|
53
|
+
name, sep, value = part.partition("=")
|
|
54
|
+
name = name.strip()
|
|
55
|
+
if not sep or not name.isidentifier():
|
|
56
|
+
raise UsageError(f"bad state item {part!r}, expected NAME=INT")
|
|
57
|
+
try:
|
|
58
|
+
state[name] = int(value)
|
|
59
|
+
except ValueError:
|
|
60
|
+
raise UsageError(f"bad value for {name}: {value.strip()!r} is not an integer") from None
|
|
61
|
+
return state
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def ast_to_text(node: ast.Node, indent: int = 0) -> str:
|
|
65
|
+
label = type(node).__name__
|
|
66
|
+
if isinstance(node, ast.Num):
|
|
67
|
+
label += f" {node.value}"
|
|
68
|
+
elif isinstance(node, ast.Var):
|
|
69
|
+
label += f" {node.name}"
|
|
70
|
+
elif isinstance(node, (ast.BinOp, ast.Compare)):
|
|
71
|
+
label += f" {node.op}"
|
|
72
|
+
elif isinstance(node, ast.Assign):
|
|
73
|
+
label += f" {node.target}"
|
|
74
|
+
pos = f" @{node.span.line}:{node.span.column}-{node.span.end_line}:{node.span.end_column}"
|
|
75
|
+
lines = [" " * indent + label + pos]
|
|
76
|
+
for child in node.children():
|
|
77
|
+
lines.append(ast_to_text(child, indent + 1))
|
|
78
|
+
return "\n".join(lines)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def format_event(e: Event) -> str:
|
|
82
|
+
where = f"{e.span.line}:{e.span.column}" if e.span.line else "-"
|
|
83
|
+
head = f"#{e.step:<4} {where:<7} {e.kind.value:<17}"
|
|
84
|
+
if e.kind == EventKind.ASSIGN:
|
|
85
|
+
old = "⊥" if e.data.get("old") is None else e.data["old"]
|
|
86
|
+
return f"{head} {e.data['variable']}: {old} -> {e.data['new']}"
|
|
87
|
+
if e.kind == EventKind.CONDITION:
|
|
88
|
+
extra = f" (iteration {e.data['iteration']})" if "iteration" in e.data else ""
|
|
89
|
+
return f"{head} {e.data['construct']} -> {str(e.data['value']).lower()}{extra}"
|
|
90
|
+
if e.kind in (EventKind.FINISH, EventKind.START):
|
|
91
|
+
return f"{head} {format_state(e.state)}"
|
|
92
|
+
if e.kind == EventKind.ERROR:
|
|
93
|
+
return f"{head} {e.data['error']['message']}"
|
|
94
|
+
return f"{head} {e.node}"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Cli:
|
|
98
|
+
def __init__(self, out: TextIO, err: TextIO):
|
|
99
|
+
self.out = out
|
|
100
|
+
self.err = err
|
|
101
|
+
|
|
102
|
+
def emit_json(self, payload: dict[str, Any]) -> None:
|
|
103
|
+
payload = {"schema_version": SCHEMA_VERSION, **payload}
|
|
104
|
+
json.dump(payload, self.out, ensure_ascii=False, indent=2)
|
|
105
|
+
self.out.write("\n")
|
|
106
|
+
|
|
107
|
+
def report_error(
|
|
108
|
+
self, args: argparse.Namespace, error: SiplError, extra: dict[str, Any] | None = None
|
|
109
|
+
) -> None:
|
|
110
|
+
if args.json:
|
|
111
|
+
self.emit_json(
|
|
112
|
+
{
|
|
113
|
+
"command": args.command,
|
|
114
|
+
"file": args.file,
|
|
115
|
+
"ok": False,
|
|
116
|
+
"diagnostics": [error.diagnostic.to_dict()],
|
|
117
|
+
**(extra or {}),
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
else:
|
|
121
|
+
self.err.write(error.diagnostic.format(args.file) + "\n")
|
|
122
|
+
|
|
123
|
+
def load(self, args: argparse.Namespace) -> ast.Program | None:
|
|
124
|
+
source = _read_source(args.file)
|
|
125
|
+
try:
|
|
126
|
+
return parse(source)
|
|
127
|
+
except SiplSyntaxError as e:
|
|
128
|
+
self.report_error(args, e)
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
def cmd_parse(self, args: argparse.Namespace) -> int:
|
|
132
|
+
program = self.load(args)
|
|
133
|
+
if program is None:
|
|
134
|
+
return EXIT_SYNTAX
|
|
135
|
+
if args.json:
|
|
136
|
+
self.emit_json(
|
|
137
|
+
{
|
|
138
|
+
"command": "parse",
|
|
139
|
+
"file": args.file,
|
|
140
|
+
"ok": True,
|
|
141
|
+
"diagnostics": [],
|
|
142
|
+
"ast": program.to_dict(),
|
|
143
|
+
}
|
|
144
|
+
)
|
|
145
|
+
else:
|
|
146
|
+
self.out.write(ast_to_text(program) + "\n")
|
|
147
|
+
return EXIT_OK
|
|
148
|
+
|
|
149
|
+
def cmd_check(self, args: argparse.Namespace) -> int:
|
|
150
|
+
program = self.load(args)
|
|
151
|
+
if program is None:
|
|
152
|
+
return EXIT_SYNTAX
|
|
153
|
+
if args.json:
|
|
154
|
+
self.emit_json(
|
|
155
|
+
{
|
|
156
|
+
"command": "check",
|
|
157
|
+
"file": args.file,
|
|
158
|
+
"ok": True,
|
|
159
|
+
"diagnostics": [],
|
|
160
|
+
"variables": ast.variables(program),
|
|
161
|
+
}
|
|
162
|
+
)
|
|
163
|
+
else:
|
|
164
|
+
self.out.write(f"{args.file}: OK\n")
|
|
165
|
+
return EXIT_OK
|
|
166
|
+
|
|
167
|
+
def _execute(self, args: argparse.Namespace, with_trace: bool) -> int:
|
|
168
|
+
state = parse_state(args.set or [])
|
|
169
|
+
program = self.load(args)
|
|
170
|
+
if program is None:
|
|
171
|
+
return EXIT_SYNTAX
|
|
172
|
+
result = trace(program, state, args.max_steps) if with_trace else run(program, state, args.max_steps)
|
|
173
|
+
code = {"ok": EXIT_OK, "error": EXIT_RUNTIME, "step_limit": EXIT_STEP_LIMIT}[result.status]
|
|
174
|
+
if args.json:
|
|
175
|
+
payload = {
|
|
176
|
+
"command": args.command,
|
|
177
|
+
"file": args.file,
|
|
178
|
+
"ok": result.ok,
|
|
179
|
+
"diagnostics": [result.error.diagnostic.to_dict()] if result.error else [],
|
|
180
|
+
}
|
|
181
|
+
payload.update(result.to_dict(with_trace=with_trace))
|
|
182
|
+
payload.pop("error", None)
|
|
183
|
+
self.emit_json(payload)
|
|
184
|
+
return code
|
|
185
|
+
if with_trace:
|
|
186
|
+
for e in result.events:
|
|
187
|
+
self.out.write(format_event(e) + "\n")
|
|
188
|
+
self._print_result(args, result)
|
|
189
|
+
return code
|
|
190
|
+
|
|
191
|
+
def _print_result(self, args: argparse.Namespace, result: ExecutionResult) -> None:
|
|
192
|
+
if result.error is not None:
|
|
193
|
+
self.err.write(result.error.diagnostic.format(args.file) + "\n")
|
|
194
|
+
self.err.write(f"state at failure: {format_state(result.state)}\n")
|
|
195
|
+
return
|
|
196
|
+
self.out.write(f"{format_state(result.state)}\n")
|
|
197
|
+
if args.verbose:
|
|
198
|
+
self.out.write(f"steps: {result.steps}\n")
|
|
199
|
+
|
|
200
|
+
def cmd_run(self, args: argparse.Namespace) -> int:
|
|
201
|
+
return self._execute(args, with_trace=False)
|
|
202
|
+
|
|
203
|
+
def cmd_trace(self, args: argparse.Namespace) -> int:
|
|
204
|
+
return self._execute(args, with_trace=True)
|
|
205
|
+
|
|
206
|
+
def cmd_term(self, args: argparse.Namespace) -> int:
|
|
207
|
+
program = self.load(args)
|
|
208
|
+
if program is None:
|
|
209
|
+
return EXIT_SYNTAX
|
|
210
|
+
d = derive(program)
|
|
211
|
+
if args.json:
|
|
212
|
+
self.emit_json(
|
|
213
|
+
{"command": "term", "file": args.file, "ok": True, "diagnostics": [], **d.to_dict(args.ascii)}
|
|
214
|
+
)
|
|
215
|
+
return EXIT_OK
|
|
216
|
+
if args.steps:
|
|
217
|
+
for i, step in enumerate(d.steps, 1):
|
|
218
|
+
self.out.write(f"{i:>3}. {step}\n")
|
|
219
|
+
self.out.write("\n")
|
|
220
|
+
self.out.write(d.term.render(args.ascii) + "\n")
|
|
221
|
+
return EXIT_OK
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
225
|
+
p = _ArgParser(prog="sipl", description="SIPL Language Toolkit")
|
|
226
|
+
p.add_argument("--version", action="version", version=f"sipl {__version__}")
|
|
227
|
+
sub = p.add_subparsers(dest="command", required=True, parser_class=_ArgParser)
|
|
228
|
+
|
|
229
|
+
def add(name: str, help_text: str) -> argparse.ArgumentParser:
|
|
230
|
+
sp = sub.add_parser(name, help=help_text, description=help_text)
|
|
231
|
+
sp.add_argument("file", help="path to a .sipl file, '-' for stdin")
|
|
232
|
+
sp.add_argument("--json", action="store_true", help="machine readable output")
|
|
233
|
+
return sp
|
|
234
|
+
|
|
235
|
+
add("parse", "parse a program and print its AST")
|
|
236
|
+
add("check", "check syntax")
|
|
237
|
+
for name, text in (("run", "run a program"), ("trace", "run a program and print the event trace")):
|
|
238
|
+
sp = add(name, text)
|
|
239
|
+
sp.add_argument(
|
|
240
|
+
"-s",
|
|
241
|
+
"--set",
|
|
242
|
+
action="append",
|
|
243
|
+
metavar="X=N",
|
|
244
|
+
help="initial value of a variable, can be repeated or comma separated",
|
|
245
|
+
)
|
|
246
|
+
sp.add_argument(
|
|
247
|
+
"--max-steps",
|
|
248
|
+
type=int,
|
|
249
|
+
default=DEFAULT_MAX_STEPS,
|
|
250
|
+
help=f"step limit (default {DEFAULT_MAX_STEPS})",
|
|
251
|
+
)
|
|
252
|
+
sp.add_argument("-v", "--verbose", action="store_true", help="print number of steps")
|
|
253
|
+
sp = add("term", "build the semantic term of a program")
|
|
254
|
+
sp.add_argument("--steps", action="store_true", help="print applied rules")
|
|
255
|
+
sp.add_argument("--ascii", action="store_true", help="ASCII notation (X=> instead of X⇒)")
|
|
256
|
+
return p
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def main(argv: list[str] | None = None, out: TextIO | None = None, err: TextIO | None = None) -> int:
|
|
260
|
+
out = out or sys.stdout
|
|
261
|
+
err = err or sys.stderr
|
|
262
|
+
for stream in (out, err):
|
|
263
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
264
|
+
if reconfigure is not None:
|
|
265
|
+
reconfigure(encoding="utf-8")
|
|
266
|
+
args = build_parser().parse_args(argv)
|
|
267
|
+
cli = Cli(out, err)
|
|
268
|
+
try:
|
|
269
|
+
return int(getattr(cli, f"cmd_{args.command}")(args))
|
|
270
|
+
except UsageError as e:
|
|
271
|
+
err.write(f"sipl: error: {e}\n")
|
|
272
|
+
return EXIT_USAGE
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
if __name__ == "__main__": # pragma: no cover
|
|
276
|
+
sys.exit(main())
|
sipl/diagnostics.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Diagnostics and error types shared by parser, interpreter and CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .ast import UNKNOWN_SPAN, SourceSpan
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Diagnostic:
|
|
13
|
+
code: str
|
|
14
|
+
message: str
|
|
15
|
+
span: SourceSpan = UNKNOWN_SPAN
|
|
16
|
+
severity: str = "error"
|
|
17
|
+
|
|
18
|
+
def to_dict(self) -> dict[str, Any]:
|
|
19
|
+
return {
|
|
20
|
+
"severity": self.severity,
|
|
21
|
+
"code": self.code,
|
|
22
|
+
"message": self.message,
|
|
23
|
+
"span": self.span.to_dict(),
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
def format(self, filename: str = "<input>") -> str:
|
|
27
|
+
return (
|
|
28
|
+
f"{filename}:{self.span.line}:{self.span.column}: {self.severity}: {self.message} [{self.code}]"
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SiplError(Exception):
|
|
33
|
+
code = "E000"
|
|
34
|
+
|
|
35
|
+
def __init__(self, message: str, span: SourceSpan = UNKNOWN_SPAN, code: str | None = None):
|
|
36
|
+
super().__init__(message)
|
|
37
|
+
self.message = message
|
|
38
|
+
self.span = span
|
|
39
|
+
if code is not None:
|
|
40
|
+
self.code = code
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def diagnostic(self) -> Diagnostic:
|
|
44
|
+
return Diagnostic(self.code, self.message, self.span)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class SiplSyntaxError(SiplError):
|
|
48
|
+
code = "E100"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class SiplRuntimeError(SiplError):
|
|
52
|
+
code = "E200"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class UndefinedVariableError(SiplRuntimeError):
|
|
56
|
+
code = "E201"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class DivisionByZeroError(SiplRuntimeError):
|
|
60
|
+
code = "E202"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class StepLimitExceeded(SiplRuntimeError):
|
|
64
|
+
code = "E300"
|
sipl/grammar/__init__.py
ADDED
|
File without changes
|
sipl/grammar/sipl.lark
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// SIPL grammar (Lark, LALR(1)).
|
|
2
|
+
// Follows the BNF from "Теорія програмування. Практикум" (2024), practical work 1:
|
|
3
|
+
// P ::= begin S end P1
|
|
4
|
+
// S ::= x := a | S1 ; S2 | if b then S1 else S2
|
|
5
|
+
// | while b do S | begin S end | skip S1-S6
|
|
6
|
+
// a ::= n | x | a1 + a2 | a1 - a2 | a1 * a2 | (a) A1-A6
|
|
7
|
+
// b ::= a1 = a2 | a1 > a2 | b1 or b2 | not b | (b) B1-B5
|
|
8
|
+
// Ambiguity of the BNF is resolved by priorities:
|
|
9
|
+
// ";" is the weakest, so "while b do S1; S2" means "(while b do S1); S2".
|
|
10
|
+
// "*" binds tighter than "+" and "-", all binary operators are left-assoc.
|
|
11
|
+
// "not" binds tighter than "or".
|
|
12
|
+
// Extensions (marked SIPL+ in docs/language.md): div, mod, comments.
|
|
13
|
+
|
|
14
|
+
start: program
|
|
15
|
+
|
|
16
|
+
program: "begin" seq "end"
|
|
17
|
+
|
|
18
|
+
seq: stmt (";" stmt)*
|
|
19
|
+
|
|
20
|
+
?stmt: assign
|
|
21
|
+
| if_stmt
|
|
22
|
+
| while_stmt
|
|
23
|
+
| block
|
|
24
|
+
| skip
|
|
25
|
+
|
|
26
|
+
assign: VAR ":=" aexp
|
|
27
|
+
if_stmt: "if" bexp "then" stmt "else" stmt
|
|
28
|
+
while_stmt: "while" bexp "do" stmt
|
|
29
|
+
block: "begin" seq "end"
|
|
30
|
+
skip: "skip"
|
|
31
|
+
|
|
32
|
+
?aexp: term
|
|
33
|
+
| aexp PLUS term -> binop
|
|
34
|
+
| aexp MINUS term -> binop
|
|
35
|
+
|
|
36
|
+
?term: factor
|
|
37
|
+
| term STAR factor -> binop
|
|
38
|
+
| term DIV factor -> binop
|
|
39
|
+
| term MOD factor -> binop
|
|
40
|
+
|
|
41
|
+
?factor: num
|
|
42
|
+
| var
|
|
43
|
+
| "(" aexp ")"
|
|
44
|
+
|
|
45
|
+
num: MINUS? INT
|
|
46
|
+
var: VAR
|
|
47
|
+
|
|
48
|
+
?bexp: bterm
|
|
49
|
+
| bexp OR bterm -> or_
|
|
50
|
+
|
|
51
|
+
?bterm: NOT bterm -> not_
|
|
52
|
+
| batom
|
|
53
|
+
|
|
54
|
+
?batom: aexp EQ aexp -> compare
|
|
55
|
+
| aexp GT aexp -> compare
|
|
56
|
+
| "(" bexp ")"
|
|
57
|
+
|
|
58
|
+
PLUS: "+"
|
|
59
|
+
MINUS: "-"
|
|
60
|
+
STAR: "*"
|
|
61
|
+
DIV.2: /div\b/
|
|
62
|
+
MOD.2: /mod\b/
|
|
63
|
+
EQ: "="
|
|
64
|
+
GT: ">"
|
|
65
|
+
OR.2: /or\b/ | "∨" | "\\/"
|
|
66
|
+
NOT.2: /not\b/ | "¬" | "!"
|
|
67
|
+
|
|
68
|
+
VAR: /[A-Za-z_][A-Za-z0-9_]*/
|
|
69
|
+
INT: /[0-9]+/
|
|
70
|
+
|
|
71
|
+
LINE_COMMENT: /\/\/[^\n]*/
|
|
72
|
+
BLOCK_COMMENT: /\/\*(.|\n)*?\*\//
|
|
73
|
+
|
|
74
|
+
%import common.WS
|
|
75
|
+
%ignore WS
|
|
76
|
+
%ignore LINE_COMMENT
|
|
77
|
+
%ignore BLOCK_COMMENT
|