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
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""SIPL interpreter: states, statement execution and trace events."""
|
|
2
|
+
|
|
3
|
+
from .events import Event, EventKind, Listener
|
|
4
|
+
from .runtime import (
|
|
5
|
+
DEFAULT_MAX_STEPS,
|
|
6
|
+
ExecutionResult,
|
|
7
|
+
Interpreter,
|
|
8
|
+
eval_aexp,
|
|
9
|
+
eval_bexp,
|
|
10
|
+
format_state,
|
|
11
|
+
run,
|
|
12
|
+
trace,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"DEFAULT_MAX_STEPS",
|
|
17
|
+
"Event",
|
|
18
|
+
"EventKind",
|
|
19
|
+
"ExecutionResult",
|
|
20
|
+
"Interpreter",
|
|
21
|
+
"Listener",
|
|
22
|
+
"eval_aexp",
|
|
23
|
+
"eval_bexp",
|
|
24
|
+
"format_state",
|
|
25
|
+
"run",
|
|
26
|
+
"trace",
|
|
27
|
+
]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Execution events (trace model) used by CLI, debugger and visualizers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from ..ast import UNKNOWN_SPAN, SourceSpan
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class EventKind(str, Enum):
|
|
14
|
+
START = "start"
|
|
15
|
+
BEFORE_STATEMENT = "before_statement"
|
|
16
|
+
AFTER_STATEMENT = "after_statement"
|
|
17
|
+
ASSIGN = "assign"
|
|
18
|
+
CONDITION = "condition"
|
|
19
|
+
FINISH = "finish"
|
|
20
|
+
ERROR = "error"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Event:
|
|
25
|
+
kind: EventKind
|
|
26
|
+
step: int
|
|
27
|
+
span: SourceSpan = UNKNOWN_SPAN
|
|
28
|
+
node: str | None = None
|
|
29
|
+
data: dict[str, Any] = field(default_factory=dict)
|
|
30
|
+
state: dict[str, int] = field(default_factory=dict)
|
|
31
|
+
|
|
32
|
+
def to_dict(self) -> dict[str, Any]:
|
|
33
|
+
d: dict[str, Any] = {"kind": self.kind.value, "step": self.step}
|
|
34
|
+
if self.node is not None:
|
|
35
|
+
d["node"] = self.node
|
|
36
|
+
if self.span != UNKNOWN_SPAN:
|
|
37
|
+
d["span"] = self.span.to_dict()
|
|
38
|
+
d.update(self.data)
|
|
39
|
+
d["state"] = dict(self.state)
|
|
40
|
+
return d
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
Listener = Callable[[Event], None]
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Big-step interpreter of SIPL with an event stream.
|
|
2
|
+
|
|
3
|
+
A state is a finite mapping Var -> int, like st = [X -> 5, Y -> 2] in the course.
|
|
4
|
+
Reading a variable that is not in the state is an error: the semantic function
|
|
5
|
+
x=> is undefined on such a state, so the whole program is undefined too.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .. import ast
|
|
14
|
+
from ..diagnostics import (
|
|
15
|
+
DivisionByZeroError,
|
|
16
|
+
SiplRuntimeError,
|
|
17
|
+
StepLimitExceeded,
|
|
18
|
+
UndefinedVariableError,
|
|
19
|
+
)
|
|
20
|
+
from .events import Event, EventKind, Listener
|
|
21
|
+
|
|
22
|
+
DEFAULT_MAX_STEPS = 100_000
|
|
23
|
+
|
|
24
|
+
State = dict[str, int]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def format_state(state: State) -> str:
|
|
28
|
+
return "[" + ", ".join(f"{k} ↦ {v}" for k, v in state.items()) + "]"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def eval_aexp(a: ast.Aexp, state: State) -> int:
|
|
32
|
+
if isinstance(a, ast.Num):
|
|
33
|
+
return a.value
|
|
34
|
+
if isinstance(a, ast.Var):
|
|
35
|
+
if a.name not in state:
|
|
36
|
+
raise UndefinedVariableError(f"variable {a.name} is undefined in the current state", a.span)
|
|
37
|
+
return state[a.name]
|
|
38
|
+
if isinstance(a, ast.BinOp):
|
|
39
|
+
left = eval_aexp(a.left, state)
|
|
40
|
+
right = eval_aexp(a.right, state)
|
|
41
|
+
if a.op == "+":
|
|
42
|
+
return left + right
|
|
43
|
+
if a.op == "-":
|
|
44
|
+
return left - right
|
|
45
|
+
if a.op == "*":
|
|
46
|
+
return left * right
|
|
47
|
+
if right == 0:
|
|
48
|
+
raise DivisionByZeroError(f"division by zero in '{a.op}'", a.span)
|
|
49
|
+
if a.op == "div":
|
|
50
|
+
return left // right
|
|
51
|
+
if a.op == "mod":
|
|
52
|
+
return left % right
|
|
53
|
+
raise SiplRuntimeError(f"unknown arithmetic expression {a!r}")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def eval_bexp(b: ast.Bexp, state: State) -> bool:
|
|
57
|
+
if isinstance(b, ast.Compare):
|
|
58
|
+
left = eval_aexp(b.left, state)
|
|
59
|
+
right = eval_aexp(b.right, state)
|
|
60
|
+
return left == right if b.op == "=" else left > right
|
|
61
|
+
if isinstance(b, ast.Or):
|
|
62
|
+
# both operands are evaluated, as in S^2(or, fb1, fb2)
|
|
63
|
+
left = eval_bexp(b.left, state)
|
|
64
|
+
right = eval_bexp(b.right, state)
|
|
65
|
+
return left or right
|
|
66
|
+
if isinstance(b, ast.Not):
|
|
67
|
+
return not eval_bexp(b.operand, state)
|
|
68
|
+
raise SiplRuntimeError(f"unknown condition {b!r}")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class ExecutionResult:
|
|
73
|
+
status: str # "ok" | "error" | "step_limit"
|
|
74
|
+
state: State
|
|
75
|
+
steps: int
|
|
76
|
+
initial_state: State
|
|
77
|
+
error: SiplRuntimeError | None = None
|
|
78
|
+
events: list[Event] = field(default_factory=list)
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def ok(self) -> bool:
|
|
82
|
+
return self.status == "ok"
|
|
83
|
+
|
|
84
|
+
def to_dict(self, with_trace: bool = False) -> dict[str, Any]:
|
|
85
|
+
d: dict[str, Any] = {
|
|
86
|
+
"status": self.status,
|
|
87
|
+
"initial_state": dict(self.initial_state),
|
|
88
|
+
"state": dict(self.state),
|
|
89
|
+
"steps": self.steps,
|
|
90
|
+
}
|
|
91
|
+
if self.error is not None:
|
|
92
|
+
d["error"] = self.error.diagnostic.to_dict()
|
|
93
|
+
if with_trace:
|
|
94
|
+
d["trace"] = [e.to_dict() for e in self.events]
|
|
95
|
+
return d
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Interpreter:
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
program: ast.Program,
|
|
102
|
+
state: State | None = None,
|
|
103
|
+
max_steps: int = DEFAULT_MAX_STEPS,
|
|
104
|
+
listeners: list[Listener] | None = None,
|
|
105
|
+
):
|
|
106
|
+
self.program = program
|
|
107
|
+
self.initial_state: State = dict(state or {})
|
|
108
|
+
self.state: State = dict(self.initial_state)
|
|
109
|
+
self.max_steps = max_steps
|
|
110
|
+
self.steps = 0
|
|
111
|
+
self.listeners: list[Listener] = list(listeners or [])
|
|
112
|
+
|
|
113
|
+
def emit(self, kind: EventKind, node: ast.Node | None = None, **data: Any) -> None:
|
|
114
|
+
if not self.listeners:
|
|
115
|
+
return
|
|
116
|
+
event = Event(
|
|
117
|
+
kind=kind,
|
|
118
|
+
step=self.steps,
|
|
119
|
+
span=node.span if node is not None else ast.UNKNOWN_SPAN,
|
|
120
|
+
node=type(node).__name__ if node is not None else None,
|
|
121
|
+
data=data,
|
|
122
|
+
state=dict(self.state),
|
|
123
|
+
)
|
|
124
|
+
for listener in self.listeners:
|
|
125
|
+
listener(event)
|
|
126
|
+
|
|
127
|
+
def run(self) -> ExecutionResult:
|
|
128
|
+
self.emit(EventKind.START, self.program)
|
|
129
|
+
status = "ok"
|
|
130
|
+
error: SiplRuntimeError | None = None
|
|
131
|
+
try:
|
|
132
|
+
self.exec_stm(self.program.body)
|
|
133
|
+
except StepLimitExceeded as e:
|
|
134
|
+
status, error = "step_limit", e
|
|
135
|
+
except SiplRuntimeError as e:
|
|
136
|
+
status, error = "error", e
|
|
137
|
+
if error is not None:
|
|
138
|
+
self.emit(EventKind.ERROR, None, error=error.diagnostic.to_dict())
|
|
139
|
+
else:
|
|
140
|
+
self.emit(EventKind.FINISH, self.program)
|
|
141
|
+
return ExecutionResult(status, dict(self.state), self.steps, dict(self.initial_state), error)
|
|
142
|
+
|
|
143
|
+
def _tick(self, node: ast.Node) -> None:
|
|
144
|
+
self.steps += 1
|
|
145
|
+
if self.steps > self.max_steps:
|
|
146
|
+
raise StepLimitExceeded(
|
|
147
|
+
f"step limit of {self.max_steps} exceeded (possible infinite loop)", node.span
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
def exec_stm(self, s: ast.Stm) -> None:
|
|
151
|
+
# Seq and Block are structural, they do not count as steps
|
|
152
|
+
if isinstance(s, ast.Seq):
|
|
153
|
+
self.exec_stm(s.first)
|
|
154
|
+
self.exec_stm(s.second)
|
|
155
|
+
return
|
|
156
|
+
if isinstance(s, ast.Block):
|
|
157
|
+
self.exec_stm(s.body)
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
self._tick(s)
|
|
161
|
+
self.emit(EventKind.BEFORE_STATEMENT, s)
|
|
162
|
+
if isinstance(s, ast.Assign):
|
|
163
|
+
value = eval_aexp(s.value, self.state)
|
|
164
|
+
old = self.state.get(s.target)
|
|
165
|
+
self.state[s.target] = value
|
|
166
|
+
self.emit(EventKind.ASSIGN, s, variable=s.target, old=old, new=value)
|
|
167
|
+
elif isinstance(s, ast.Skip):
|
|
168
|
+
pass
|
|
169
|
+
elif isinstance(s, ast.If):
|
|
170
|
+
cond = eval_bexp(s.cond, self.state)
|
|
171
|
+
self.emit(EventKind.CONDITION, s.cond, construct="if", value=cond)
|
|
172
|
+
self.exec_stm(s.then_branch if cond else s.else_branch)
|
|
173
|
+
elif isinstance(s, ast.While):
|
|
174
|
+
iteration = 0
|
|
175
|
+
while True:
|
|
176
|
+
cond = eval_bexp(s.cond, self.state)
|
|
177
|
+
self.emit(EventKind.CONDITION, s.cond, construct="while", value=cond, iteration=iteration)
|
|
178
|
+
if not cond:
|
|
179
|
+
break
|
|
180
|
+
self.exec_stm(s.body)
|
|
181
|
+
iteration += 1
|
|
182
|
+
self._tick(s)
|
|
183
|
+
else:
|
|
184
|
+
raise SiplRuntimeError(f"unknown statement {s!r}", s.span)
|
|
185
|
+
self.emit(EventKind.AFTER_STATEMENT, s)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def run(
|
|
189
|
+
program: ast.Program, state: State | None = None, max_steps: int = DEFAULT_MAX_STEPS
|
|
190
|
+
) -> ExecutionResult:
|
|
191
|
+
return Interpreter(program, state, max_steps).run()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def trace(
|
|
195
|
+
program: ast.Program, state: State | None = None, max_steps: int = DEFAULT_MAX_STEPS
|
|
196
|
+
) -> ExecutionResult:
|
|
197
|
+
events: list[Event] = []
|
|
198
|
+
interp = Interpreter(program, state, max_steps, listeners=[events.append])
|
|
199
|
+
result = interp.run()
|
|
200
|
+
result.events = events
|
|
201
|
+
return result
|
sipl/parser.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""SIPL parser: source text -> typed AST (sipl.ast)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
from importlib import resources
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from lark import Lark, Token, Transformer, Tree, v_args
|
|
10
|
+
from lark.exceptions import UnexpectedCharacters, UnexpectedEOF, UnexpectedInput, UnexpectedToken, VisitError
|
|
11
|
+
|
|
12
|
+
from . import ast
|
|
13
|
+
from .ast import SourceSpan
|
|
14
|
+
from .diagnostics import SiplSyntaxError
|
|
15
|
+
|
|
16
|
+
TOKEN_NAMES = {
|
|
17
|
+
"VAR": "variable",
|
|
18
|
+
"INT": "number",
|
|
19
|
+
"$END": "end of input",
|
|
20
|
+
"OR": "'or'",
|
|
21
|
+
"NOT": "'not'",
|
|
22
|
+
"DIV": "'div'",
|
|
23
|
+
"MOD": "'mod'",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def grammar_text() -> str:
|
|
28
|
+
return resources.files("sipl.grammar").joinpath("sipl.lark").read_text(encoding="utf-8")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@lru_cache(maxsize=1)
|
|
32
|
+
def _lark() -> Lark:
|
|
33
|
+
return Lark(
|
|
34
|
+
grammar_text(), parser="lalr", lexer="basic", propagate_positions=True, maybe_placeholders=False
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parse_tree(source: str) -> Tree:
|
|
39
|
+
"""Raw Lark parse tree (concrete syntax). Raises SiplSyntaxError."""
|
|
40
|
+
try:
|
|
41
|
+
return _lark().parse(source)
|
|
42
|
+
except UnexpectedInput as e:
|
|
43
|
+
raise _syntax_error(e, source) from None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def parse(source: str) -> ast.Program:
|
|
47
|
+
tree = parse_tree(source)
|
|
48
|
+
try:
|
|
49
|
+
result = _ToAst().transform(tree)
|
|
50
|
+
except VisitError as e:
|
|
51
|
+
if isinstance(e.orig_exc, SiplSyntaxError):
|
|
52
|
+
raise e.orig_exc from None
|
|
53
|
+
raise
|
|
54
|
+
assert isinstance(result, ast.Program)
|
|
55
|
+
return result
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def parse_file(path: str) -> ast.Program:
|
|
59
|
+
with open(path, encoding="utf-8") as f:
|
|
60
|
+
return parse(f.read())
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _token_label(name: str) -> str:
|
|
64
|
+
if name in TOKEN_NAMES:
|
|
65
|
+
return TOKEN_NAMES[name]
|
|
66
|
+
for t in _lark().terminals:
|
|
67
|
+
if t.name == name and t.pattern.type == "str":
|
|
68
|
+
return f"'{t.pattern.value}'"
|
|
69
|
+
return name.lower()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _offset_to_span(source: str, pos: int, length: int = 1) -> SourceSpan:
|
|
73
|
+
line = source.count("\n", 0, pos) + 1
|
|
74
|
+
col = pos - (source.rfind("\n", 0, pos) + 1) + 1
|
|
75
|
+
return SourceSpan(line, col, line, col + length, pos, pos + length)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _syntax_error(e: UnexpectedInput, source: str) -> SiplSyntaxError:
|
|
79
|
+
if isinstance(e, UnexpectedToken) and e.token.type != "$END":
|
|
80
|
+
tok = e.token
|
|
81
|
+
expected = _expected(e)
|
|
82
|
+
span = _token_span(tok)
|
|
83
|
+
msg = f"unexpected {_token_label(tok.type) if tok.type in ('VAR', 'INT') else repr(str(tok))}"
|
|
84
|
+
if tok.type in ("VAR", "INT"):
|
|
85
|
+
msg += f" {tok!s}"
|
|
86
|
+
msg += f", expected {_join(expected)}"
|
|
87
|
+
before = source[: tok.start_pos or 0].rstrip()
|
|
88
|
+
if before.endswith(";") and tok.type == "END":
|
|
89
|
+
msg += " (a ';' before 'end' is not allowed: ';' separates statements)"
|
|
90
|
+
if "';'" in expected and tok.type in _STMT_START:
|
|
91
|
+
msg += " (missing ';' between statements?)"
|
|
92
|
+
if "'else'" in expected and len(expected) <= 6:
|
|
93
|
+
msg += " (in SIPL every 'if' needs an 'else' branch)"
|
|
94
|
+
return SiplSyntaxError(msg, span, "E101")
|
|
95
|
+
if isinstance(e, (UnexpectedEOF, UnexpectedToken)):
|
|
96
|
+
expected = _expected(e)
|
|
97
|
+
pos = len(source.rstrip())
|
|
98
|
+
return SiplSyntaxError(
|
|
99
|
+
f"unexpected end of input, expected {_join(expected)}", _offset_to_span(source, pos, 0), "E102"
|
|
100
|
+
)
|
|
101
|
+
if isinstance(e, UnexpectedCharacters):
|
|
102
|
+
ch = source[e.pos_in_stream] if e.pos_in_stream is not None and e.pos_in_stream < len(source) else "?"
|
|
103
|
+
span = _offset_to_span(source, e.pos_in_stream or 0)
|
|
104
|
+
return SiplSyntaxError(f"unexpected character {ch!r}", span, "E103")
|
|
105
|
+
return SiplSyntaxError(str(e), _offset_to_span(source, 0), "E100")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
_STMT_START = {"VAR", "IF", "WHILE", "BEGIN", "SKIP"}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _expected(e: UnexpectedInput) -> list[str]:
|
|
112
|
+
names: set[str] = set(getattr(e, "expected", None) or [])
|
|
113
|
+
ip = getattr(e, "interactive_parser", None)
|
|
114
|
+
if ip is not None:
|
|
115
|
+
try:
|
|
116
|
+
names = set(ip.accepts())
|
|
117
|
+
except Exception: # noqa: BLE001
|
|
118
|
+
pass
|
|
119
|
+
return sorted({_token_label(x) for x in names})
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _join(items: list[str]) -> str:
|
|
123
|
+
if len(items) == 1:
|
|
124
|
+
return items[0]
|
|
125
|
+
return "one of " + ", ".join(items)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _token_span(tok: Token) -> SourceSpan:
|
|
129
|
+
return SourceSpan(
|
|
130
|
+
tok.line or 0,
|
|
131
|
+
tok.column or 0,
|
|
132
|
+
tok.end_line or 0,
|
|
133
|
+
tok.end_column or 0,
|
|
134
|
+
tok.start_pos or 0,
|
|
135
|
+
tok.end_pos or 0,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _meta_span(meta: Any) -> SourceSpan:
|
|
140
|
+
if getattr(meta, "empty", True):
|
|
141
|
+
return ast.UNKNOWN_SPAN
|
|
142
|
+
return SourceSpan(meta.line, meta.column, meta.end_line, meta.end_column, meta.start_pos, meta.end_pos)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _join_spans(a: SourceSpan, b: SourceSpan) -> SourceSpan:
|
|
146
|
+
return SourceSpan(a.line, a.column, b.end_line, b.end_column, a.start, b.end)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@v_args(meta=True)
|
|
150
|
+
class _ToAst(Transformer):
|
|
151
|
+
def start(self, meta, items):
|
|
152
|
+
return items[0]
|
|
153
|
+
|
|
154
|
+
def program(self, meta, items):
|
|
155
|
+
return ast.Program(items[0], span=_meta_span(meta))
|
|
156
|
+
|
|
157
|
+
def seq(self, meta, items):
|
|
158
|
+
# S1; S2; S3 is folded to the left: (S1; S2); S3
|
|
159
|
+
result = items[0]
|
|
160
|
+
for stm in items[1:]:
|
|
161
|
+
result = ast.Seq(result, stm, span=_join_spans(result.span, stm.span))
|
|
162
|
+
return result
|
|
163
|
+
|
|
164
|
+
def assign(self, meta, items):
|
|
165
|
+
name, value = items
|
|
166
|
+
return ast.Assign(str(name), value, span=_meta_span(meta), target_span=_token_span(name))
|
|
167
|
+
|
|
168
|
+
def if_stmt(self, meta, items):
|
|
169
|
+
cond, then_b, else_b = items
|
|
170
|
+
return ast.If(cond, then_b, else_b, span=_meta_span(meta))
|
|
171
|
+
|
|
172
|
+
def while_stmt(self, meta, items):
|
|
173
|
+
cond, body = items
|
|
174
|
+
return ast.While(cond, body, span=_meta_span(meta))
|
|
175
|
+
|
|
176
|
+
def block(self, meta, items):
|
|
177
|
+
return ast.Block(items[0], span=_meta_span(meta))
|
|
178
|
+
|
|
179
|
+
def skip(self, meta, items):
|
|
180
|
+
return ast.Skip(span=_meta_span(meta))
|
|
181
|
+
|
|
182
|
+
def binop(self, meta, items):
|
|
183
|
+
left, op, right = items
|
|
184
|
+
return ast.BinOp(str(op), left, right, span=_meta_span(meta))
|
|
185
|
+
|
|
186
|
+
def num(self, meta, items):
|
|
187
|
+
text = "".join(str(t) for t in items)
|
|
188
|
+
return ast.Num(int(text), span=_meta_span(meta))
|
|
189
|
+
|
|
190
|
+
def var(self, meta, items):
|
|
191
|
+
return ast.Var(str(items[0]), span=_meta_span(meta))
|
|
192
|
+
|
|
193
|
+
def compare(self, meta, items):
|
|
194
|
+
left, op, right = items
|
|
195
|
+
return ast.Compare(str(op), left, right, span=_meta_span(meta))
|
|
196
|
+
|
|
197
|
+
def or_(self, meta, items):
|
|
198
|
+
left, _, right = items
|
|
199
|
+
return ast.Or(left, right, span=_meta_span(meta))
|
|
200
|
+
|
|
201
|
+
def not_(self, meta, items):
|
|
202
|
+
_, operand = items
|
|
203
|
+
return ast.Not(operand, span=_meta_span(meta))
|
sipl/printer.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""AST -> SIPL source text (one line or indented)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from . import ast
|
|
6
|
+
|
|
7
|
+
_PREC = {"+": 1, "-": 1, "*": 2, "div": 2, "mod": 2}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def aexp_to_str(a: ast.Aexp, parent_prec: int = 0, right: bool = False) -> str:
|
|
11
|
+
if isinstance(a, ast.Num):
|
|
12
|
+
return str(a.value)
|
|
13
|
+
if isinstance(a, ast.Var):
|
|
14
|
+
return a.name
|
|
15
|
+
prec = _PREC[a.op]
|
|
16
|
+
text = f"{aexp_to_str(a.left, prec)} {a.op} {aexp_to_str(a.right, prec, right=True)}"
|
|
17
|
+
# left-assoc: the right operand of equal precedence needs parentheses
|
|
18
|
+
if prec < parent_prec or (right and prec == parent_prec):
|
|
19
|
+
return f"({text})"
|
|
20
|
+
return text
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def bexp_to_str(b: ast.Bexp, parent: int = 0, right: bool = False) -> str:
|
|
24
|
+
if isinstance(b, ast.Compare):
|
|
25
|
+
text = f"{aexp_to_str(b.left)} {b.op} {aexp_to_str(b.right)}"
|
|
26
|
+
return f"({text})" if parent == 2 else text
|
|
27
|
+
if isinstance(b, ast.Not):
|
|
28
|
+
return f"not {bexp_to_str(b.operand, 2)}"
|
|
29
|
+
text = f"{bexp_to_str(b.left, 1)} or {bexp_to_str(b.right, 1, right=True)}"
|
|
30
|
+
return f"({text})" if parent == 2 or right else text
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def stm_to_str(s: ast.Stm) -> str:
|
|
34
|
+
if isinstance(s, ast.Assign):
|
|
35
|
+
return f"{s.target} := {aexp_to_str(s.value)}"
|
|
36
|
+
if isinstance(s, ast.Seq):
|
|
37
|
+
return f"{stm_to_str(s.first)}; {stm_to_str(s.second)}"
|
|
38
|
+
if isinstance(s, ast.If):
|
|
39
|
+
return f"if {bexp_to_str(s.cond)} then {_inner(s.then_branch)} else {_inner(s.else_branch)}"
|
|
40
|
+
if isinstance(s, ast.While):
|
|
41
|
+
return f"while {bexp_to_str(s.cond)} do {_inner(s.body)}"
|
|
42
|
+
if isinstance(s, ast.Block):
|
|
43
|
+
return f"begin {stm_to_str(s.body)} end"
|
|
44
|
+
return "skip"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _inner(s: ast.Stm) -> str:
|
|
48
|
+
# a Seq directly inside if/while is impossible in valid SIPL, wrap it to stay correct
|
|
49
|
+
if isinstance(s, ast.Seq):
|
|
50
|
+
return f"begin {stm_to_str(s)} end"
|
|
51
|
+
return stm_to_str(s)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def program_to_str(p: ast.Program) -> str:
|
|
55
|
+
return f"begin {stm_to_str(p.body)} end"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def to_source(node: ast.Node) -> str:
|
|
59
|
+
if isinstance(node, ast.Program):
|
|
60
|
+
return program_to_str(node)
|
|
61
|
+
if isinstance(node, (ast.Num, ast.Var, ast.BinOp)):
|
|
62
|
+
return aexp_to_str(node)
|
|
63
|
+
if isinstance(node, (ast.Compare, ast.Or, ast.Not)):
|
|
64
|
+
return bexp_to_str(node)
|
|
65
|
+
return stm_to_str(node) # type: ignore[arg-type]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Semantic terms of SIPL programs (course notation)."""
|
|
2
|
+
|
|
3
|
+
from .terms import (
|
|
4
|
+
AssignT,
|
|
5
|
+
Const,
|
|
6
|
+
Denom,
|
|
7
|
+
Derivation,
|
|
8
|
+
Group,
|
|
9
|
+
IdT,
|
|
10
|
+
IfT,
|
|
11
|
+
RuleStep,
|
|
12
|
+
SeqT,
|
|
13
|
+
Superpos,
|
|
14
|
+
Term,
|
|
15
|
+
WhT,
|
|
16
|
+
derive,
|
|
17
|
+
sem_p,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"AssignT",
|
|
22
|
+
"Const",
|
|
23
|
+
"Denom",
|
|
24
|
+
"Derivation",
|
|
25
|
+
"Group",
|
|
26
|
+
"IdT",
|
|
27
|
+
"IfT",
|
|
28
|
+
"RuleStep",
|
|
29
|
+
"SeqT",
|
|
30
|
+
"Superpos",
|
|
31
|
+
"Term",
|
|
32
|
+
"WhT",
|
|
33
|
+
"derive",
|
|
34
|
+
"sem_p",
|
|
35
|
+
]
|