artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
0
calculators/builder-solo/run-03/calc/__init__.py
Normal file
0
calculators/builder-solo/run-03/calc/__init__.py
Normal file
39
calculators/builder-solo/run-03/calc/evaluator.py
Normal file
39
calculators/builder-solo/run-03/calc/evaluator.py
Normal file
@ -0,0 +1,39 @@
|
||||
from calc.parser import Num, Unary, BinOp, Node
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node: Node):
|
||||
"""Walk the AST and return an int or float.
|
||||
|
||||
Result-type rule: if the result is mathematically whole-valued it is
|
||||
returned as int; non-whole results are returned as float. This rule is
|
||||
applied after every operation so intermediate values are also normalised.
|
||||
"""
|
||||
if isinstance(node, Num):
|
||||
return _normalise(node.value)
|
||||
if isinstance(node, Unary):
|
||||
return _normalise(-evaluate(node.operand))
|
||||
if isinstance(node, BinOp):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
if node.op == '+':
|
||||
return _normalise(left + right)
|
||||
if node.op == '-':
|
||||
return _normalise(left - right)
|
||||
if node.op == '*':
|
||||
return _normalise(left * right)
|
||||
if node.op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
return _normalise(left / right)
|
||||
raise EvalError(f"unknown node type: {type(node).__name__}")
|
||||
|
||||
|
||||
def _normalise(value):
|
||||
"""Return int when value is whole-valued, float otherwise."""
|
||||
if isinstance(value, float) and value == int(value):
|
||||
return int(value)
|
||||
return value
|
||||
56
calculators/builder-solo/run-03/calc/lexer.py
Normal file
56
calculators/builder-solo/run-03/calc/lexer.py
Normal file
@ -0,0 +1,56 @@
|
||||
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.isdigit() or ch == '.':
|
||||
j = i
|
||||
has_dot = False
|
||||
while j < len(src) and (src[j].isdigit() or (src[j] == '.' and not has_dot)):
|
||||
if src[j] == '.':
|
||||
has_dot = True
|
||||
j += 1
|
||||
raw = src[i:j]
|
||||
value = float(raw) if has_dot else int(raw)
|
||||
tokens.append(Token('NUMBER', value))
|
||||
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
|
||||
140
calculators/builder-solo/run-03/calc/parser.py
Normal file
140
calculators/builder-solo/run-03/calc/parser.py
Normal file
@ -0,0 +1,140 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
from calc.lexer import Token
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Num:
|
||||
"""Leaf node: a numeric literal."""
|
||||
value: Union[int, float]
|
||||
|
||||
def __repr__(self):
|
||||
return f"Num({self.value!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
"""Unary operator node: op is '-', operand is the inner Node."""
|
||||
op: str
|
||||
operand: object
|
||||
|
||||
def __repr__(self):
|
||||
return f"Unary({self.op!r}, {self.operand!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
"""Binary operator node. op is one of '+', '-', '*', '/'.
|
||||
Precedence and associativity are encoded in the tree structure, not here.
|
||||
"""
|
||||
op: str
|
||||
left: object
|
||||
right: object
|
||||
|
||||
def __repr__(self):
|
||||
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
||||
|
||||
|
||||
Node = Union[Num, Unary, BinOp]
|
||||
|
||||
|
||||
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) -> 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
|
||||
|
||||
# Grammar (lowest to highest precedence):
|
||||
# expr -> term (('+' | '-') term)*
|
||||
# term -> unary (('*' | '/') unary)*
|
||||
# unary -> '-' unary | primary
|
||||
# primary-> NUMBER | '(' expr ')'
|
||||
|
||||
def _expr(self) -> Node:
|
||||
node = self._term()
|
||||
while self._peek().kind in ('PLUS', 'MINUS'):
|
||||
op_tok = self._advance()
|
||||
op = op_tok.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_tok = self._advance()
|
||||
op = op_tok.value
|
||||
right = self._unary()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
def _unary(self) -> Node:
|
||||
if self._peek().kind == 'MINUS':
|
||||
self._advance()
|
||||
operand = self._unary()
|
||||
return Unary('-', operand)
|
||||
return self._primary()
|
||||
|
||||
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()
|
||||
if self._peek().kind != 'RPAREN':
|
||||
raise ParseError(
|
||||
f"expected ')' but got {self._peek().kind!r}"
|
||||
)
|
||||
self._advance()
|
||||
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) -> Node:
|
||||
"""Parse a token list (from lexer.tokenize) into an AST Node.
|
||||
|
||||
AST node shapes:
|
||||
Num(value) — numeric literal
|
||||
Unary('-', operand) — unary negation
|
||||
BinOp(op, left, right) — binary operation; op in {'+','-','*','/'}
|
||||
|
||||
Raises ParseError on malformed input.
|
||||
"""
|
||||
return _Parser(tokens).parse()
|
||||
87
calculators/builder-solo/run-03/calc/test_evaluator.py
Normal file
87
calculators/builder-solo/run-03/calc/test_evaluator.py
Normal file
@ -0,0 +1,87 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse
|
||||
from calc.evaluator import evaluate, EvalError
|
||||
|
||||
|
||||
def calc(expr):
|
||||
return evaluate(parse(tokenize(expr)))
|
||||
|
||||
|
||||
class TestD1Arithmetic(unittest.TestCase):
|
||||
def test_addition(self):
|
||||
self.assertEqual(calc("1+2"), 3)
|
||||
|
||||
def test_precedence_mul_over_add(self):
|
||||
self.assertEqual(calc("2+3*4"), 14)
|
||||
|
||||
def test_parens_override_precedence(self):
|
||||
self.assertEqual(calc("(2+3)*4"), 20)
|
||||
|
||||
def test_left_assoc_subtraction(self):
|
||||
self.assertEqual(calc("8-3-2"), 3)
|
||||
|
||||
def test_unary_minus_at_start(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_minus_after_operator(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
def test_double_unary_minus(self):
|
||||
self.assertEqual(calc("--5"), 5)
|
||||
|
||||
def test_multiply(self):
|
||||
self.assertEqual(calc("3*4"), 12)
|
||||
|
||||
|
||||
class TestD2Division(unittest.TestCase):
|
||||
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_division_by_zero_not_bare_exception(self):
|
||||
"""EvalError (not ZeroDivisionError) must escape the API."""
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError must not escape evaluate()")
|
||||
|
||||
def test_expression_division_by_zero(self):
|
||||
with self.assertRaises(EvalError):
|
||||
calc("5/(3-3)")
|
||||
|
||||
|
||||
class TestD3ResultType(unittest.TestCase):
|
||||
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_int_arithmetic_stays_int(self):
|
||||
result = calc("3+4")
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
def test_float_literal_whole_normalised(self):
|
||||
result = calc("2.0+1")
|
||||
self.assertIsInstance(result, int)
|
||||
self.assertEqual(result, 3)
|
||||
|
||||
def test_result_type_str_no_dot(self):
|
||||
self.assertEqual(str(calc("4/2")), "2")
|
||||
|
||||
def test_result_type_str_with_decimal(self):
|
||||
self.assertEqual(str(calc("7/2")), "3.5")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
95
calculators/builder-solo/run-03/calc/test_lexer.py
Normal file
95
calculators/builder-solo/run-03/calc/test_lexer.py
Normal file
@ -0,0 +1,95 @@
|
||||
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[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_leading_dot(self):
|
||||
toks = tokenize(".5")
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(toks[0].value, 0.5)
|
||||
|
||||
def test_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_zero(self):
|
||||
toks = tokenize("0")
|
||||
self.assertEqual(toks[0].value, 0)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
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(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):
|
||||
self.assertEqual(kinds("3.5*(1-2)"),
|
||||
['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'])
|
||||
|
||||
def test_lex_error_at(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("$5")
|
||||
|
||||
def test_lex_error_letter(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("abc")
|
||||
|
||||
def test_lex_error_position_in_message(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
msg = str(ctx.exception)
|
||||
self.assertIn('2', msg) # position 2
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
151
calculators/builder-solo/run-03/calc/test_parser.py
Normal file
151
calculators/builder-solo/run-03/calc/test_parser.py
Normal file
@ -0,0 +1,151 @@
|
||||
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(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))))
|
||||
|
||||
|
||||
class TestLeftAssociativity(unittest.TestCase):
|
||||
"""D2 — same-precedence operators associate left."""
|
||||
|
||||
def test_sub_sub(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_div(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_add(self):
|
||||
tree = p("1+2+3")
|
||||
self.assertEqual(tree, BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_mul_mul(self):
|
||||
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_overrides(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("((2+3))")
|
||||
self.assertEqual(tree, BinOp('+', Num(2), Num(3)))
|
||||
|
||||
def test_paren_in_sum(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))))
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
"""D4 — leading and nested unary minus."""
|
||||
|
||||
def test_simple_unary(self):
|
||||
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(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):
|
||||
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_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_only_operator(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("*")
|
||||
|
||||
def test_unclosed_paren_complex(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("(1+2")
|
||||
|
||||
|
||||
class TestSimpleCases(unittest.TestCase):
|
||||
"""Basic sanity checks."""
|
||||
|
||||
def test_single_number(self):
|
||||
self.assertEqual(p("42"), Num(42))
|
||||
|
||||
def test_float(self):
|
||||
self.assertEqual(p("3.14"), Num(3.14))
|
||||
|
||||
def test_simple_add(self):
|
||||
self.assertEqual(p("1+2"), BinOp('+', Num(1), Num(2)))
|
||||
|
||||
def test_simple_sub(self):
|
||||
self.assertEqual(p("5-3"), BinOp('-', Num(5), Num(3)))
|
||||
|
||||
def test_simple_mul(self):
|
||||
self.assertEqual(p("4*2"), BinOp('*', Num(4), Num(2)))
|
||||
|
||||
def test_simple_div(self):
|
||||
self.assertEqual(p("8/2"), BinOp('/', Num(8), Num(2)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user