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,40 @@
"""AST evaluator for calc expressions.
evaluate(node) -> int | float
Result-type rule:
- Whole-valued results (including float 2.0) are returned/displayed as int.
- Non-whole results are returned as float.
Division by zero raises EvalError, not a bare ZeroDivisionError.
"""
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):
if node.op == "-":
return -evaluate(node.operand)
raise EvalError(f"unknown unary op {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")
result = left / right
return int(result) if result == int(result) else result
raise EvalError(f"unknown binary op {node.op!r}")
raise EvalError(f"unknown node type {type(node).__name__}")

View File

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

View File

@ -0,0 +1,116 @@
"""Recursive-descent parser for calc expressions.
AST node shapes:
Num(value) — numeric literal; value is int or float
BinOp(op, left, right) — binary op; op is one of '+' '-' '*' '/'
Unary(op, operand) — unary op; op is '-'
All nodes implement __repr__ for easy shape inspection.
Grammar (lowest → highest precedence):
expr : term (('+' | '-') term)*
term : unary (('*' | '/') unary)*
unary : '-' unary | primary
primary : NUMBER | '(' expr ')'
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Union
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]
def parse(tokens: list) -> Node:
"""Parse a token list into an AST. Raises ParseError on malformed input."""
p = _Parser(tokens)
tree = p.expr()
if p.current().kind != "EOF":
raise ParseError(f"unexpected token {p.current()!r} after expression")
return tree
class _Parser:
def __init__(self, tokens: list) -> None:
self._tokens = tokens
self._pos = 0
def current(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!r} but got {tok.kind!r} ({tok.value!r})"
)
self._pos += 1
return tok
def expr(self) -> Node:
node = self.term()
while self.current().kind in ("PLUS", "MINUS"):
op = self.consume().value
node = BinOp(op, node, self.term())
return node
def term(self) -> Node:
node = self.unary()
while self.current().kind in ("STAR", "SLASH"):
op = self.consume().value
node = BinOp(op, node, self.unary())
return node
def unary(self) -> Node:
if self.current().kind == "MINUS":
self.consume("MINUS")
return Unary("-", self.unary())
return self.primary()
def primary(self) -> Node:
tok = self.current()
if tok.kind == "NUMBER":
self.consume("NUMBER")
return Num(tok.value)
if tok.kind == "LPAREN":
self.consume("LPAREN")
node = self.expr()
if self.current().kind != "RPAREN":
raise ParseError("unclosed '(' — expected ')'")
self.consume("RPAREN")
return node
if tok.kind == "EOF":
raise ParseError("unexpected end of input")
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")

View File

@ -0,0 +1,100 @@
"""Tests for calc/evaluator.py — covers D1, D2, D3 gates."""
import unittest
import subprocess
import sys
from calc.lexer import tokenize
from calc.parser import parse
from calc.evaluator import evaluate, EvalError
def calc(s):
return evaluate(parse(tokenize(s)))
class TestArithmetic(unittest.TestCase):
"""D1 — arithmetic correctness."""
def test_addition_with_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_associative_subtraction(self):
self.assertEqual(calc("8-3-2"), 3)
def test_unary_minus(self):
self.assertEqual(calc("-2+5"), 3)
def test_unary_minus_before_mul(self):
self.assertEqual(calc("2*-3"), -6)
class TestDivision(unittest.TestCase):
"""D2 — true division and EvalError on 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_no_bare_zero_division_error(self):
try:
calc("1/0")
except EvalError:
pass
except ZeroDivisionError:
self.fail("ZeroDivisionError escaped the API — must be EvalError")
class TestResultType(unittest.TestCase):
"""D3 — whole-valued results as int, non-whole as float."""
def test_whole_division_returns_int(self):
result = calc("4/2")
self.assertEqual(result, 2)
self.assertIsInstance(result, int)
def test_non_whole_division_returns_float(self):
result = calc("7/2")
self.assertEqual(result, 3.5)
self.assertIsInstance(result, float)
def test_integer_arithmetic_stays_int(self):
result = calc("2+3*4")
self.assertIsInstance(result, int)
class TestCLI(unittest.TestCase):
"""D4 — CLI exit codes and output."""
def _run(self, expr):
return subprocess.run(
[sys.executable, "calc.py", expr],
capture_output=True,
text=True,
cwd="/tmp/ao-solo-ssWwR6/r4/work",
)
def test_valid_expression_exit_zero(self):
proc = self._run("2+3*4")
self.assertEqual(proc.returncode, 0)
self.assertEqual(proc.stdout.strip(), "14")
def test_invalid_expression_exit_nonzero(self):
proc = self._run("1 +")
self.assertNotEqual(proc.returncode, 0)
self.assertEqual(proc.stdout, "")
self.assertGreater(len(proc.stderr.strip()), 0)
def test_division_by_zero_exit_nonzero(self):
proc = self._run("1/0")
self.assertNotEqual(proc.returncode, 0)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,93 @@
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].kind, 'NUMBER')
self.assertEqual(toks[0].value, 42)
self.assertIsInstance(toks[0].value, int)
self.assertEqual(toks[1].kind, 'EOF')
def test_float(self):
toks = tokenize("3.14")
self.assertEqual(toks[0].kind, 'NUMBER')
self.assertAlmostEqual(toks[0].value, 3.14)
self.assertIsInstance(toks[0].value, float)
def test_float_leading_dot(self):
toks = tokenize(".5")
self.assertEqual(toks[0].kind, 'NUMBER')
self.assertAlmostEqual(toks[0].value, 0.5)
def test_float_trailing_dot(self):
toks = tokenize("10.")
self.assertEqual(toks[0].kind, 'NUMBER')
self.assertAlmostEqual(toks[0].value, 10.0)
self.assertIsInstance(toks[0].value, float)
class TestOperatorsAndParens(unittest.TestCase):
def test_simple_expression(self):
self.assertEqual(kinds("1+2*3"), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
def test_minus(self):
self.assertIn('MINUS', kinds("1-2"))
def test_slash(self):
self.assertIn('SLASH', kinds("4/2"))
def test_parens(self):
k = kinds("(1)")
self.assertEqual(k[0], 'LPAREN')
self.assertEqual(k[-2], 'RPAREN')
def test_complex_expr(self):
k = kinds("3.5*(1-2)")
self.assertEqual(k, ['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'])
class TestWhitespaceAndErrors(unittest.TestCase):
def test_whitespace_skipped(self):
k = kinds(" 12 + 3 ")
self.assertEqual(k, ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
def test_tab_whitespace(self):
k = kinds("1\t+\t2")
self.assertEqual(k, ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
def test_lex_error_at_sign(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
self.assertIn('@', str(ctx.exception))
def test_lex_error_dollar(self):
with self.assertRaises(LexError):
tokenize("$100")
def test_lex_error_letter(self):
with self.assertRaises(LexError):
tokenize("abc")
def test_lex_error_position_in_message(self):
try:
tokenize("1 @ 2")
self.fail("LexError not raised")
except LexError as e:
msg = str(e)
self.assertIn('@', msg)
self.assertIn('2', msg) # position 2
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,120 @@
"""Tests for calc/parser.py covering DoD gates D1D5."""
import unittest
from calc.lexer import tokenize
from calc.parser import parse, ParseError, Num, BinOp, Unary
def p(src: str):
"""Shorthand: tokenize then parse."""
return parse(tokenize(src))
class TestD1Precedence(unittest.TestCase):
def test_mul_binds_tighter_than_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_binds_tighter_than_sub(self):
# 9-6/2 => BinOp('-', Num(9), BinOp('/', Num(6), Num(2)))
tree = p("9-6/2")
self.assertEqual(tree, BinOp("-", Num(9), BinOp("/", Num(6), Num(2))))
def test_add_before_mul_different_shape(self):
# 1+2*3 must NOT parse as (1+2)*3
tree = p("1+2*3")
self.assertNotEqual(tree, BinOp("*", BinOp("+", Num(1), Num(2)), Num(3)))
class TestD2LeftAssociativity(unittest.TestCase):
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)))
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 TestD3Parentheses(unittest.TestCase):
def test_parens_override_precedence(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)) (extra parens transparent)
tree = p("((2+3))")
self.assertEqual(tree, BinOp("+", Num(2), Num(3)))
def test_parens_and_precedence_mixed(self):
# 2*(3+4*5) => BinOp('*', Num(2), BinOp('+', Num(3), BinOp('*', Num(4), Num(5))))
tree = p("2*(3+4*5)")
self.assertEqual(
tree,
BinOp("*", Num(2), BinOp("+", Num(3), BinOp("*", Num(4), Num(5)))),
)
class TestD4UnaryMinus(unittest.TestCase):
def test_leading_unary(self):
# -5 => Unary('-', Num(5))
tree = p("-5")
self.assertEqual(tree, Unary("-", Num(5)))
def test_unary_in_parens(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_after_binop(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 TestD5Errors(unittest.TestCase):
def _raises(self, src: str):
with self.assertRaises(ParseError, msg=f"expected ParseError for {src!r}"):
p(src)
def test_trailing_operator(self):
self._raises("1 +")
def test_unclosed_paren(self):
self._raises("(1")
def test_two_numbers_no_op(self):
self._raises("1 2")
def test_close_before_open(self):
self._raises(")(")
def test_empty_string(self):
self._raises("")
def test_open_close_no_expr(self):
# "()" should fail — no expression inside
self._raises("()")
if __name__ == "__main__":
unittest.main()