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,47 @@
"""Evaluator for the arithmetic AST produced by calc.parser."""
from __future__ import annotations
from calc.parser import BinOp, Num, Node, Unary
class EvalError(Exception):
"""Raised on a runtime evaluation error (e.g. division by zero)."""
def evaluate(node: Node) -> int | float:
"""Walk *node* and return its numeric value.
Result type rule: if the mathematical result is a whole number, return int;
otherwise return float. This guarantees '4/2' → 2 and '7/2' → 3.5.
Raises EvalError on division by zero.
"""
if isinstance(node, Num):
return node.value
if isinstance(node, Unary):
v = evaluate(node.operand)
return -v
if isinstance(node, BinOp):
left = evaluate(node.left)
right = evaluate(node.right)
if node.op == '+':
result = left + right
elif node.op == '-':
result = left - right
elif node.op == '*':
result = left * right
elif node.op == '/':
if right == 0:
raise EvalError("Division by zero")
result = left / right
else:
raise EvalError(f"Unknown operator {node.op!r}")
if isinstance(result, float) and result == int(result):
return int(result)
return result
raise EvalError(f"Unknown node type {type(node)!r}")

View File

@ -0,0 +1,67 @@
"""Lexer for arithmetic expressions."""
from dataclasses import dataclass
from typing import Union
class LexError(Exception):
"""Raised on an unrecognised character."""
@dataclass
class Token:
kind: str # NUMBER PLUS MINUS STAR SLASH LPAREN RPAREN EOF
value: Union[int, float, str, None]
_SINGLE = {
'+': 'PLUS',
'-': 'MINUS',
'*': 'STAR',
'/': 'SLASH',
'(': 'LPAREN',
')': 'RPAREN',
}
def tokenize(src: str) -> list:
"""Return a list of Token for *src*, ending with EOF."""
tokens = []
i = 0
n = len(src)
while i < n:
ch = src[i]
# Skip whitespace
if ch in ' \t\r\n':
i += 1
continue
# Number: integer or float (leading dot allowed, trailing dot allowed)
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]
if raw == '.':
raise LexError(f"Unexpected character '.' at position {i}")
value = float(raw) if has_dot else int(raw)
tokens.append(Token('NUMBER', value))
i = j
continue
# Single-character operators and parentheses
if ch in _SINGLE:
tokens.append(Token(_SINGLE[ch], ch))
i += 1
continue
# Anything else is an error
raise LexError(f"Unexpected character {ch!r} at position {i}")
tokens.append(Token('EOF', None))
return tokens

View File

@ -0,0 +1,143 @@
"""Recursive-descent parser for arithmetic expressions.
AST node types:
Num(value) -- a numeric literal (int or float)
BinOp(op, left, right) -- binary operation; op in ('+','-','*','/')
Unary(op, operand) -- unary operation; op == '-'
Grammar (precedence low → high):
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, tokenize
class ParseError(Exception):
"""Raised on syntactically invalid input."""
# ---------------------------------------------------------------------------
# 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, kind: str | None = None) -> Token:
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 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_tok = self._consume()
op = op_tok.value # '+' or '-'
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_tok = self._consume()
op = op_tok.value # '*' or '/'
right = self._unary()
node = BinOp(op, node, right)
return node
def _unary(self) -> Node:
if self._peek().kind == 'MINUS':
self._consume('MINUS')
operand = self._unary()
return Unary('-', operand)
return self._primary()
def _primary(self) -> Node:
tok = self._peek()
if tok.kind == 'NUMBER':
self._consume('NUMBER')
return Num(tok.value)
if tok.kind == 'LPAREN':
self._consume('LPAREN')
node = self._expr()
if self._peek().kind != 'RPAREN':
raise ParseError(
f"Expected ')' but got {self._peek().kind!r}"
)
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})"
)
def parse(tokens: list[Token]) -> Node:
"""Parse *tokens* (from lexer.tokenize) into an AST Node.
Raises ParseError on malformed input.
"""
return _Parser(tokens).parse()

View File

@ -0,0 +1,87 @@
"""Tests for calc.evaluator — covers D1, D2, D3."""
import unittest
from calc.lexer import tokenize
from calc.parser import parse
from calc.evaluator import EvalError, evaluate
def calc(s):
return evaluate(parse(tokenize(s)))
class TestArithmetic(unittest.TestCase):
"""D1 — arithmetic, precedence, parens, unary minus."""
def test_add(self):
self.assertEqual(calc("2+3"), 5)
def test_mul(self):
self.assertEqual(calc("3*4"), 12)
def test_precedence(self):
self.assertEqual(calc("2+3*4"), 14)
def test_parens(self):
self.assertEqual(calc("(2+3)*4"), 20)
def test_sub_left_assoc(self):
self.assertEqual(calc("8-3-2"), 3)
def test_unary_minus(self):
self.assertEqual(calc("-2+5"), 3)
def test_unary_minus_mul(self):
self.assertEqual(calc("2*-3"), -6)
def test_sub(self):
self.assertEqual(calc("10-3"), 7)
def test_nested_parens(self):
self.assertEqual(calc("((4))"), 4)
def test_unary_double(self):
self.assertEqual(calc("--5"), 5)
class TestDivision(unittest.TestCase):
"""D2 — true division, division by zero → EvalError."""
def test_true_division(self):
self.assertAlmostEqual(calc("7/2"), 3.5)
def test_division_by_zero(self):
with self.assertRaises(EvalError):
calc("1/0")
def test_division_by_zero_expr(self):
with self.assertRaises(EvalError):
calc("5/(3-3)")
class TestResultType(unittest.TestCase):
"""D3 — whole-valued results are int, non-whole are float."""
def test_whole_division_is_int(self):
result = calc("4/2")
self.assertEqual(result, 2)
self.assertIsInstance(result, int)
def test_non_whole_is_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")
self.assertIsInstance(result, int)
def test_whole_negative_is_int(self):
result = calc("6/2")
self.assertEqual(result, 3)
self.assertIsInstance(result, int)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,134 @@
"""Unit tests for calc.lexer — covers D1, D2, D3."""
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):
"""D1 — integers and floats."""
def test_integer(self):
toks = tokenize("42")
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)
self.assertIsInstance(toks[0].value, float)
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)
def test_integer_eof(self):
toks = tokenize("42")
self.assertEqual(kinds("42"), ['NUMBER', 'EOF'])
class TestOperatorsAndParens(unittest.TestCase):
"""D2 — operators and parentheses."""
def test_plus(self):
self.assertIn('PLUS', kinds("+"))
def test_minus(self):
self.assertIn('MINUS', kinds("-"))
def test_star(self):
self.assertIn('STAR', kinds("*"))
def test_slash(self):
self.assertIn('SLASH', kinds("/"))
def test_lparen(self):
self.assertIn('LPAREN', kinds("("))
def test_rparen(self):
self.assertIn('RPAREN', kinds(")"))
def test_expr_kinds(self):
self.assertEqual(
kinds("1+2*3"),
['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'],
)
def test_complex_expr(self):
self.assertEqual(
kinds("3.5*(1-2)"),
['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'],
)
class TestWhitespaceAndErrors(unittest.TestCase):
"""D3 — whitespace is skipped; invalid chars raise LexError."""
def test_whitespace_skipped(self):
self.assertEqual(
kinds(" 12 + 3 "),
['NUMBER', 'PLUS', 'NUMBER', 'EOF'],
)
def test_tab_whitespace(self):
self.assertEqual(kinds("1\t+\t2"), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
def test_at_raises_lexerror(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
self.assertIn('@', str(ctx.exception))
def test_dollar_raises_lexerror(self):
with self.assertRaises(LexError) as ctx:
tokenize("$")
self.assertIn('$', str(ctx.exception))
def test_letter_raises_lexerror(self):
with self.assertRaises(LexError) as ctx:
tokenize("x")
self.assertIn('x', str(ctx.exception))
def test_lexerror_includes_position(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
# position 2 (0-indexed) where '@' appears
self.assertIn('2', str(ctx.exception))
def test_required_whitespace_expr(self):
# " 12 + 3 " from the DoD
toks = tokenize(" 12 + 3 ")
self.assertEqual(toks[0].value, 12)
self.assertEqual(toks[2].value, 3)
def test_required_complex_expr(self):
# "3.5*(1-2)" from the DoD
toks = tokenize("3.5*(1-2)")
self.assertAlmostEqual(toks[0].value, 3.5)
self.assertEqual(toks[1].kind, 'STAR')
self.assertEqual(toks[2].kind, 'LPAREN')
self.assertEqual(toks[3].value, 1)
self.assertEqual(toks[4].kind, 'MINUS')
self.assertEqual(toks[5].value, 2)
self.assertEqual(toks[6].kind, 'RPAREN')
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,149 @@
"""Tests for calc/parser.py — D1 through D5."""
import unittest
from calc.lexer import tokenize
from calc.parser import parse, ParseError, Num, BinOp, Unary
def p(src: str):
"""Shorthand: tokenize + parse."""
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)))
tree = p("1+2*3")
self.assertEqual(tree, BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
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)))
def test_sub_then_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_div_then_sub(self):
# 6/2-1 → BinOp('-', BinOp('/', Num(6), Num(2)), Num(1))
tree = p("6/2-1")
self.assertEqual(tree, BinOp('-', BinOp('/', Num(6), Num(2)), 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_paren_overrides_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_paren_on_right(self):
# 3*(1+2) → BinOp('*', Num(3), BinOp('+', Num(1), Num(2)))
tree = p("3*(1+2)")
self.assertEqual(tree, BinOp('*', Num(3), BinOp('+', Num(1), Num(2))))
def test_nested_parens(self):
# ((4)) → Num(4)
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 — leading and nested unary minus."""
def test_simple_negative(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_mul_unary_rhs(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_expr(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_operator(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):
# ")(" has no valid parse
with self.assertRaises(ParseError):
p(")(")
def test_empty_string(self):
with self.assertRaises(ParseError):
p("")
def test_close_paren_only(self):
with self.assertRaises(ParseError):
p(")")
def test_only_operator(self):
with self.assertRaises(ParseError):
p("*")
if __name__ == "__main__":
unittest.main()