artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
@ -0,0 +1,42 @@
|
||||
"""Evaluator for arithmetic AST nodes produced by calc.parser."""
|
||||
|
||||
from calc.parser import Num, BinOp, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node) -> int | float:
|
||||
"""Walk the AST and return the numeric result.
|
||||
|
||||
Whole-valued floats are returned as int (e.g. 4/2 → 2, not 2.0).
|
||||
Division by zero raises EvalError.
|
||||
"""
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
operand = evaluate(node.operand)
|
||||
if node.op == "-":
|
||||
return -operand
|
||||
raise EvalError(f"unknown unary operator: {node.op!r}")
|
||||
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}")
|
||||
# Normalize: whole-valued float → int
|
||||
if isinstance(result, float) and result == int(result):
|
||||
return int(result)
|
||||
return result
|
||||
raise EvalError(f"unknown node type: {type(node).__name__}")
|
||||
60
calculators/builder-adversary-stateless/run-05/calc/lexer.py
Normal file
60
calculators/builder-adversary-stateless/run-05/calc/lexer.py
Normal file
@ -0,0 +1,60 @@
|
||||
"""Lexer for arithmetic calculator."""
|
||||
|
||||
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Token:
|
||||
__slots__ = ("kind", "value")
|
||||
|
||||
def __init__(self, kind: str, value):
|
||||
self.kind = kind
|
||||
self.value = value
|
||||
|
||||
def __repr__(self):
|
||||
return f"Token({self.kind}, {self.value!r})"
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, Token) and self.kind == other.kind and self.value == other.value
|
||||
|
||||
|
||||
_SINGLE = {
|
||||
"+": "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
|
||||
elif ch in _SINGLE:
|
||||
tokens.append(Token(_SINGLE[ch], ch))
|
||||
i += 1
|
||||
elif 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]
|
||||
try:
|
||||
value = float(raw) if has_dot else int(raw)
|
||||
except ValueError:
|
||||
raise LexError(f"invalid number literal {raw!r} at position {i}")
|
||||
tokens.append(Token("NUMBER", value))
|
||||
i = j
|
||||
else:
|
||||
raise LexError(f"unexpected character {ch!r} at position {i}")
|
||||
tokens.append(Token("EOF", None))
|
||||
return tokens
|
||||
144
calculators/builder-adversary-stateless/run-05/calc/parser.py
Normal file
144
calculators/builder-adversary-stateless/run-05/calc/parser.py
Normal file
@ -0,0 +1,144 @@
|
||||
"""Recursive-descent parser for arithmetic expressions.
|
||||
|
||||
AST nodes:
|
||||
Num(value) -- numeric literal (int or float)
|
||||
BinOp(op, left, right) -- binary op; op in {'+', '-', '*', '/'}
|
||||
Unary(op, operand) -- unary op; op == '-'
|
||||
|
||||
Grammar:
|
||||
expr → term (('+' | '-') term)*
|
||||
term → unary (('*' | '/') unary)*
|
||||
unary → '-' unary | primary
|
||||
primary → NUMBER | '(' expr ')'
|
||||
"""
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Num:
|
||||
__slots__ = ("value",)
|
||||
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def __repr__(self):
|
||||
return f"Num({self.value!r})"
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, Num) and self.value == other.value
|
||||
|
||||
|
||||
class BinOp:
|
||||
__slots__ = ("op", "left", "right")
|
||||
|
||||
def __init__(self, op, left, right):
|
||||
self.op = op
|
||||
self.left = left
|
||||
self.right = right
|
||||
|
||||
def __repr__(self):
|
||||
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
||||
|
||||
def __eq__(self, other):
|
||||
return (
|
||||
isinstance(other, BinOp)
|
||||
and self.op == other.op
|
||||
and self.left == other.left
|
||||
and self.right == other.right
|
||||
)
|
||||
|
||||
|
||||
class Unary:
|
||||
__slots__ = ("op", "operand")
|
||||
|
||||
def __init__(self, op, operand):
|
||||
self.op = op
|
||||
self.operand = operand
|
||||
|
||||
def __repr__(self):
|
||||
return f"Unary({self.op!r}, {self.operand!r})"
|
||||
|
||||
def __eq__(self, other):
|
||||
return (
|
||||
isinstance(other, Unary)
|
||||
and self.op == other.op
|
||||
and self.operand == other.operand
|
||||
)
|
||||
|
||||
|
||||
class _Parser:
|
||||
def __init__(self, tokens):
|
||||
self._tokens = tokens
|
||||
self._pos = 0
|
||||
|
||||
def _peek(self):
|
||||
return self._tokens[self._pos]
|
||||
|
||||
def _consume(self, kind=None):
|
||||
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):
|
||||
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 = self._term()
|
||||
while self._peek().kind in ("PLUS", "MINUS"):
|
||||
op = self._consume().value
|
||||
right = self._term()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
def _term(self):
|
||||
node = self._unary()
|
||||
while self._peek().kind in ("STAR", "SLASH"):
|
||||
op = self._consume().value
|
||||
right = self._unary()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
def _unary(self):
|
||||
if self._peek().kind == "MINUS":
|
||||
op = self._consume().value
|
||||
operand = self._unary()
|
||||
return Unary(op, operand)
|
||||
return self._primary()
|
||||
|
||||
def _primary(self):
|
||||
tok = self._peek()
|
||||
if tok.kind == "NUMBER":
|
||||
self._consume()
|
||||
return Num(tok.value)
|
||||
if tok.kind == "LPAREN":
|
||||
self._consume("LPAREN")
|
||||
node = self._expr()
|
||||
if self._peek().kind != "RPAREN":
|
||||
raise ParseError("unclosed parenthesis")
|
||||
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) -> object:
|
||||
"""Parse a token list (from tokenize()) into an AST node.
|
||||
|
||||
Raises ParseError on malformed input.
|
||||
"""
|
||||
return _Parser(tokens).parse()
|
||||
@ -0,0 +1,92 @@
|
||||
"""Tests for calc.evaluator — covers D1 (arithmetic), D2 (division/EvalError), D3 (result type)."""
|
||||
|
||||
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 — arithmetic: +, -, *, /, precedence, parens, unary minus."""
|
||||
|
||||
def test_add_mul_precedence(self):
|
||||
self.assertEqual(calc("2+3*4"), 14)
|
||||
|
||||
def test_parens(self):
|
||||
self.assertEqual(calc("(2+3)*4"), 20)
|
||||
|
||||
def test_left_assoc_subtract(self):
|
||||
self.assertEqual(calc("8-3-2"), 3)
|
||||
|
||||
def test_unary_minus_add(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_minus_mul(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
def test_simple_add(self):
|
||||
self.assertEqual(calc("1+2"), 3)
|
||||
|
||||
def test_simple_sub(self):
|
||||
self.assertEqual(calc("5-3"), 2)
|
||||
|
||||
def test_simple_mul(self):
|
||||
self.assertEqual(calc("3*4"), 12)
|
||||
|
||||
def test_nested_parens(self):
|
||||
self.assertEqual(calc("((2+3))"), 5)
|
||||
|
||||
|
||||
class TestDivision(unittest.TestCase):
|
||||
"""D2 — true division and EvalError on divide-by-zero."""
|
||||
|
||||
def test_true_division(self):
|
||||
self.assertEqual(calc("7/2"), 3.5)
|
||||
|
||||
def test_divide_by_zero_raises(self):
|
||||
with self.assertRaises(EvalError):
|
||||
calc("1/0")
|
||||
|
||||
def test_divide_by_zero_expression(self):
|
||||
with self.assertRaises(EvalError):
|
||||
calc("5/(2-2)")
|
||||
|
||||
def test_no_bare_zero_division_error(self):
|
||||
"""ZeroDivisionError must NOT escape the API."""
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError escaped — must be EvalError")
|
||||
|
||||
|
||||
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_division_is_float(self):
|
||||
result = calc("7/2")
|
||||
self.assertEqual(result, 3.5)
|
||||
self.assertIsInstance(result, float)
|
||||
|
||||
def test_integer_add_is_int(self):
|
||||
result = calc("2+3")
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
def test_integer_mul_is_int(self):
|
||||
result = calc("3*4")
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -0,0 +1,126 @@
|
||||
"""Tests for calc/lexer.py covering D1-D3."""
|
||||
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):
|
||||
result = tokenize("42")
|
||||
self.assertEqual(result, [Token("NUMBER", 42), Token("EOF", None)])
|
||||
self.assertIsInstance(result[0].value, int)
|
||||
|
||||
def test_float_standard(self):
|
||||
result = tokenize("3.14")
|
||||
self.assertEqual(len(result), 2)
|
||||
self.assertEqual(result[0].kind, "NUMBER")
|
||||
self.assertAlmostEqual(result[0].value, 3.14)
|
||||
self.assertIsInstance(result[0].value, float)
|
||||
|
||||
def test_float_leading_dot(self):
|
||||
result = tokenize(".5")
|
||||
self.assertEqual(result[0].kind, "NUMBER")
|
||||
self.assertAlmostEqual(result[0].value, 0.5)
|
||||
|
||||
def test_float_trailing_dot(self):
|
||||
result = tokenize("10.")
|
||||
self.assertEqual(result[0].kind, "NUMBER")
|
||||
self.assertAlmostEqual(result[0].value, 10.0)
|
||||
self.assertIsInstance(result[0].value, float)
|
||||
|
||||
def test_zero(self):
|
||||
result = tokenize("0")
|
||||
self.assertEqual(result[0], Token("NUMBER", 0))
|
||||
|
||||
|
||||
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_eof_last(self):
|
||||
result = tokenize("1+2")
|
||||
self.assertEqual(result[-1].kind, "EOF")
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def test_spaces_skipped(self):
|
||||
self.assertEqual(
|
||||
kinds(" 12 + 3 "),
|
||||
["NUMBER", "PLUS", "NUMBER", "EOF"],
|
||||
)
|
||||
result = tokenize(" 12 + 3 ")
|
||||
self.assertEqual(result[0].value, 12)
|
||||
self.assertEqual(result[2].value, 3)
|
||||
|
||||
def test_tabs_skipped(self):
|
||||
self.assertEqual(kinds("1\t+\t2"), ["NUMBER", "PLUS", "NUMBER", "EOF"])
|
||||
|
||||
def test_complex_expression(self):
|
||||
result = kv("3.5*(1-2)")
|
||||
self.assertEqual(
|
||||
result,
|
||||
[
|
||||
("NUMBER", 3.5),
|
||||
("STAR", "*"),
|
||||
("LPAREN", "("),
|
||||
("NUMBER", 1),
|
||||
("MINUS", "-"),
|
||||
("NUMBER", 2),
|
||||
("RPAREN", ")"),
|
||||
("EOF", None),
|
||||
],
|
||||
)
|
||||
|
||||
def test_at_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("1 @ 2")
|
||||
|
||||
def test_dollar_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$")
|
||||
|
||||
def test_letter_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("x")
|
||||
|
||||
def test_lex_error_message_has_char_and_pos(self):
|
||||
try:
|
||||
tokenize("1 @ 2")
|
||||
except LexError as e:
|
||||
self.assertIn("@", str(e))
|
||||
|
||||
def test_bare_dot_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize(".")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -0,0 +1,154 @@
|
||||
"""Tests for calc/parser.py — covers D1–D5."""
|
||||
import unittest
|
||||
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import BinOp, Num, ParseError, Unary, parse
|
||||
|
||||
|
||||
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)))
|
||||
self.assertEqual(p("1+2*3"), BinOp("+", Num(1), BinOp("*", Num(2), Num(3))))
|
||||
|
||||
def test_mul_add(self):
|
||||
# 2*3+4 → BinOp('+', BinOp('*', Num(2), Num(3)), Num(4))
|
||||
self.assertEqual(p("2*3+4"), BinOp("+", BinOp("*", Num(2), Num(3)), Num(4)))
|
||||
|
||||
def test_add_div(self):
|
||||
# 1+8/4 → BinOp('+', Num(1), BinOp('/', Num(8), Num(4)))
|
||||
self.assertEqual(p("1+8/4"), BinOp("+", Num(1), BinOp("/", Num(8), Num(4))))
|
||||
|
||||
def test_sub_mul(self):
|
||||
# 10-2*3 → BinOp('-', Num(10), BinOp('*', Num(2), Num(3)))
|
||||
self.assertEqual(
|
||||
p("10-2*3"), BinOp("-", Num(10), BinOp("*", Num(2), Num(3)))
|
||||
)
|
||||
|
||||
def test_single_number(self):
|
||||
self.assertEqual(p("42"), Num(42))
|
||||
|
||||
def test_single_float(self):
|
||||
self.assertEqual(p("3.14"), Num(3.14))
|
||||
|
||||
|
||||
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))
|
||||
self.assertEqual(
|
||||
p("8-3-2"), BinOp("-", BinOp("-", Num(8), Num(3)), Num(2))
|
||||
)
|
||||
|
||||
def test_div_div(self):
|
||||
# 8/4/2 → BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))
|
||||
self.assertEqual(
|
||||
p("8/4/2"), BinOp("/", BinOp("/", Num(8), Num(4)), Num(2))
|
||||
)
|
||||
|
||||
def test_add_add(self):
|
||||
# 1+2+3 → BinOp('+', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
self.assertEqual(
|
||||
p("1+2+3"), BinOp("+", BinOp("+", Num(1), Num(2)), Num(3))
|
||||
)
|
||||
|
||||
def test_mul_mul(self):
|
||||
# 2*3*4 → BinOp('*', BinOp('*', Num(2), Num(3)), Num(4))
|
||||
self.assertEqual(
|
||||
p("2*3*4"), BinOp("*", BinOp("*", Num(2), Num(3)), Num(4))
|
||||
)
|
||||
|
||||
|
||||
class TestParentheses(unittest.TestCase):
|
||||
"""D3 — parentheses override precedence."""
|
||||
|
||||
def test_parens_override_mul(self):
|
||||
# (1+2)*3 → BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
self.assertEqual(
|
||||
p("(1+2)*3"), BinOp("*", BinOp("+", Num(1), Num(2)), Num(3))
|
||||
)
|
||||
|
||||
def test_nested_parens(self):
|
||||
# ((1+2)) → BinOp('+', Num(1), Num(2))
|
||||
self.assertEqual(p("((1+2))"), BinOp("+", Num(1), Num(2)))
|
||||
|
||||
def test_parens_inside_add(self):
|
||||
# 1+(2+3) → BinOp('+', Num(1), BinOp('+', Num(2), Num(3)))
|
||||
self.assertEqual(
|
||||
p("1+(2+3)"), BinOp("+", Num(1), BinOp("+", Num(2), Num(3)))
|
||||
)
|
||||
|
||||
def test_parens_alone(self):
|
||||
self.assertEqual(p("(5)"), Num(5))
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
"""D4 — unary minus."""
|
||||
|
||||
def test_leading_unary(self):
|
||||
# -5 → Unary('-', Num(5))
|
||||
self.assertEqual(p("-5"), Unary("-", Num(5)))
|
||||
|
||||
def test_unary_of_paren(self):
|
||||
# -(1+2) → Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
self.assertEqual(
|
||||
p("-(1+2)"), Unary("-", BinOp("+", Num(1), Num(2)))
|
||||
)
|
||||
|
||||
def test_mul_unary(self):
|
||||
# 3 * -2 → BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
self.assertEqual(
|
||||
p("3 * -2"), BinOp("*", Num(3), Unary("-", Num(2)))
|
||||
)
|
||||
|
||||
def test_double_unary(self):
|
||||
# --5 → Unary('-', Unary('-', Num(5)))
|
||||
self.assertEqual(p("--5"), Unary("-", Unary("-", Num(5))))
|
||||
|
||||
def test_unary_in_add(self):
|
||||
# 1 + -2 → BinOp('+', Num(1), Unary('-', Num(2)))
|
||||
self.assertEqual(
|
||||
p("1 + -2"), BinOp("+", Num(1), Unary("-", Num(2)))
|
||||
)
|
||||
|
||||
|
||||
class TestErrors(unittest.TestCase):
|
||||
"""D5 — malformed input raises ParseError."""
|
||||
|
||||
def _raises(self, src):
|
||||
with self.assertRaises(ParseError):
|
||||
p(src)
|
||||
|
||||
def test_trailing_op(self):
|
||||
self._raises("1 +")
|
||||
|
||||
def test_unclosed_paren(self):
|
||||
self._raises("(1")
|
||||
|
||||
def test_two_numbers(self):
|
||||
self._raises("1 2")
|
||||
|
||||
def test_close_before_open(self):
|
||||
self._raises(")(")
|
||||
|
||||
def test_empty(self):
|
||||
self._raises("")
|
||||
|
||||
def test_just_op(self):
|
||||
self._raises("*")
|
||||
|
||||
def test_mismatched_parens(self):
|
||||
self._raises("(1+2")
|
||||
|
||||
def test_extra_close(self):
|
||||
self._raises("(1+2))")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user