pyrpn-lib 0.1.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.
- pyrpn_lib/__init__.py +21 -0
- pyrpn_lib/ops.py +31 -0
- pyrpn_lib/program.py +124 -0
- pyrpn_lib/py.typed +0 -0
- pyrpn_lib/stack.py +55 -0
- pyrpn_lib-0.1.0.dist-info/METADATA +83 -0
- pyrpn_lib-0.1.0.dist-info/RECORD +8 -0
- pyrpn_lib-0.1.0.dist-info/WHEEL +4 -0
pyrpn_lib/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from .ops import Cmd, Op, add, div, dup, mul, neg, sqrt, sub, swap
|
|
2
|
+
from .program import StackFunction, StackProgram, stack_function
|
|
3
|
+
from .stack import Stack, StackUnderflow
|
|
4
|
+
|
|
5
|
+
__all__ = [ # noqa: RUF022
|
|
6
|
+
"Stack",
|
|
7
|
+
"StackUnderflow",
|
|
8
|
+
"StackProgram",
|
|
9
|
+
"StackFunction",
|
|
10
|
+
"stack_function",
|
|
11
|
+
"Op",
|
|
12
|
+
"add",
|
|
13
|
+
"sub",
|
|
14
|
+
"mul",
|
|
15
|
+
"div",
|
|
16
|
+
"neg",
|
|
17
|
+
"sqrt",
|
|
18
|
+
"Cmd",
|
|
19
|
+
"swap",
|
|
20
|
+
"dup",
|
|
21
|
+
]
|
pyrpn_lib/ops.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import operator
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class Op:
|
|
9
|
+
fn: Callable
|
|
10
|
+
arity: int
|
|
11
|
+
|
|
12
|
+
add = Op(operator.add, 2)
|
|
13
|
+
sub = Op(operator.sub, 2)
|
|
14
|
+
mul = Op(operator.mul, 2)
|
|
15
|
+
div = Op(operator.truediv, 2)
|
|
16
|
+
neg = Op(operator.neg, 1)
|
|
17
|
+
sqrt = Op(math.sqrt, 1)
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Cmd:
|
|
21
|
+
fn: Callable[[list], None]
|
|
22
|
+
needs: int = 0 # minimum stack depth
|
|
23
|
+
|
|
24
|
+
def _swap(items):
|
|
25
|
+
items[-1], items[-2] = items[-2], items[-1]
|
|
26
|
+
|
|
27
|
+
def _dup(items):
|
|
28
|
+
items.append(items[-1])
|
|
29
|
+
|
|
30
|
+
swap = Cmd(_swap, 2)
|
|
31
|
+
dup = Cmd(_dup, 1)
|
pyrpn_lib/program.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from collections.abc import Callable
|
|
3
|
+
from typing import get_type_hints
|
|
4
|
+
|
|
5
|
+
from .stack import Stack, StackUnderflow
|
|
6
|
+
|
|
7
|
+
StackProgramType = Callable[[Stack], None]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _validate_function(program: StackProgramType) -> None:
|
|
11
|
+
"""Raise TypeError if `fn` isn't (Stack) -> None."""
|
|
12
|
+
if not callable(program):
|
|
13
|
+
raise TypeError(f"program must be callable; got {type(program).__name__}")
|
|
14
|
+
|
|
15
|
+
name = getattr(program, "__name__", repr(program))
|
|
16
|
+
|
|
17
|
+
params = list(inspect.signature(program).parameters.values())
|
|
18
|
+
if len(params) != 1:
|
|
19
|
+
raise TypeError(
|
|
20
|
+
f"program: '{name}' must accept exactly one argument; found {len(params)}"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
param = params[0]
|
|
24
|
+
if param.kind not in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD):
|
|
25
|
+
raise TypeError(
|
|
26
|
+
f"program '{name}': its argument must be a plain positional parameter"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
hints = get_type_hints(program)
|
|
31
|
+
except Exception as ex:
|
|
32
|
+
raise TypeError(
|
|
33
|
+
f"program '{name}': could not resolve annotations: {ex}"
|
|
34
|
+
) from ex
|
|
35
|
+
|
|
36
|
+
if param.name not in hints:
|
|
37
|
+
raise TypeError(
|
|
38
|
+
f"program '{name}': parameter '{param.name}' needs a type annotation, expected pyrpn.Stack"
|
|
39
|
+
)
|
|
40
|
+
if hints[param.name] is not Stack:
|
|
41
|
+
raise TypeError(
|
|
42
|
+
f"program '{name}': parameter '{param.name}' must be annotated pyrpn.Stack; got {hints[param.name]!r}"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
if "return" not in hints:
|
|
46
|
+
raise TypeError(
|
|
47
|
+
f"program '{name}': missing return annotation (expected -> None)"
|
|
48
|
+
)
|
|
49
|
+
if hints["return"] is not type(None):
|
|
50
|
+
raise TypeError(
|
|
51
|
+
f"program '{name}': must return None; annotated {hints['return']!r}"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class StackFunction:
|
|
56
|
+
"""A (Stack) -> None routine that works on a stack the caller supplies."""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self, fn: StackProgramType, *, takes: int = 0, returns: int | None = None
|
|
60
|
+
) -> None:
|
|
61
|
+
_validate_function(fn)
|
|
62
|
+
self.fn = fn
|
|
63
|
+
self.takes = takes
|
|
64
|
+
self.returns = returns
|
|
65
|
+
self.__name__ = getattr(fn, "__name__", repr(fn))
|
|
66
|
+
self.__doc__ = fn.__doc__
|
|
67
|
+
|
|
68
|
+
def call(self, stack: Stack) -> Stack:
|
|
69
|
+
"""Run the program on an existing stack and return that same stack."""
|
|
70
|
+
|
|
71
|
+
if not isinstance(stack, Stack):
|
|
72
|
+
raise TypeError(
|
|
73
|
+
f"program '{self.__name__}' needs a stack; got {type(stack).__name__}"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
if len(stack) < self.takes:
|
|
77
|
+
raise StackUnderflow(
|
|
78
|
+
f"{self.__name__} takes {self.takes} items(s), stack has {len(stack)}"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
before = len(stack)
|
|
82
|
+
snapshot = stack.items.copy()
|
|
83
|
+
try:
|
|
84
|
+
result = self.fn(stack)
|
|
85
|
+
if result is not None:
|
|
86
|
+
raise TypeError(
|
|
87
|
+
f"program '{self.__name__}' returned {result!r}, expected None"
|
|
88
|
+
)
|
|
89
|
+
if self.returns is not None:
|
|
90
|
+
expected = before - self.takes + self.returns
|
|
91
|
+
if len(stack) != expected:
|
|
92
|
+
raise RuntimeError(
|
|
93
|
+
f"{self.__name__} declared ({self.takes} -> {self.returns}) "
|
|
94
|
+
f"but left {len(stack)} item(s), expected {expected}"
|
|
95
|
+
)
|
|
96
|
+
except Exception:
|
|
97
|
+
stack.items[:] = snapshot
|
|
98
|
+
raise
|
|
99
|
+
return stack
|
|
100
|
+
|
|
101
|
+
def __repr__(self) -> str:
|
|
102
|
+
return f"{type(self).__name__}({self.__name__})"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def stack_function(*, takes: int = 0, returns: int | None = None) -> Callable[[StackProgramType], StackFunction]:
|
|
106
|
+
def deco(fn: StackProgramType) -> StackFunction:
|
|
107
|
+
return StackFunction(fn, takes=takes, returns=returns)
|
|
108
|
+
|
|
109
|
+
return deco
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class StackProgram(StackFunction):
|
|
113
|
+
"""Wraps a (Stack) -> None function. Validated on creation; run with .run()."""
|
|
114
|
+
|
|
115
|
+
def __init__(self, fn: StackProgramType) -> None:
|
|
116
|
+
super().__init__(fn, takes=0)
|
|
117
|
+
|
|
118
|
+
def run(self, *, verbose: bool = True) -> Stack:
|
|
119
|
+
if verbose:
|
|
120
|
+
print(f"running program: {self.__name__}")
|
|
121
|
+
s = self.call(Stack())
|
|
122
|
+
if verbose:
|
|
123
|
+
print(s)
|
|
124
|
+
return s
|
pyrpn_lib/py.typed
ADDED
|
File without changes
|
pyrpn_lib/stack.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .ops import Cmd, Op
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class StackUnderflow(IndexError):
|
|
10
|
+
"""Raised when an operation needs more items than the stack holds."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _label(fn: Callable) -> str:
|
|
14
|
+
return getattr(fn, "__name__", repr(fn).lstrip("_"))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Stack:
|
|
18
|
+
def __init__(self) -> None:
|
|
19
|
+
self.items: list[Any] = []
|
|
20
|
+
|
|
21
|
+
def _need(self, n: int, what: str) -> None:
|
|
22
|
+
have = len(self.items)
|
|
23
|
+
if have < n:
|
|
24
|
+
raise StackUnderflow(f"{what} needs {n} items(s), stack has (have)")
|
|
25
|
+
|
|
26
|
+
def __lshift__(self, x: Any) -> Stack:
|
|
27
|
+
if isinstance(x, Op):
|
|
28
|
+
self._need(x.arity, _label(x.fn))
|
|
29
|
+
start = len(self.items) - x.arity
|
|
30
|
+
result = x.fn(*self.items[start:])
|
|
31
|
+
del self.items[start:]
|
|
32
|
+
self.items.append(result)
|
|
33
|
+
elif isinstance(x, Cmd):
|
|
34
|
+
self._need(x.needs, _label(x.fn))
|
|
35
|
+
x.fn(self.items)
|
|
36
|
+
else:
|
|
37
|
+
self.items.append(x)
|
|
38
|
+
return self
|
|
39
|
+
|
|
40
|
+
def __rshift__(self, sink: Callable):
|
|
41
|
+
self._need(1, "'>>'")
|
|
42
|
+
sink(self.items[-1])
|
|
43
|
+
self.items.pop()
|
|
44
|
+
return self
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def peek(self) -> Any:
|
|
48
|
+
self._need(1, "peek")
|
|
49
|
+
return self.items[-1]
|
|
50
|
+
|
|
51
|
+
def __len__(self) -> int:
|
|
52
|
+
return len(self.items)
|
|
53
|
+
|
|
54
|
+
def __repr__(self) -> str:
|
|
55
|
+
return f"Stack({self.items})"
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: pyrpn-lib
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A type-safe, decorator-driven RPN stack library for Python
|
|
5
|
+
Author: Breadleaf
|
|
6
|
+
Author-email: Breadleaf <bkhnapa@gmail.com>
|
|
7
|
+
Requires-Dist: pytest>=9.2.0
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# PyRPN
|
|
12
|
+
|
|
13
|
+
A type-safe, decorator-driven RPN stack library for Python
|
|
14
|
+
|
|
15
|
+
## Features
|
|
16
|
+
|
|
17
|
+
- Intuitive stack syntax: `<<` to push `>>` to sink
|
|
18
|
+
- Strict decorator validation: `@stack_function` and `@StackProgram` validates at definition time
|
|
19
|
+
- Automatic snapshots & rollbacks: if a decorated function or operation fails, the stack will automatically rollback
|
|
20
|
+
|
|
21
|
+
## Examples
|
|
22
|
+
|
|
23
|
+
### Basic Stack Arithmetic
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
import pyrpn as p
|
|
27
|
+
|
|
28
|
+
# Build expressions using the shift operator
|
|
29
|
+
s = p.Stack() << 5 << 3 << p.sub
|
|
30
|
+
print(s) # Output: Stack([2])
|
|
31
|
+
|
|
32
|
+
# Chaining multiple operators
|
|
33
|
+
calc = p.Stack() << 4 << 9 << p.sqrt << p.add
|
|
34
|
+
print(calc) # Output: Stack([7.0])
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Writing Custom Stack Functions
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
import pyrpn as p
|
|
41
|
+
|
|
42
|
+
@p.stack_function(takes=1, returns=1)
|
|
43
|
+
def add_one(s: p.Stack) -> None:
|
|
44
|
+
s << 1 << p.add
|
|
45
|
+
|
|
46
|
+
s = p.Stack() << 5
|
|
47
|
+
add_one.call(s)
|
|
48
|
+
print(s) # Output: Stack([6])
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Running Standalone Programs
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
import pyrpn as p
|
|
55
|
+
|
|
56
|
+
@p.StackProgram
|
|
57
|
+
def calculate_hypotenuse(s: p.Stack) -> None:
|
|
58
|
+
# sqrt(3^2 + 4^2) = 5.0
|
|
59
|
+
s << 3 << p.dup << p.mul
|
|
60
|
+
s << 4 << p.dup << p.mul
|
|
61
|
+
s << p.add << p.sqrt
|
|
62
|
+
|
|
63
|
+
result = calculate_hypotenuse.run()
|
|
64
|
+
# Output:
|
|
65
|
+
# running program: calculate_hypotenuse
|
|
66
|
+
# Stack([5.0])
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Sinking Results
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
import pyrpn as p
|
|
73
|
+
|
|
74
|
+
results = []
|
|
75
|
+
s = p.Stack() << 43
|
|
76
|
+
s >> results.append
|
|
77
|
+
print(results) # Output: [43]
|
|
78
|
+
print(s) # Output: Stack([])
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
Distributed under the MIT License. See LICENSE for more information.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
pyrpn_lib/__init__.py,sha256=LD5K4F9IOW9LbS4WTVqV01j2IgFwFB85GI2aLWlgGzM,413
|
|
2
|
+
pyrpn_lib/ops.py,sha256=pt1IUBJt90sPcvsXQQfmXh_r3aUYF3n-1SQcB_LjwPw,588
|
|
3
|
+
pyrpn_lib/program.py,sha256=bWhOjf3Z_EmBMUeEVjaFu6n7BnHoqe5p-1Ok9ADPdaw,4164
|
|
4
|
+
pyrpn_lib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
pyrpn_lib/stack.py,sha256=aYAHtIlioSmqkH5B0B_-gUACd6Bn8LEbK13hIeamdrk,1430
|
|
6
|
+
pyrpn_lib-0.1.0.dist-info/WHEEL,sha256=7hzKWg-J8I3Buqyw5tBii5z_MmAVsDYXXijd_QAtNZ8,81
|
|
7
|
+
pyrpn_lib-0.1.0.dist-info/METADATA,sha256=NoxRu58vSfWdW1wSzJ6edJmTvKJ2uX2vjU01YyBArTc,1711
|
|
8
|
+
pyrpn_lib-0.1.0.dist-info/RECORD,,
|