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,36 @@
from __future__ import annotations
from calc.parser import Node, Num, BinOp, Unary
class EvalError(Exception):
pass
def evaluate(node: Node) -> int | float:
"""Walk an AST and return its numeric value.
Uses true division (7/2 → 3.5). Division by zero raises EvalError.
Integer operands with integer-only operations (+ - *) return int;
any division always returns float. The CLI formats whole floats as int.
"""
if isinstance(node, Num):
return node.value
if isinstance(node, Unary):
if node.op == '-':
return -evaluate(node.operand)
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}")

View File

@ -0,0 +1,54 @@
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 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.isdigit() or ch == '.':
j = i
while j < n and src[j].isdigit():
j += 1
if j < n and src[j] == '.':
j += 1
while j < n and src[j].isdigit():
j += 1
tokens.append(Token('NUMBER', float(src[i:j])))
else:
tokens.append(Token('NUMBER', int(src[i:j])))
i = j
continue
if ch == '+':
tokens.append(Token('PLUS', '+'))
elif ch == '-':
tokens.append(Token('MINUS', '-'))
elif ch == '*':
tokens.append(Token('STAR', '*'))
elif ch == '/':
tokens.append(Token('SLASH', '/'))
elif ch == '(':
tokens.append(Token('LPAREN', '('))
elif ch == ')':
tokens.append(Token('RPAREN', ')'))
else:
raise LexError(f"unexpected character {ch!r} at position {i}")
i += 1
tokens.append(Token('EOF', None))
return tokens

View File

@ -0,0 +1,118 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Union
from calc.lexer import Token
class ParseError(Exception):
pass
@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]
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}, 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 token list into an AST.
Raises ParseError on malformed input.
Node shapes: Num(value), BinOp(op, left, right), Unary(op, operand).
"""
return _Parser(tokens).parse()

View File

@ -0,0 +1,116 @@
import subprocess
import sys
import unittest
from calc.lexer import tokenize
from calc.parser import parse
from calc.evaluator import evaluate, EvalError
def ev(src: str) -> int | float:
return evaluate(parse(tokenize(src)))
class TestArithmetic(unittest.TestCase):
"""D1 — basic arithmetic, precedence, parens, unary minus."""
def test_add_mul_precedence(self):
self.assertEqual(ev("2+3*4"), 14)
def test_parens_override(self):
self.assertEqual(ev("(2+3)*4"), 20)
def test_left_assoc_subtraction(self):
self.assertEqual(ev("8-3-2"), 3)
def test_unary_minus_add(self):
self.assertEqual(ev("-2+5"), 3)
def test_unary_minus_in_mul(self):
self.assertEqual(ev("2*-3"), -6)
class TestDivision(unittest.TestCase):
"""D2 — true division and division-by-zero EvalError."""
def test_true_division(self):
self.assertAlmostEqual(ev("7/2"), 3.5)
def test_division_by_zero_raises_eval_error(self):
with self.assertRaises(EvalError):
ev("1/0")
def test_division_by_zero_not_bare_exception(self):
# must NOT raise ZeroDivisionError directly
try:
ev("1/0")
except EvalError:
pass
except ZeroDivisionError:
self.fail("ZeroDivisionError escaped the API; expected EvalError")
def test_division_by_zero_expr(self):
with self.assertRaises(EvalError):
ev("5/(3-3)")
class TestResultType(unittest.TestCase):
"""D3 — whole-valued results print as integers, non-whole as floats."""
def _cli(self, expr: str) -> str:
result = subprocess.run(
[sys.executable, "calc.py", expr],
capture_output=True, text=True,
)
self.assertEqual(result.returncode, 0, msg=result.stderr)
return result.stdout.strip()
def test_whole_division_prints_no_dot(self):
self.assertEqual(self._cli("4/2"), "2")
def test_non_whole_division_prints_decimal(self):
self.assertEqual(self._cli("7/2"), "3.5")
def test_integer_arithmetic_stays_int(self):
self.assertEqual(self._cli("2+3*4"), "14")
def test_negative_whole_float(self):
self.assertEqual(self._cli("-4/2"), "-2")
class TestCLI(unittest.TestCase):
"""D4 — CLI exits 0 on success, non-zero with stderr on error."""
def _run(self, expr: str):
return subprocess.run(
[sys.executable, "calc.py", expr],
capture_output=True, text=True,
)
def test_valid_expression_exits_zero(self):
r = self._run("2+3*4")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "14")
def test_valid_parens_exits_zero(self):
r = self._run("(2+3)*4")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "20")
def test_invalid_expression_exits_nonzero(self):
r = self._run("1 +")
self.assertNotEqual(r.returncode, 0)
self.assertTrue(r.stderr.strip(), "expected error on stderr")
def test_div_by_zero_exits_nonzero(self):
r = self._run("1/0")
self.assertNotEqual(r.returncode, 0)
self.assertTrue(r.stderr.strip())
def test_no_traceback_on_error(self):
r = self._run("1 +")
self.assertNotIn("Traceback", r.stderr)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,82 @@
import unittest
from calc.lexer import tokenize, Token, LexError
def kinds(src):
return [t.kind for t in tokenize(src)]
def tok(src):
return [(t.kind, t.value) for t in tokenize(src)]
class TestNumbers(unittest.TestCase):
def test_integer(self):
t = tokenize("42")
self.assertEqual(t[0], Token('NUMBER', 42))
self.assertIsInstance(t[0].value, int)
self.assertEqual(t[1].kind, 'EOF')
def test_float(self):
t = tokenize("3.14")
self.assertEqual(t[0], Token('NUMBER', 3.14))
self.assertIsInstance(t[0].value, float)
def test_leading_dot(self):
t = tokenize(".5")
self.assertAlmostEqual(t[0].value, 0.5)
self.assertIsInstance(t[0].value, float)
def test_trailing_dot(self):
t = tokenize("10.")
self.assertAlmostEqual(t[0].value, 10.0)
self.assertIsInstance(t[0].value, float)
class TestOperatorsAndParens(unittest.TestCase):
def test_all_operators(self):
self.assertEqual(kinds("+"), ['PLUS', 'EOF'])
self.assertEqual(kinds("-"), ['MINUS', 'EOF'])
self.assertEqual(kinds("*"), ['STAR', 'EOF'])
self.assertEqual(kinds("/"), ['SLASH', 'EOF'])
self.assertEqual(kinds("("), ['LPAREN', 'EOF'])
self.assertEqual(kinds(")"), ['RPAREN', 'EOF'])
def test_expression(self):
self.assertEqual(kinds("1+2*3"), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
class TestWhitespaceAndErrors(unittest.TestCase):
def test_whitespace_skipped(self):
self.assertEqual(kinds(" 12 + 3 "), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
def test_complex_expr(self):
result = tok("3.5*(1-2)")
self.assertEqual(result, [
('NUMBER', 3.5),
('STAR', '*'),
('LPAREN', '('),
('NUMBER', 1),
('MINUS', '-'),
('NUMBER', 2),
('RPAREN', ')'),
('EOF', None),
])
def test_lex_error_at_sign(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
self.assertIn('@', str(ctx.exception))
self.assertIn('2', str(ctx.exception)) # position 2
def test_lex_error_letter(self):
with self.assertRaises(LexError):
tokenize("1 + x")
def test_lex_error_dollar(self):
with self.assertRaises(LexError):
tokenize("$")
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,145 @@
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_mul(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_mul_add(self):
# 2*3+1 => BinOp('+', BinOp('*', Num(2), Num(3)), Num(1))
tree = p("2*3+1")
self.assertEqual(tree, BinOp('+', BinOp('*', Num(2), Num(3)), Num(1)))
def test_sub_div(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_sub(self):
# 3*4-1 => BinOp('-', BinOp('*', Num(3), Num(4)), Num(1))
tree = p("3*4-1")
self.assertEqual(tree, BinOp('-', BinOp('*', Num(3), Num(4)), Num(1)))
class TestLeftAssociativity(unittest.TestCase):
"""D2 — same-precedence operators associate left."""
def test_sub_left(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(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(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_mul_left(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 TestParentheses(unittest.TestCase):
"""D3 — parentheses override precedence."""
def test_parens_override_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_parens_nested(self):
# (2+(3*4)) => BinOp('+', Num(2), BinOp('*', Num(3), Num(4)))
tree = p("(2+(3*4))")
self.assertEqual(tree, BinOp('+', Num(2), BinOp('*', Num(3), Num(4))))
def test_parens_single_number(self):
# (5) => Num(5)
tree = p("(5)")
self.assertEqual(tree, Num(5))
def test_parens_force_right_assoc(self):
# 8-(3-2) => BinOp('-', Num(8), BinOp('-', Num(3), Num(2)))
tree = p("8-(3-2)")
self.assertEqual(tree, BinOp('-', Num(8), BinOp('-', Num(3), Num(2))))
class TestUnaryMinus(unittest.TestCase):
"""D4 — unary minus."""
def test_simple_unary(self):
# -5 => Unary('-', Num(5))
tree = p("-5")
self.assertEqual(tree, Unary('-', Num(5)))
def test_unary_paren(self):
# -(1+2) => Unary('-', BinOp('+', Num(1), Num(2)))
tree = p("-(1+2)")
self.assertEqual(tree, Unary('-', BinOp('+', Num(1), Num(2))))
def test_unary_in_mul(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))))
def test_unary_in_add(self):
# 1 + -2 => BinOp('+', Num(1), Unary('-', Num(2)))
tree = p("1 + -2")
self.assertEqual(tree, BinOp('+', Num(1), Unary('-', Num(2))))
class TestErrors(unittest.TestCase):
"""D5 — malformed input raises ParseError."""
def test_trailing_op(self):
with self.assertRaises(ParseError):
p("1 +")
def test_unclosed_paren(self):
with self.assertRaises(ParseError):
p("(1")
def test_two_numbers(self):
with self.assertRaises(ParseError):
p("1 2")
def test_close_open_paren(self):
with self.assertRaises(ParseError):
p(")(")
def test_empty_string(self):
with self.assertRaises(ParseError):
p("")
def test_just_op(self):
with self.assertRaises(ParseError):
p("+")
def test_mismatched_paren(self):
with self.assertRaises(ParseError):
p("(1+2")
if __name__ == "__main__":
unittest.main()