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,26 @@
from calc.parser import Num, BinOp, Unary
class EvalError(Exception):
pass
def evaluate(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)
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 node type: {type(node).__name__!r}")

View File

@ -0,0 +1,52 @@
from dataclasses import dataclass
from typing import Any
class LexError(Exception):
pass
@dataclass
class Token:
kind: str
value: Any
_OPERATORS = {
'+': 'PLUS',
'-': 'MINUS',
'*': 'STAR',
'/': 'SLASH',
'(': 'LPAREN',
')': 'RPAREN',
}
def tokenize(src: str) -> list:
tokens = []
i = 0
n = len(src)
while i < n:
ch = src[i]
if ch in ' \t':
i += 1
continue
if ch.isdigit() or ch == '.':
j = i
while j < n and (src[j].isdigit() or src[j] == '.'):
j += 1
raw = src[i:j]
try:
value = float(raw) if '.' in raw else int(raw)
except ValueError:
raise LexError(f"malformed number {raw!r} at position {i}")
tokens.append(Token('NUMBER', value))
i = j
continue
if ch in _OPERATORS:
tokens.append(Token(_OPERATORS[ch], ch))
i += 1
continue
raise LexError(f"unexpected character {ch!r} at position {i}")
tokens.append(Token('EOF', None))
return tokens

View File

@ -0,0 +1,121 @@
from dataclasses import dataclass
from typing import Any
from calc.lexer import Token
class ParseError(Exception):
pass
@dataclass
class Num:
value: Any
def __repr__(self):
return f"Num({self.value!r})"
@dataclass
class BinOp:
op: str
left: Any
right: Any
def __repr__(self):
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
@dataclass
class Unary:
op: str
operand: Any
def __repr__(self):
return f"Unary({self.op!r}, {self.operand!r})"
class _Parser:
def __init__(self, tokens: list):
self._tokens = tokens
self._pos = 0
def _peek(self) -> Token:
return self._tokens[self._pos]
def _consume(self, kind: str) -> Token:
tok = self._peek()
if tok.kind != kind:
raise ParseError(
f"expected {kind}, got {tok.kind!r} ({tok.value!r})"
)
self._pos += 1
return tok
def _advance(self) -> Token:
tok = self._tokens[self._pos]
self._pos += 1
return tok
def parse(self):
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):
# addition / subtraction — left-associative, lowest precedence
node = self._term()
while self._peek().kind in ('PLUS', 'MINUS'):
op = self._advance().value
right = self._term()
node = BinOp(op, node, right)
return node
def _term(self):
# multiplication / division — left-associative, higher precedence
node = self._unary()
while self._peek().kind in ('STAR', 'SLASH'):
op = self._advance().value
right = self._unary()
node = BinOp(op, node, right)
return node
def _unary(self):
if self._peek().kind == 'MINUS':
op = self._advance().value
operand = self._unary()
return Unary(op, operand)
return self._primary()
def _primary(self):
tok = self._peek()
if tok.kind == 'NUMBER':
self._advance()
return Num(tok.value)
if tok.kind == 'LPAREN':
self._advance()
node = self._expr()
self._consume('RPAREN')
return node
raise ParseError(
f"unexpected token {tok.kind!r} ({tok.value!r})"
)
def parse(tokens: list):
"""Parse a token list produced by calc.lexer.tokenize into an AST.
AST node types:
Num(value) — a numeric literal
BinOp(op, left, right) — binary +, -, *, /
Unary(op, operand) — unary -
Raises ParseError on malformed input.
"""
return _Parser(tokens).parse()

View File

@ -0,0 +1,126 @@
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):
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_paren_override_precedence(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)
def test_simple_add(self):
self.assertEqual(ev("1+2"), 3)
def test_simple_sub(self):
self.assertEqual(ev("5-3"), 2)
def test_simple_mul(self):
self.assertEqual(ev("3*4"), 12)
def test_nested_parens(self):
self.assertEqual(ev("((3+2))*2"), 10)
class TestDivision(unittest.TestCase):
# D2: true division, division by zero raises EvalError
def test_true_division(self):
self.assertAlmostEqual(ev("7/2"), 3.5)
def test_div_by_zero(self):
with self.assertRaises(EvalError):
ev("1/0")
def test_div_by_zero_expr(self):
with self.assertRaises(EvalError):
ev("5/(3-3)")
def test_no_bare_zerodivision(self):
try:
ev("1/0")
except EvalError:
pass
except ZeroDivisionError:
self.fail("ZeroDivisionError escaped the API — should be EvalError")
class TestResultType(unittest.TestCase):
# D3: whole-valued results → int-like, non-whole → float
def test_whole_division_is_int(self):
result = ev("4/2")
# 4/2 returns 2.0 as a float; CLI formats it as "2"
# The _fmt function in calc.py handles display; here we verify the value
self.assertEqual(result, 2)
def test_non_whole_is_float(self):
result = ev("7/2")
self.assertIsInstance(result, float)
self.assertAlmostEqual(result, 3.5)
def test_integer_arithmetic_stays_int(self):
result = ev("3+4")
self.assertIsInstance(result, int)
self.assertEqual(result, 7)
class TestCLI(unittest.TestCase):
# D4: CLI output and exit codes
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_basic_expression(self):
r = self._run("2+3*4")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "14")
def test_paren_expression(self):
r = self._run("(2+3)*4")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "20")
def test_true_division_output(self):
r = self._run("7/2")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "3.5")
def test_whole_division_no_dot(self):
r = self._run("4/2")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "2")
def test_div_by_zero_exits_nonzero(self):
r = self._run("1/0")
self.assertNotEqual(r.returncode, 0)
self.assertGreater(len(r.stderr.strip()), 0)
def test_invalid_expr_exits_nonzero(self):
r = self._run("1 +")
self.assertNotEqual(r.returncode, 0)
self.assertGreater(len(r.stderr.strip()), 0)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,132 @@
import unittest
from calc.lexer import tokenize, Token, LexError
def kinds(src):
return [t.kind for t in tokenize(src)]
def values(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], Token('NUMBER', 42))
self.assertEqual(toks[1], Token('EOF', None))
def test_float(self):
toks = tokenize("3.14")
self.assertEqual(toks[0], Token('NUMBER', 3.14))
self.assertEqual(toks[1], Token('EOF', None))
def test_leading_dot(self):
toks = tokenize(".5")
self.assertEqual(toks[0], Token('NUMBER', 0.5))
def test_trailing_dot(self):
toks = tokenize("10.")
self.assertEqual(toks[0], Token('NUMBER', 10.0))
def test_integer_value_type(self):
toks = tokenize("42")
self.assertIsInstance(toks[0].value, int)
def test_float_value_type(self):
toks = tokenize("3.14")
self.assertIsInstance(toks[0].value, float)
class TestOperatorsAndParens(unittest.TestCase):
def test_plus(self):
self.assertIn(Token('PLUS', '+'), tokenize("+"))
def test_minus(self):
self.assertIn(Token('MINUS', '-'), tokenize("-"))
def test_star(self):
self.assertIn(Token('STAR', '*'), tokenize("*"))
def test_slash(self):
self.assertIn(Token('SLASH', '/'), tokenize("/"))
def test_lparen(self):
self.assertIn(Token('LPAREN', '('), tokenize("("))
def test_rparen(self):
self.assertIn(Token('RPAREN', ')'), tokenize(")"))
def test_expression_kinds(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_spaces_between_tokens(self):
self.assertEqual(
kinds(" 12 + 3 "),
['NUMBER', 'PLUS', 'NUMBER', 'EOF'],
)
def test_tabs_skipped(self):
self.assertEqual(kinds("1\t+\t2"), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
def test_invalid_char_raises(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
self.assertIn('@', str(ctx.exception))
def test_dollar_raises(self):
with self.assertRaises(LexError):
tokenize("$")
def test_letter_raises(self):
with self.assertRaises(LexError):
tokenize("x")
def test_lex_error_position(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
self.assertIn('2', str(ctx.exception)) # position 2
class TestEndToEnd(unittest.TestCase):
def test_padded_addition(self):
v = values(" 12 + 3 ")
self.assertEqual(v, [('NUMBER', 12), ('PLUS', '+'), ('NUMBER', 3), ('EOF', None)])
def test_complex_with_values(self):
v = values("3.5*(1-2)")
self.assertEqual(v, [
('NUMBER', 3.5),
('STAR', '*'),
('LPAREN', '('),
('NUMBER', 1),
('MINUS', '-'),
('NUMBER', 2),
('RPAREN', ')'),
('EOF', None),
])
def test_eof_always_last(self):
for src in ["", "1", "1+2", "()"]:
toks = tokenize(src)
self.assertEqual(toks[-1].kind, 'EOF')
def test_empty_string(self):
toks = tokenize("")
self.assertEqual(toks, [Token('EOF', None)])
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,128 @@
import unittest
from calc.lexer import tokenize
from calc.parser import parse, ParseError, Num, BinOp, Unary
def p(src):
return parse(tokenize(src))
class TestPrecedence(unittest.TestCase):
# D1: * and / bind tighter than + and -
def test_add_mul_precedence(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_precedence(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_precedence(self):
# 6-4/2 => BinOp('-', Num(6), BinOp('/', Num(4), Num(2)))
tree = p("6-4/2")
self.assertEqual(tree, BinOp('-', Num(6), BinOp('/', Num(4), Num(2))))
class TestLeftAssociativity(unittest.TestCase):
# D2: same-precedence operators associate left
def test_subtraction_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_division_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_addition_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)))
def test_mul_left_assoc(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: parens override precedence
def test_paren_plus_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):
tree = p("((4))")
self.assertEqual(tree, Num(4))
def test_paren_changes_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):
tree = p("-5")
self.assertEqual(tree, Unary('-', Num(5)))
def test_unary_in_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_plus_expr(self):
# -1 + 2 => BinOp('+', Unary('-', Num(1)), Num(2))
tree = p("-1+2")
self.assertEqual(tree, BinOp('+', Unary('-', Num(1)), 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_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("*")
def test_mismatched_paren(self):
with self.assertRaises(ParseError):
p("(1+2")
if __name__ == "__main__":
unittest.main()