artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
"""Evaluator for the arithmetic AST produced by calc.parser.
|
||||
|
||||
evaluate(node) -> int | float
|
||||
|
||||
Whole-valued results are returned as int ("4/2" -> 2).
|
||||
Non-whole results are returned as float ("7/2" -> 3.5).
|
||||
Division by zero raises EvalError.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from calc.parser import Node, Num, BinOp, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _normalize(val: int | float) -> int | float:
|
||||
"""Return int if val is a whole-valued float, otherwise unchanged."""
|
||||
if isinstance(val, float) and val.is_integer():
|
||||
return int(val)
|
||||
return val
|
||||
|
||||
|
||||
def evaluate(node: Node) -> int | float:
|
||||
"""Walk an AST node and return its numeric value."""
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, BinOp):
|
||||
l = evaluate(node.left)
|
||||
r = evaluate(node.right)
|
||||
if node.op == '+':
|
||||
return _normalize(l + r)
|
||||
if node.op == '-':
|
||||
return _normalize(l - r)
|
||||
if node.op == '*':
|
||||
return _normalize(l * r)
|
||||
if node.op == '/':
|
||||
if r == 0:
|
||||
raise EvalError("division by zero")
|
||||
return _normalize(l / r)
|
||||
raise EvalError(f"unknown operator {node.op!r}")
|
||||
if isinstance(node, Unary):
|
||||
val = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return _normalize(-val)
|
||||
raise EvalError(f"unknown unary operator {node.op!r}")
|
||||
raise EvalError(f"unknown AST node type {type(node).__name__!r}")
|
||||
@@ -0,0 +1,45 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import List
|
||||
|
||||
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Token:
|
||||
kind: str
|
||||
value: object
|
||||
|
||||
|
||||
_SINGLE = {'+': 'PLUS', '-': 'MINUS', '*': 'STAR', '/': 'SLASH',
|
||||
'(': 'LPAREN', ')': 'RPAREN'}
|
||||
|
||||
|
||||
def tokenize(src: str) -> List[Token]:
|
||||
tokens: List[Token] = []
|
||||
i = 0
|
||||
while i < len(src):
|
||||
ch = src[i]
|
||||
if ch in ' \t\n\r':
|
||||
i += 1
|
||||
continue
|
||||
if ch.isdigit() or ch == '.':
|
||||
j = i
|
||||
while j < len(src) 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"invalid number literal {raw!r} at position {i}")
|
||||
tokens.append(Token('NUMBER', value))
|
||||
i = j
|
||||
continue
|
||||
if ch in _SINGLE:
|
||||
tokens.append(Token(_SINGLE[ch], ch))
|
||||
i += 1
|
||||
continue
|
||||
raise LexError(f"unexpected character {ch!r} at position {i}")
|
||||
tokens.append(Token('EOF', None))
|
||||
return tokens
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Recursive-descent parser for arithmetic expressions.
|
||||
|
||||
Grammar (precedence low → high):
|
||||
expr ::= term (('+' | '-') term)*
|
||||
term ::= unary (('*' | '/') unary)*
|
||||
unary ::= '-' unary | primary
|
||||
primary::= NUMBER | '(' expr ')'
|
||||
|
||||
AST node shapes:
|
||||
Num(value) – leaf; value is int or float
|
||||
BinOp(op, left, right) – op is '+', '-', '*', or '/'
|
||||
Unary(op, operand) – op is '-'
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Union
|
||||
|
||||
from calc.lexer import Token
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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) -> Token:
|
||||
tok = self._peek()
|
||||
if tok.kind != kind:
|
||||
raise ParseError(
|
||||
f"expected {kind!r} but got {tok.kind!r} (value={tok.value!r})"
|
||||
)
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def _advance(self) -> Token:
|
||||
tok = self._tokens[self._pos]
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
# expr ::= term (('+' | '-') term)*
|
||||
def _expr(self) -> Node:
|
||||
node = self._term()
|
||||
while self._peek().kind in ('PLUS', 'MINUS'):
|
||||
op_tok = self._advance()
|
||||
right = self._term()
|
||||
node = BinOp(op_tok.value, node, right)
|
||||
return node
|
||||
|
||||
# term ::= unary (('*' | '/') unary)*
|
||||
def _term(self) -> Node:
|
||||
node = self._unary()
|
||||
while self._peek().kind in ('STAR', 'SLASH'):
|
||||
op_tok = self._advance()
|
||||
right = self._unary()
|
||||
node = BinOp(op_tok.value, node, right)
|
||||
return node
|
||||
|
||||
# unary ::= '-' unary | primary
|
||||
def _unary(self) -> Node:
|
||||
if self._peek().kind == 'MINUS':
|
||||
op_tok = self._advance()
|
||||
return Unary(op_tok.value, self._unary())
|
||||
return self._primary()
|
||||
|
||||
# primary ::= NUMBER | '(' expr ')'
|
||||
def _primary(self) -> Node:
|
||||
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
|
||||
if tok.kind == 'EOF':
|
||||
raise ParseError("unexpected end of input")
|
||||
raise ParseError(f"unexpected token {tok.kind!r} (value={tok.value!r})")
|
||||
|
||||
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 after expression: {tok.kind!r} (value={tok.value!r})"
|
||||
)
|
||||
return node
|
||||
|
||||
|
||||
def parse(tokens: List[Token]) -> Node:
|
||||
"""Parse a token list produced by calc.lexer.tokenize into an AST."""
|
||||
return _Parser(tokens).parse()
|
||||
@@ -0,0 +1,90 @@
|
||||
import unittest
|
||||
|
||||
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 — basic arithmetic, precedence, parens, unary minus."""
|
||||
|
||||
def test_add_mul_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_prefix(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_minus_in_mul(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
def test_simple_add(self):
|
||||
self.assertEqual(calc("1+1"), 2)
|
||||
|
||||
def test_simple_sub(self):
|
||||
self.assertEqual(calc("10-4"), 6)
|
||||
|
||||
def test_nested_parens(self):
|
||||
self.assertEqual(calc("((3+2))*2"), 10)
|
||||
|
||||
|
||||
class TestDivision(unittest.TestCase):
|
||||
"""D2 — true division and division-by-zero."""
|
||||
|
||||
def test_true_division(self):
|
||||
self.assertAlmostEqual(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(self):
|
||||
"""ZeroDivisionError must NOT escape the API."""
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError escaped; should be wrapped in EvalError")
|
||||
|
||||
def test_expression_div_by_zero(self):
|
||||
with self.assertRaises(EvalError):
|
||||
calc("5/(3-3)")
|
||||
|
||||
|
||||
class TestResultType(unittest.TestCase):
|
||||
"""D3 — whole-valued results print without trailing .0."""
|
||||
|
||||
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.assertIsInstance(result, float)
|
||||
self.assertAlmostEqual(result, 3.5)
|
||||
|
||||
def test_integer_arithmetic_returns_int(self):
|
||||
result = calc("3+4")
|
||||
self.assertIsInstance(result, int)
|
||||
self.assertEqual(result, 7)
|
||||
|
||||
def test_str_no_trailing_dot_zero(self):
|
||||
self.assertEqual(str(calc("4/2")), "2")
|
||||
|
||||
def test_str_float_has_decimal(self):
|
||||
self.assertIn(".", str(calc("7/2")))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,103 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize, Token, LexError
|
||||
|
||||
|
||||
def kinds(src):
|
||||
return [t.kind for t in tokenize(src)]
|
||||
|
||||
|
||||
def kv(src):
|
||||
return [(t.kind, t.value) for t in tokenize(src)]
|
||||
|
||||
|
||||
class TestNumbers(unittest.TestCase):
|
||||
def test_integer(self):
|
||||
toks = tokenize("42")
|
||||
self.assertEqual(toks, [Token('NUMBER', 42), Token('EOF', None)])
|
||||
self.assertIsInstance(toks[0].value, int)
|
||||
|
||||
def test_float_standard(self):
|
||||
toks = tokenize("3.14")
|
||||
self.assertEqual(toks, [Token('NUMBER', 3.14), Token('EOF', None)])
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
def test_float_leading_dot(self):
|
||||
toks = tokenize(".5")
|
||||
self.assertAlmostEqual(toks[0].value, 0.5)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
def test_float_trailing_dot(self):
|
||||
toks = tokenize("10.")
|
||||
self.assertAlmostEqual(toks[0].value, 10.0)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
def test_zero(self):
|
||||
toks = tokenize("0")
|
||||
self.assertEqual(toks[0], Token('NUMBER', 0))
|
||||
self.assertIsInstance(toks[0].value, int)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_all_ops(self):
|
||||
self.assertEqual(kinds("+-*/()"), ['PLUS','MINUS','STAR','SLASH','LPAREN','RPAREN','EOF'])
|
||||
|
||||
def test_expression(self):
|
||||
self.assertEqual(kinds("1+2*3"), ['NUMBER','PLUS','NUMBER','STAR','NUMBER','EOF'])
|
||||
|
||||
def test_values_preserved(self):
|
||||
self.assertEqual([t.value for t in tokenize("1+2*3")], [1, '+', 2, '*', 3, None])
|
||||
|
||||
def test_parens(self):
|
||||
self.assertEqual(kinds("(1+2)"), ['LPAREN','NUMBER','PLUS','NUMBER','RPAREN','EOF'])
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def test_spaces_between(self):
|
||||
self.assertEqual(kinds(" 12 + 3 "), ['NUMBER','PLUS','NUMBER','EOF'])
|
||||
vals = [t.value for t in tokenize(" 12 + 3 ")]
|
||||
self.assertEqual(vals, [12, '+', 3, None])
|
||||
|
||||
def test_complex_expr(self):
|
||||
toks = tokenize("3.5*(1-2)")
|
||||
expected_kinds = ['NUMBER','STAR','LPAREN','NUMBER','MINUS','NUMBER','RPAREN','EOF']
|
||||
self.assertEqual([t.kind for t in toks], expected_kinds)
|
||||
self.assertAlmostEqual(toks[0].value, 3.5)
|
||||
|
||||
def test_tabs(self):
|
||||
self.assertEqual(kinds("1\t+\t2"), ['NUMBER','PLUS','NUMBER','EOF'])
|
||||
|
||||
def test_at_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("$5")
|
||||
|
||||
def test_letter_raises(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 x 2")
|
||||
self.assertIn('x', str(ctx.exception))
|
||||
|
||||
def test_error_position_in_message(self):
|
||||
try:
|
||||
tokenize("1 @ 2")
|
||||
except LexError as e:
|
||||
self.assertIn('2', str(e)) # position 2
|
||||
|
||||
def test_malformed_float_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("..")
|
||||
|
||||
def test_malformed_float_multiple_dots_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("1.2.3")
|
||||
|
||||
def test_bare_dot_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize(".")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Test suite for calc.parser — asserts on AST structure."""
|
||||
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)))
|
||||
tree = p("1+2*3")
|
||||
self.assertEqual(tree, 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))
|
||||
tree = p("2*3+1")
|
||||
self.assertEqual(tree, BinOp('+', BinOp('*', Num(2), Num(3)), Num(1)))
|
||||
|
||||
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_mul_and_div_chain(self):
|
||||
# 2+3*4-1 → BinOp('-', BinOp('+', Num(2), BinOp('*', Num(3), Num(4))), Num(1))
|
||||
tree = p("2+3*4-1")
|
||||
expected = BinOp('-', BinOp('+', Num(2), BinOp('*', Num(3), Num(4))), Num(1))
|
||||
self.assertEqual(tree, expected)
|
||||
|
||||
|
||||
class TestLeftAssociativity(unittest.TestCase):
|
||||
"""D2 — same-precedence operators are left-associative."""
|
||||
|
||||
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_overrides_div(self):
|
||||
# 6/(1+2) → BinOp('/', Num(6), BinOp('+', Num(1), Num(2)))
|
||||
tree = p("6/(1+2)")
|
||||
self.assertEqual(tree, BinOp('/', Num(6), BinOp('+', Num(1), Num(2))))
|
||||
|
||||
def test_nested_parens(self):
|
||||
# ((2+3)) → BinOp('+', Num(2), Num(3))
|
||||
tree = p("((2+3))")
|
||||
self.assertEqual(tree, BinOp('+', Num(2), Num(3)))
|
||||
|
||||
def test_paren_single_number(self):
|
||||
tree = p("(42)")
|
||||
self.assertEqual(tree, Num(42))
|
||||
|
||||
|
||||
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_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_mul_unary(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_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_parens(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("(1+2))")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user