artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
0
calculators/builder-solo/run-01/calc/__init__.py
Normal file
0
calculators/builder-solo/run-01/calc/__init__.py
Normal file
37
calculators/builder-solo/run-01/calc/evaluator.py
Normal file
37
calculators/builder-solo/run-01/calc/evaluator.py
Normal file
@ -0,0 +1,37 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from calc.parser import BinOp, Node, Num, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node: Node) -> int | float:
|
||||
"""Walk an AST and return its numeric value.
|
||||
|
||||
Result type rule: integer arithmetic stays int; true division always
|
||||
produces a float (callers display whole-valued floats without '.0').
|
||||
"""
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
val = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return -val
|
||||
raise EvalError(f"unknown unary operator: {node.op!r}")
|
||||
if isinstance(node, BinOp):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
if node.op == '+':
|
||||
return left + right
|
||||
if node.op == '-':
|
||||
return left - right
|
||||
if node.op == '*':
|
||||
return left * right
|
||||
if node.op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
return left / right
|
||||
raise EvalError(f"unknown binary operator: {node.op!r}")
|
||||
raise EvalError(f"unknown node type: {type(node)!r}")
|
||||
56
calculators/builder-solo/run-01/calc/lexer.py
Normal file
56
calculators/builder-solo/run-01/calc/lexer.py
Normal file
@ -0,0 +1,56 @@
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Token:
|
||||
kind: str
|
||||
value: Union[int, float, str, None]
|
||||
|
||||
def __repr__(self):
|
||||
return f"{self.kind}({self.value!r})"
|
||||
|
||||
|
||||
_SINGLE = {
|
||||
'+': 'PLUS',
|
||||
'-': 'MINUS',
|
||||
'*': 'STAR',
|
||||
'/': 'SLASH',
|
||||
'(': 'LPAREN',
|
||||
')': 'RPAREN',
|
||||
}
|
||||
|
||||
|
||||
def tokenize(src: str) -> list[Token]:
|
||||
tokens: list[Token] = []
|
||||
i = 0
|
||||
n = len(src)
|
||||
while i < n:
|
||||
ch = src[i]
|
||||
if ch in ' \t\r\n':
|
||||
i += 1
|
||||
continue
|
||||
if ch in _SINGLE:
|
||||
tokens.append(Token(_SINGLE[ch], ch))
|
||||
i += 1
|
||||
continue
|
||||
if ch.isdigit() or ch == '.':
|
||||
j = i
|
||||
has_dot = False
|
||||
while j < n and (src[j].isdigit() or (src[j] == '.' and not has_dot)):
|
||||
if src[j] == '.':
|
||||
has_dot = True
|
||||
j += 1
|
||||
raw = src[i:j]
|
||||
value: Union[int, float] = float(raw) if has_dot else int(raw)
|
||||
tokens.append(Token('NUMBER', value))
|
||||
i = j
|
||||
continue
|
||||
raise LexError(f"unexpected character {ch!r} at position {i}")
|
||||
tokens.append(Token('EOF', None))
|
||||
return tokens
|
||||
133
calculators/builder-solo/run-01/calc/parser.py
Normal file
133
calculators/builder-solo/run-01/calc/parser.py
Normal file
@ -0,0 +1,133 @@
|
||||
"""Recursive-descent parser for calc expressions.
|
||||
|
||||
AST node shapes (all are dataclasses with __repr__):
|
||||
Num(value: int|float)
|
||||
BinOp(op: str, left: Node, right: Node) -- op in {'+','-','*','/'}
|
||||
Unary(op: str, operand: Node) -- op == '-'
|
||||
|
||||
Grammar:
|
||||
expr ::= term (( '+' | '-' ) term)*
|
||||
term ::= unary (( '*' | '/' ) unary)*
|
||||
unary ::= '-' unary | primary
|
||||
primary::= NUMBER | '(' expr ')'
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
from calc.lexer import Token
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# ---------- AST nodes ----------
|
||||
|
||||
@dataclass
|
||||
class Num:
|
||||
value: Union[int, float]
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Num({self.value!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
op: str
|
||||
left: "Node"
|
||||
right: "Node"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
op: str
|
||||
operand: "Node"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Unary({self.op!r}, {self.operand!r})"
|
||||
|
||||
|
||||
Node = Union[Num, BinOp, Unary]
|
||||
|
||||
|
||||
# ---------- parser ----------
|
||||
|
||||
class _Parser:
|
||||
def __init__(self, tokens: list[Token]) -> None:
|
||||
self._tokens = tokens
|
||||
self._pos = 0
|
||||
|
||||
def _peek(self) -> Token:
|
||||
return self._tokens[self._pos]
|
||||
|
||||
def _consume(self) -> Token:
|
||||
tok = self._tokens[self._pos]
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def _expect(self, kind: str) -> Token:
|
||||
tok = self._peek()
|
||||
if tok.kind != kind:
|
||||
raise ParseError(
|
||||
f"expected {kind!r} but got {tok.kind!r} ({tok.value!r})"
|
||||
)
|
||||
return self._consume()
|
||||
|
||||
def parse(self) -> Node:
|
||||
if self._peek().kind == 'EOF':
|
||||
raise ParseError("empty input")
|
||||
node = self._expr()
|
||||
if self._peek().kind != 'EOF':
|
||||
tok = self._peek()
|
||||
raise ParseError(
|
||||
f"unexpected token {tok.kind!r} ({tok.value!r}) after expression"
|
||||
)
|
||||
return node
|
||||
|
||||
def _expr(self) -> Node:
|
||||
node = self._term()
|
||||
while self._peek().kind in ('PLUS', 'MINUS'):
|
||||
op = self._consume().value
|
||||
right = self._term()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
def _term(self) -> Node:
|
||||
node = self._unary()
|
||||
while self._peek().kind in ('STAR', 'SLASH'):
|
||||
op = self._consume().value
|
||||
right = self._unary()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
def _unary(self) -> Node:
|
||||
if self._peek().kind == 'MINUS':
|
||||
op = self._consume().value
|
||||
operand = self._unary()
|
||||
return Unary(op, operand)
|
||||
return self._primary()
|
||||
|
||||
def _primary(self) -> Node:
|
||||
tok = self._peek()
|
||||
if tok.kind == 'NUMBER':
|
||||
self._consume()
|
||||
return Num(tok.value)
|
||||
if tok.kind == 'LPAREN':
|
||||
self._consume()
|
||||
node = self._expr()
|
||||
self._expect('RPAREN')
|
||||
return node
|
||||
if tok.kind == 'EOF':
|
||||
raise ParseError("unexpected end of input")
|
||||
raise ParseError(
|
||||
f"unexpected token {tok.kind!r} ({tok.value!r})"
|
||||
)
|
||||
|
||||
|
||||
def parse(tokens: list[Token]) -> Node:
|
||||
"""Parse a list of tokens into an AST. Raises ParseError on malformed input."""
|
||||
return _Parser(tokens).parse()
|
||||
85
calculators/builder-solo/run-01/calc/test_evaluator.py
Normal file
85
calculators/builder-solo/run-01/calc/test_evaluator.py
Normal file
@ -0,0 +1,85 @@
|
||||
"""Tests for calc/evaluator.py — covers D1–D3 from the eval phase plan."""
|
||||
import unittest
|
||||
|
||||
from calc.evaluator import EvalError, evaluate
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse
|
||||
|
||||
|
||||
def ev(src: str):
|
||||
return evaluate(parse(tokenize(src)))
|
||||
|
||||
|
||||
class TestArithmetic(unittest.TestCase):
|
||||
"""D1 — correct evaluation for +, -, *, /, precedence, parens, unary minus."""
|
||||
|
||||
def test_mul_over_add(self):
|
||||
self.assertEqual(ev("2+3*4"), 14)
|
||||
|
||||
def test_paren_override(self):
|
||||
self.assertEqual(ev("(2+3)*4"), 20)
|
||||
|
||||
def test_left_assoc_sub(self):
|
||||
self.assertEqual(ev("8-3-2"), 3)
|
||||
|
||||
def test_unary_leading(self):
|
||||
self.assertEqual(ev("-2+5"), 3)
|
||||
|
||||
def test_mul_unary(self):
|
||||
self.assertEqual(ev("2*-3"), -6)
|
||||
|
||||
|
||||
class TestDivision(unittest.TestCase):
|
||||
"""D2 — true division; EvalError on divide by zero."""
|
||||
|
||||
def test_true_division(self):
|
||||
self.assertAlmostEqual(ev("7/2"), 3.5)
|
||||
|
||||
def test_exact_division_type(self):
|
||||
result = ev("4/2")
|
||||
self.assertAlmostEqual(result, 2.0)
|
||||
|
||||
def test_division_by_zero_raises_eval_error(self):
|
||||
with self.assertRaises(EvalError):
|
||||
ev("1/0")
|
||||
|
||||
def test_division_by_zero_expression(self):
|
||||
with self.assertRaises(EvalError):
|
||||
ev("5/(3-3)")
|
||||
|
||||
def test_not_bare_zero_division_error(self):
|
||||
from builtins import ZeroDivisionError as ZDE
|
||||
try:
|
||||
ev("1/0")
|
||||
except EvalError:
|
||||
pass # correct
|
||||
except ZDE:
|
||||
self.fail("ZeroDivisionError escaped; should be EvalError")
|
||||
|
||||
|
||||
class TestResultType(unittest.TestCase):
|
||||
"""D3 — result type rule: whole-valued floats vs fractional floats."""
|
||||
|
||||
def test_int_plus_int(self):
|
||||
result = ev("1+2")
|
||||
self.assertIsInstance(result, int)
|
||||
self.assertEqual(result, 3)
|
||||
|
||||
def test_true_div_fractional(self):
|
||||
result = ev("7/2")
|
||||
self.assertIsInstance(result, float)
|
||||
self.assertEqual(result, 3.5)
|
||||
|
||||
def test_true_div_whole_valued(self):
|
||||
result = ev("4/2")
|
||||
self.assertIsInstance(result, float)
|
||||
self.assertTrue(result == 2.0)
|
||||
|
||||
def test_unary_preserves_int(self):
|
||||
result = ev("-3")
|
||||
self.assertIsInstance(result, int)
|
||||
self.assertEqual(result, -3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
91
calculators/builder-solo/run-01/calc/test_lexer.py
Normal file
91
calculators/builder-solo/run-01/calc/test_lexer.py
Normal file
@ -0,0 +1,91 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize, Token, LexError
|
||||
|
||||
|
||||
def kinds(src):
|
||||
return [t.kind for t in tokenize(src)]
|
||||
|
||||
|
||||
def pairs(src):
|
||||
return [(t.kind, t.value) for t in tokenize(src)]
|
||||
|
||||
|
||||
class TestNumbers(unittest.TestCase):
|
||||
def test_integer(self):
|
||||
toks = tokenize("42")
|
||||
self.assertEqual(len(toks), 2)
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertEqual(toks[0].value, 42)
|
||||
self.assertIsInstance(toks[0].value, int)
|
||||
self.assertEqual(toks[1].kind, 'EOF')
|
||||
|
||||
def test_float(self):
|
||||
t = tokenize("3.14")[0]
|
||||
self.assertEqual(t.kind, 'NUMBER')
|
||||
self.assertAlmostEqual(t.value, 3.14)
|
||||
self.assertIsInstance(t.value, float)
|
||||
|
||||
def test_float_leading_dot(self):
|
||||
t = tokenize(".5")[0]
|
||||
self.assertEqual(t.kind, 'NUMBER')
|
||||
self.assertAlmostEqual(t.value, 0.5)
|
||||
|
||||
def test_float_trailing_dot(self):
|
||||
t = tokenize("10.")[0]
|
||||
self.assertEqual(t.kind, 'NUMBER')
|
||||
self.assertAlmostEqual(t.value, 10.0)
|
||||
self.assertIsInstance(t.value, float)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_single_ops(self):
|
||||
for ch, kind in [('+', 'PLUS'), ('-', 'MINUS'), ('*', 'STAR'), ('/', 'SLASH'),
|
||||
('(', 'LPAREN'), (')', 'RPAREN')]:
|
||||
with self.subTest(ch=ch):
|
||||
toks = tokenize(ch)
|
||||
self.assertEqual(toks[0].kind, kind)
|
||||
self.assertEqual(toks[1].kind, 'EOF')
|
||||
|
||||
def test_expression(self):
|
||||
self.assertEqual(kinds("1+2*3"),
|
||||
['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_complex_expression(self):
|
||||
self.assertEqual(kinds("3.5*(1-2)"),
|
||||
['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'])
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def test_whitespace(self):
|
||||
toks = tokenize(" 12 + 3 ")
|
||||
self.assertEqual(kinds(" 12 + 3 "), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
self.assertEqual(toks[0].value, 12)
|
||||
self.assertEqual(toks[2].value, 3)
|
||||
|
||||
def test_tabs(self):
|
||||
self.assertEqual(kinds("1\t+\t2"), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_invalid_at(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('@', str(ctx.exception))
|
||||
|
||||
def test_invalid_letter(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("abc")
|
||||
|
||||
def test_invalid_dollar(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$")
|
||||
|
||||
def test_position_in_message(self):
|
||||
try:
|
||||
tokenize("1 @ 2")
|
||||
except LexError as e:
|
||||
msg = str(e)
|
||||
self.assertIn('@', msg)
|
||||
self.assertIn('2', msg)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
125
calculators/builder-solo/run-01/calc/test_parser.py
Normal file
125
calculators/builder-solo/run-01/calc/test_parser.py
Normal file
@ -0,0 +1,125 @@
|
||||
"""Tests for calc/parser.py — covers D1–D5 from the parse phase plan."""
|
||||
import unittest
|
||||
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError, Num, BinOp, Unary
|
||||
|
||||
|
||||
def p(src: str):
|
||||
return parse(tokenize(src))
|
||||
|
||||
|
||||
class TestPrecedence(unittest.TestCase):
|
||||
"""D1 — * and / bind tighter than + and -"""
|
||||
|
||||
def test_mul_over_add(self):
|
||||
# 1+2*3 => BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
tree = p("1+2*3")
|
||||
self.assertEqual(tree, BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
def test_div_over_sub(self):
|
||||
# 10-6/2 => BinOp('-', Num(10), BinOp('/', Num(6), Num(2)))
|
||||
tree = p("10-6/2")
|
||||
self.assertEqual(tree, BinOp('-', Num(10), BinOp('/', Num(6), Num(2))))
|
||||
|
||||
def test_mul_then_add(self):
|
||||
# 2*3+4 => BinOp('+', BinOp('*', Num(2), Num(3)), Num(4))
|
||||
tree = p("2*3+4")
|
||||
self.assertEqual(tree, BinOp('+', BinOp('*', Num(2), Num(3)), Num(4)))
|
||||
|
||||
|
||||
class TestLeftAssociativity(unittest.TestCase):
|
||||
"""D2 — same-precedence operators associate left"""
|
||||
|
||||
def test_sub_left_assoc(self):
|
||||
# 8-3-2 => BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))
|
||||
tree = p("8-3-2")
|
||||
self.assertEqual(tree, BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)))
|
||||
|
||||
def test_div_left_assoc(self):
|
||||
# 8/4/2 => BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))
|
||||
tree = p("8/4/2")
|
||||
self.assertEqual(tree, BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)))
|
||||
|
||||
def test_add_left_assoc(self):
|
||||
# 1+2+3 => BinOp('+', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
tree = p("1+2+3")
|
||||
self.assertEqual(tree, BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
|
||||
class TestParentheses(unittest.TestCase):
|
||||
"""D3 — parens override precedence"""
|
||||
|
||||
def test_paren_forces_add_under_mul(self):
|
||||
# (1+2)*3 => BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
tree = p("(1+2)*3")
|
||||
self.assertEqual(tree, BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_nested_parens(self):
|
||||
# ((2+3)) => BinOp('+', Num(2), Num(3))
|
||||
tree = p("((2+3))")
|
||||
self.assertEqual(tree, BinOp('+', Num(2), Num(3)))
|
||||
|
||||
def test_paren_inside_expr(self):
|
||||
# 1*(2+3)*4 => BinOp('*', BinOp('*', Num(1), BinOp('+', Num(2), Num(3))), Num(4))
|
||||
tree = p("1*(2+3)*4")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp('*', BinOp('*', Num(1), BinOp('+', Num(2), Num(3))), Num(4))
|
||||
)
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
"""D4 — unary minus"""
|
||||
|
||||
def test_leading_unary(self):
|
||||
# -5 => Unary('-', Num(5))
|
||||
tree = p("-5")
|
||||
self.assertEqual(tree, Unary('-', Num(5)))
|
||||
|
||||
def test_unary_grouped(self):
|
||||
# -(1+2) => Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
tree = p("-(1+2)")
|
||||
self.assertEqual(tree, Unary('-', BinOp('+', Num(1), Num(2))))
|
||||
|
||||
def test_mul_unary(self):
|
||||
# 3 * -2 => BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
tree = p("3 * -2")
|
||||
self.assertEqual(tree, BinOp('*', Num(3), Unary('-', Num(2))))
|
||||
|
||||
def test_double_unary(self):
|
||||
# --5 => Unary('-', Unary('-', Num(5)))
|
||||
tree = p("--5")
|
||||
self.assertEqual(tree, Unary('-', Unary('-', Num(5))))
|
||||
|
||||
|
||||
class TestErrors(unittest.TestCase):
|
||||
"""D5 — malformed input raises ParseError"""
|
||||
|
||||
def test_trailing_operator(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("1 +")
|
||||
|
||||
def test_unclosed_paren(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("(1")
|
||||
|
||||
def test_extra_number(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("1 2")
|
||||
|
||||
def test_close_before_open(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p(")(")
|
||||
|
||||
def test_empty_string(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("")
|
||||
|
||||
def test_only_operator(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("+")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user