artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs

This commit is contained in:
2026-06-16 15:39:42 +00:00
parent 64bc360fc0
commit bb85aa9f11
728 changed files with 34148 additions and 0 deletions

View File

@ -0,0 +1,41 @@
"""Evaluator for the arithmetic AST produced by calc.parser.
evaluate(node) -> int | float
Result-type rule: if the result is a whole number (no fractional part),
return an int; otherwise return a float. This means 4/2 → 2 (int) and
7/2 → 3.5 (float).
"""
from calc.parser import Num, BinOp, Unary, Node
class EvalError(Exception):
pass
def evaluate(node: Node) -> "int | float":
if isinstance(node, Num):
return node.value
if isinstance(node, Unary):
return -evaluate(node.operand)
if isinstance(node, BinOp):
left = evaluate(node.left)
right = evaluate(node.right)
op = node.op
if op == '+':
result = left + right
elif op == '-':
result = left - right
elif op == '*':
result = left * right
elif op == '/':
if right == 0:
raise EvalError("division by zero")
result = left / right
else:
raise EvalError(f"unknown operator: {op!r}")
if isinstance(result, float) and result.is_integer():
return int(result)
return result
raise EvalError(f"unknown node type: {type(node).__name__}")

View File

@ -0,0 +1,49 @@
"""Lexer for arithmetic expressions."""
from typing import NamedTuple, Union
class LexError(Exception):
pass
class Token(NamedTuple):
kind: str
value: Union[int, float, str, None]
_SINGLE = {
'+': 'PLUS',
'-': 'MINUS',
'*': 'STAR',
'/': 'SLASH',
'(': 'LPAREN',
')': 'RPAREN',
}
def tokenize(src: str) -> list:
tokens = []
i = 0
while i < len(src):
ch = src[i]
if ch in ' \t':
i += 1
elif ch in _SINGLE:
tokens.append(Token(_SINGLE[ch], ch))
i += 1
elif ch.isdigit() or ch == '.':
j = i
has_dot = False
while j < len(src) and (src[j].isdigit() or (src[j] == '.' and not has_dot)):
if src[j] == '.':
has_dot = True
j += 1
raw = src[i:j]
value = float(raw) if has_dot else int(raw)
tokens.append(Token('NUMBER', value))
i = j
else:
raise LexError(f"unexpected character {ch!r} at position {i}")
tokens.append(Token('EOF', None))
return tokens

View File

@ -0,0 +1,147 @@
"""Recursive-descent parser for arithmetic expressions.
AST node shapes (stable contract for the eval phase):
Num(value) — numeric literal; value is int or float
BinOp(op, left, right) — binary operation; op in ('+', '-', '*', '/')
Unary(op, operand) — unary operation; op == '-'
Grammar (encodes precedence and left-associativity):
expr → term (('+' | '-') term)*
term → unary (('*' | '/') unary)*
unary → '-' unary | primary
primary → NUMBER | '(' expr ')'
"""
from __future__ import annotations
from typing import Union
class ParseError(Exception):
pass
class Num:
__slots__ = ("value",)
def __init__(self, value: Union[int, float]) -> None:
self.value = value
def __repr__(self) -> str:
return f"Num({self.value!r})"
def __eq__(self, other: object) -> bool:
return isinstance(other, Num) and self.value == other.value
class BinOp:
__slots__ = ("op", "left", "right")
def __init__(self, op: str, left: "Node", right: "Node") -> None:
self.op = op
self.left = left
self.right = right
def __repr__(self) -> str:
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
def __eq__(self, other: object) -> bool:
return (
isinstance(other, BinOp)
and self.op == other.op
and self.left == other.left
and self.right == other.right
)
class Unary:
__slots__ = ("op", "operand")
def __init__(self, op: str, operand: "Node") -> None:
self.op = op
self.operand = operand
def __repr__(self) -> str:
return f"Unary({self.op!r}, {self.operand!r})"
def __eq__(self, other: object) -> bool:
return (
isinstance(other, Unary)
and self.op == other.op
and self.operand == other.operand
)
Node = Union[Num, BinOp, Unary]
class _Parser:
def __init__(self, tokens: list) -> None:
self._tokens = tokens
self._pos = 0
def _peek(self):
return self._tokens[self._pos]
def _consume(self, kind: str = None):
tok = self._tokens[self._pos]
if kind is not None and tok.kind != kind:
raise ParseError(
f"expected {kind}, got {tok.kind!r} ({tok.value!r})"
)
self._pos += 1
return tok
def parse(self) -> Node:
if self._peek().kind == "EOF":
raise ParseError("empty expression")
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("LPAREN")
node = self._expr()
if self._peek().kind != "RPAREN":
raise ParseError("unclosed parenthesis — expected ')'")
self._consume("RPAREN")
return node
if tok.kind == "EOF":
raise ParseError("unexpected end of expression")
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")
def parse(tokens: list) -> Node:
"""Parse a token list produced by calc.lexer.tokenize into an AST."""
return _Parser(tokens).parse()

View File

@ -0,0 +1,99 @@
"""Tests for calc.evaluator — covers D1, D2, D3, and a CLI smoke test (D4)."""
import subprocess
import sys
import unittest
from calc.lexer import tokenize
from calc.parser import parse
from calc.evaluator import evaluate, EvalError
def calc(expr):
return evaluate(parse(tokenize(expr)))
class TestArithmetic(unittest.TestCase):
"""D1 — + - * /, precedence, parens, unary minus."""
def test_addition(self):
self.assertEqual(calc("1+2"), 3)
def test_multiplication_precedence(self):
self.assertEqual(calc("2+3*4"), 14)
def test_parens_override_precedence(self):
self.assertEqual(calc("(2+3)*4"), 20)
def test_left_assoc_subtraction(self):
self.assertEqual(calc("8-3-2"), 3)
def test_unary_minus_leading(self):
self.assertEqual(calc("-2+5"), 3)
def test_unary_minus_in_expression(self):
self.assertEqual(calc("2*-3"), -6)
class TestDivision(unittest.TestCase):
"""D2 — true division and EvalError on div-by-zero."""
def test_true_division(self):
self.assertEqual(calc("7/2"), 3.5)
def test_division_by_zero_raises_eval_error(self):
with self.assertRaises(EvalError):
calc("1/0")
def test_division_by_zero_not_bare_exception(self):
try:
calc("1/0")
except EvalError:
pass
except ZeroDivisionError:
self.fail("ZeroDivisionError escaped — should have been EvalError")
class TestResultType(unittest.TestCase):
"""D3 — whole-valued floats return int, non-whole return float."""
def test_integer_division_returns_int(self):
result = calc("4/2")
self.assertEqual(result, 2)
self.assertIsInstance(result, int)
def test_non_integer_division_returns_float(self):
result = calc("7/2")
self.assertEqual(result, 3.5)
self.assertIsInstance(result, float)
def test_int_literal_stays_int(self):
result = calc("6")
self.assertIsInstance(result, int)
class TestCLI(unittest.TestCase):
"""D4 — CLI smoke tests."""
def _run(self, expr):
return subprocess.run(
[sys.executable, "calc.py", expr],
capture_output=True,
text=True,
cwd=__file__.rsplit("/calc/", 1)[0],
)
def test_cli_valid_expression(self):
r = self._run("2+3*4")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "14")
def test_cli_invalid_expression_stderr_nonzero(self):
r = self._run("1 +")
self.assertNotEqual(r.returncode, 0)
self.assertGreater(len(r.stderr.strip()), 0)
self.assertEqual(r.stdout.strip(), "")
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,89 @@
import unittest
from calc.lexer import tokenize, Token, LexError
def kinds(tokens):
return [t.kind for t in tokens]
def vals(tokens):
return [t.value for t in tokens]
class TestNumbers(unittest.TestCase):
def test_integer(self):
toks = tokenize("42")
self.assertEqual(kinds(toks), ['NUMBER', 'EOF'])
self.assertEqual(toks[0].value, 42)
self.assertIsInstance(toks[0].value, int)
def test_float(self):
toks = tokenize("3.14")
self.assertEqual(kinds(toks), ['NUMBER', 'EOF'])
self.assertAlmostEqual(toks[0].value, 3.14)
self.assertIsInstance(toks[0].value, float)
def test_float_leading_dot(self):
toks = tokenize(".5")
self.assertEqual(kinds(toks), ['NUMBER', 'EOF'])
self.assertAlmostEqual(toks[0].value, 0.5)
def test_float_trailing_dot(self):
toks = tokenize("10.")
self.assertEqual(kinds(toks), ['NUMBER', 'EOF'])
self.assertAlmostEqual(toks[0].value, 10.0)
class TestOperatorsAndParens(unittest.TestCase):
def test_operators(self):
toks = tokenize("1+2*3")
self.assertEqual(kinds(toks), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
def test_all_operators(self):
toks = tokenize("+-*/")
self.assertEqual(kinds(toks), ['PLUS', 'MINUS', 'STAR', 'SLASH', 'EOF'])
def test_parens(self):
toks = tokenize("()")
self.assertEqual(kinds(toks), ['LPAREN', 'RPAREN', 'EOF'])
def test_complex_expr(self):
toks = tokenize("3.5*(1-2)")
self.assertEqual(kinds(toks), ['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'])
self.assertAlmostEqual(toks[0].value, 3.5)
self.assertEqual(toks[3].value, 1)
self.assertEqual(toks[5].value, 2)
class TestWhitespaceAndErrors(unittest.TestCase):
def test_whitespace_skipped(self):
toks = tokenize(" 12 + 3 ")
self.assertEqual(kinds(toks), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
self.assertEqual(toks[0].value, 12)
self.assertEqual(toks[2].value, 3)
def test_tab_skipped(self):
toks = tokenize("1\t+\t2")
self.assertEqual(kinds(toks), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
def test_invalid_at_raises(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
self.assertIn('@', str(ctx.exception))
def test_invalid_dollar_raises(self):
with self.assertRaises(LexError):
tokenize("$")
def test_invalid_letter_raises(self):
with self.assertRaises(LexError):
tokenize("x")
def test_invalid_position_in_message(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
self.assertIn('2', str(ctx.exception)) # position 2
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,164 @@
"""Tests for calc.parser — asserts on AST structure, not evaluation."""
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_add_then_mul(self):
# 1+2*3 → BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
self.assertEqual(
p("1+2*3"),
BinOp("+", Num(1), BinOp("*", Num(2), Num(3))),
)
def test_mul_then_add(self):
# 2*3+1 → BinOp('+', BinOp('*', Num(2), Num(3)), Num(1))
self.assertEqual(
p("2*3+1"),
BinOp("+", BinOp("*", Num(2), Num(3)), Num(1)),
)
def test_sub_then_div(self):
# 10-6/3 → BinOp('-', Num(10), BinOp('/', Num(6), Num(3)))
self.assertEqual(
p("10-6/3"),
BinOp("-", Num(10), BinOp("/", Num(6), Num(3))),
)
def test_mul_and_div_same_precedence_left(self):
# 4*3/2 → BinOp('/', BinOp('*', Num(4), Num(3)), Num(2))
self.assertEqual(
p("4*3/2"),
BinOp("/", BinOp("*", Num(4), Num(3)), Num(2)),
)
class TestAssociativity(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))
self.assertEqual(
p("8-3-2"),
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))
self.assertEqual(
p("8/4/2"),
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))
self.assertEqual(
p("1+2+3"),
BinOp("+", BinOp("+", Num(1), Num(2)), Num(3)),
)
def test_mul_left_assoc(self):
# 2*3*4 → BinOp('*', BinOp('*', Num(2), Num(3)), Num(4))
self.assertEqual(
p("2*3*4"),
BinOp("*", BinOp("*", Num(2), Num(3)), Num(4)),
)
class TestParentheses(unittest.TestCase):
"""D3 — parens override precedence."""
def test_parens_force_add_under_mul(self):
# (1+2)*3 → BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
self.assertEqual(
p("(1+2)*3"),
BinOp("*", BinOp("+", Num(1), Num(2)), Num(3)),
)
def test_nested_parens(self):
# ((2+3)) → BinOp('+', Num(2), Num(3))
self.assertEqual(p("((2+3))"), BinOp("+", Num(2), Num(3)))
def test_parens_right_side(self):
# 3*(1+2) → BinOp('*', Num(3), BinOp('+', Num(1), Num(2)))
self.assertEqual(
p("3*(1+2)"),
BinOp("*", Num(3), BinOp("+", Num(1), Num(2))),
)
class TestUnaryMinus(unittest.TestCase):
"""D4 — leading and nested unary minus."""
def test_leading_unary(self):
# -5 → Unary('-', Num(5))
self.assertEqual(p("-5"), Unary("-", Num(5)))
def test_unary_in_parens(self):
# -(1+2) → Unary('-', BinOp('+', Num(1), Num(2)))
self.assertEqual(
p("-(1+2)"),
Unary("-", BinOp("+", Num(1), Num(2))),
)
def test_unary_right_operand(self):
# 3 * -2 → BinOp('*', Num(3), Unary('-', Num(2)))
self.assertEqual(
p("3 * -2"),
BinOp("*", Num(3), Unary("-", Num(2))),
)
def test_double_unary(self):
# --5 → Unary('-', Unary('-', Num(5)))
self.assertEqual(p("--5"), Unary("-", Unary("-", Num(5))))
def test_unary_in_addition(self):
# 1 + -2 → BinOp('+', Num(1), Unary('-', Num(2)))
self.assertEqual(
p("1 + -2"),
BinOp("+", Num(1), Unary("-", Num(2))),
)
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_two_numbers_no_op(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("*")
def test_mismatched_parens_extra_close(self):
with self.assertRaises(ParseError):
p("(1+2))")
if __name__ == "__main__":
unittest.main()