artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
33
calculators/builder-adversary/run-05/calc/evaluator.py
Normal file
33
calculators/builder-adversary/run-05/calc/evaluator.py
Normal file
@ -0,0 +1,33 @@
|
||||
from calc.parser import Num, BinOp, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node) -> "int | float":
|
||||
"""Walk the AST and return a numeric result.
|
||||
|
||||
Type rule: integer arithmetic stays int; division returns float, except when
|
||||
the quotient is whole-valued — then it is normalised to int so the CLI can
|
||||
print it without a trailing '.0'.
|
||||
"""
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
return -evaluate(node.operand)
|
||||
if isinstance(node, BinOp):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
if node.op == 'PLUS':
|
||||
return left + right
|
||||
if node.op == 'MINUS':
|
||||
return left - right
|
||||
if node.op == 'STAR':
|
||||
return left * right
|
||||
if node.op == 'SLASH':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
result = left / right
|
||||
return int(result) if result == int(result) else result
|
||||
raise EvalError(f"unknown node: {type(node).__name__}")
|
||||
56
calculators/builder-adversary/run-05/calc/lexer.py
Normal file
56
calculators/builder-adversary/run-05/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, None] = None
|
||||
|
||||
|
||||
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.isdigit() or ch == '.':
|
||||
j = i
|
||||
while j < n and src[j].isdigit():
|
||||
j += 1
|
||||
if j < n and src[j] == '.':
|
||||
j += 1
|
||||
while j < n and src[j].isdigit():
|
||||
j += 1
|
||||
tokens.append(Token('NUMBER', float(src[i:j])))
|
||||
else:
|
||||
tokens.append(Token('NUMBER', int(src[i:j])))
|
||||
i = j
|
||||
elif 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
|
||||
else:
|
||||
raise LexError(f"unexpected character {ch!r} at position {i}")
|
||||
tokens.append(Token('EOF'))
|
||||
return tokens
|
||||
104
calculators/builder-adversary/run-05/calc/parser.py
Normal file
104
calculators/builder-adversary/run-05/calc/parser.py
Normal file
@ -0,0 +1,104 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Num:
|
||||
value: Union[int, float]
|
||||
|
||||
def __repr__(self):
|
||||
return f"Num({self.value})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
op: str
|
||||
left: object
|
||||
right: object
|
||||
|
||||
def __repr__(self):
|
||||
return f"BinOp({self.op}, {self.left!r}, {self.right!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
op: str
|
||||
operand: object
|
||||
|
||||
def __repr__(self):
|
||||
return f"Unary({self.op}, {self.operand!r})"
|
||||
|
||||
|
||||
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!r}, got {tok.kind!r}")
|
||||
self.pos += 1
|
||||
return tok
|
||||
|
||||
def _expr(self):
|
||||
left = self._term()
|
||||
while self._peek().kind in ('PLUS', 'MINUS'):
|
||||
op = self._consume().kind
|
||||
right = self._term()
|
||||
left = BinOp(op, left, right)
|
||||
return left
|
||||
|
||||
def _term(self):
|
||||
left = self._unary()
|
||||
while self._peek().kind in ('STAR', 'SLASH'):
|
||||
op = self._consume().kind
|
||||
right = self._unary()
|
||||
left = BinOp(op, left, right)
|
||||
return left
|
||||
|
||||
def _unary(self):
|
||||
if self._peek().kind == 'MINUS':
|
||||
self._consume()
|
||||
return Unary('MINUS', self._unary())
|
||||
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()
|
||||
node = self._expr()
|
||||
if self._peek().kind != 'RPAREN':
|
||||
raise ParseError(f"expected ')', got {self._peek().kind!r}")
|
||||
self._consume()
|
||||
return node
|
||||
raise ParseError(f"unexpected token {tok.kind!r}")
|
||||
|
||||
|
||||
def parse(tokens) -> object:
|
||||
"""Parse a token list into an AST.
|
||||
|
||||
Nodes:
|
||||
Num(value) — numeric literal (int or float)
|
||||
BinOp(op, left, right) — binary op; op in {'PLUS','MINUS','STAR','SLASH'}
|
||||
Unary(op, operand) — unary minus; op == 'MINUS'
|
||||
|
||||
Raises ParseError on malformed input.
|
||||
"""
|
||||
p = _Parser(tokens)
|
||||
if p._peek().kind == 'EOF':
|
||||
raise ParseError("empty input")
|
||||
node = p._expr()
|
||||
if p._peek().kind != 'EOF':
|
||||
raise ParseError(f"unexpected token {p._peek().kind!r} after expression")
|
||||
return node
|
||||
74
calculators/builder-adversary/run-05/calc/test_evaluator.py
Normal file
74
calculators/builder-adversary/run-05/calc/test_evaluator.py
Normal file
@ -0,0 +1,74 @@
|
||||
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):
|
||||
def test_add_mul_precedence(self):
|
||||
self.assertEqual(calc("2+3*4"), 14)
|
||||
|
||||
def test_paren_override(self):
|
||||
self.assertEqual(calc("(2+3)*4"), 20)
|
||||
|
||||
def test_left_assoc_sub(self):
|
||||
self.assertEqual(calc("8-3-2"), 3)
|
||||
|
||||
def test_unary_minus(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_in_mul(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
def test_add(self):
|
||||
self.assertEqual(calc("1+2"), 3)
|
||||
|
||||
def test_sub(self):
|
||||
self.assertEqual(calc("5-3"), 2)
|
||||
|
||||
def test_mul(self):
|
||||
self.assertEqual(calc("3*4"), 12)
|
||||
|
||||
|
||||
class TestDivision(unittest.TestCase):
|
||||
def test_true_division(self):
|
||||
self.assertEqual(calc("7/2"), 3.5)
|
||||
|
||||
def test_exact_division(self):
|
||||
self.assertEqual(calc("4/2"), 2)
|
||||
|
||||
def test_division_by_zero(self):
|
||||
with self.assertRaises(EvalError):
|
||||
calc("1/0")
|
||||
|
||||
def test_division_by_zero_not_bare(self):
|
||||
# Must raise EvalError, not the raw ZeroDivisionError
|
||||
try:
|
||||
calc("1/0")
|
||||
self.fail("expected EvalError")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("bare ZeroDivisionError escaped; must be EvalError")
|
||||
|
||||
|
||||
class TestResultType(unittest.TestCase):
|
||||
def test_int_arithmetic_stays_int(self):
|
||||
self.assertIsInstance(calc("2+3"), int)
|
||||
|
||||
def test_whole_division_returns_int(self):
|
||||
# 4/2 = 2.0 → normalised to int so fmt can omit '.0'
|
||||
self.assertIsInstance(calc("4/2"), int)
|
||||
self.assertEqual(calc("4/2"), 2)
|
||||
|
||||
def test_non_whole_division_returns_float(self):
|
||||
self.assertIsInstance(calc("7/2"), float)
|
||||
self.assertEqual(calc("7/2"), 3.5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
125
calculators/builder-adversary/run-05/calc/test_lexer.py
Normal file
125
calculators/builder-adversary/run-05/calc/test_lexer.py
Normal file
@ -0,0 +1,125 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize, Token, LexError
|
||||
|
||||
|
||||
def kinds(src):
|
||||
return [t.kind for t in tokenize(src)]
|
||||
|
||||
|
||||
def pairs(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")])
|
||||
|
||||
def test_float(self):
|
||||
result = tokenize("3.14")
|
||||
self.assertEqual(result[0], Token("NUMBER", 3.14))
|
||||
self.assertEqual(result[1], Token("EOF"))
|
||||
|
||||
def test_float_leading_dot(self):
|
||||
result = tokenize(".5")
|
||||
self.assertEqual(result[0], Token("NUMBER", 0.5))
|
||||
self.assertEqual(result[1], Token("EOF"))
|
||||
|
||||
def test_float_trailing_dot(self):
|
||||
result = tokenize("10.")
|
||||
self.assertEqual(result[0], Token("NUMBER", 10.0))
|
||||
self.assertEqual(result[1], Token("EOF"))
|
||||
|
||||
def test_number_value_int(self):
|
||||
result = tokenize("0")
|
||||
self.assertIsInstance(result[0].value, int)
|
||||
|
||||
def test_number_value_float(self):
|
||||
result = tokenize("3.14")
|
||||
self.assertIsInstance(result[0].value, float)
|
||||
|
||||
|
||||
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_expression_1_plus_2_times_3(self):
|
||||
self.assertEqual(
|
||||
kinds("1+2*3"),
|
||||
["NUMBER", "PLUS", "NUMBER", "STAR", "NUMBER", "EOF"],
|
||||
)
|
||||
|
||||
def test_all_operators(self):
|
||||
self.assertEqual(
|
||||
kinds("+-*/()"),
|
||||
["PLUS", "MINUS", "STAR", "SLASH", "LPAREN", "RPAREN", "EOF"],
|
||||
)
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def test_whitespace_between_tokens(self):
|
||||
result = tokenize(" 12 + 3 ")
|
||||
self.assertEqual(kinds(" 12 + 3 "), ["NUMBER", "PLUS", "NUMBER", "EOF"])
|
||||
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):
|
||||
self.assertEqual(
|
||||
pairs("3.5*(1-2)"),
|
||||
[
|
||||
("NUMBER", 3.5),
|
||||
("STAR", None),
|
||||
("LPAREN", None),
|
||||
("NUMBER", 1),
|
||||
("MINUS", None),
|
||||
("NUMBER", 2),
|
||||
("RPAREN", None),
|
||||
("EOF", None),
|
||||
],
|
||||
)
|
||||
|
||||
def test_invalid_at_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("1 @ 2")
|
||||
|
||||
def test_invalid_dollar_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$5")
|
||||
|
||||
def test_invalid_letter_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("x")
|
||||
|
||||
def test_lex_error_message_contains_char(self):
|
||||
try:
|
||||
tokenize("1 @ 2")
|
||||
except LexError as e:
|
||||
self.assertIn("@", str(e))
|
||||
|
||||
def test_lex_error_message_contains_position(self):
|
||||
try:
|
||||
tokenize("1 @ 2")
|
||||
except LexError as e:
|
||||
self.assertIn("2", str(e))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
104
calculators/builder-adversary/run-05/calc/test_parser.py
Normal file
104
calculators/builder-adversary/run-05/calc/test_parser.py
Normal file
@ -0,0 +1,104 @@
|
||||
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):
|
||||
def test_mul_over_add(self):
|
||||
# 1+2*3 → 1+(2*3)
|
||||
self.assertEqual(repr(p('1+2*3')),
|
||||
'BinOp(PLUS, Num(1), BinOp(STAR, Num(2), Num(3)))')
|
||||
|
||||
def test_div_over_sub(self):
|
||||
# 6-4/2 → 6-(4/2)
|
||||
self.assertEqual(repr(p('6-4/2')),
|
||||
'BinOp(MINUS, Num(6), BinOp(SLASH, Num(4), Num(2)))')
|
||||
|
||||
def test_mul_over_add_reversed(self):
|
||||
# 2*3+1 → (2*3)+1
|
||||
self.assertEqual(repr(p('2*3+1')),
|
||||
'BinOp(PLUS, BinOp(STAR, Num(2), Num(3)), Num(1))')
|
||||
|
||||
|
||||
class TestLeftAssociativity(unittest.TestCase):
|
||||
def test_subtraction_left(self):
|
||||
# 8-3-2 → (8-3)-2
|
||||
self.assertEqual(repr(p('8-3-2')),
|
||||
'BinOp(MINUS, BinOp(MINUS, Num(8), Num(3)), Num(2))')
|
||||
|
||||
def test_division_left(self):
|
||||
# 8/4/2 → (8/4)/2
|
||||
self.assertEqual(repr(p('8/4/2')),
|
||||
'BinOp(SLASH, BinOp(SLASH, Num(8), Num(4)), Num(2))')
|
||||
|
||||
def test_addition_left(self):
|
||||
# 1+2+3 → (1+2)+3
|
||||
self.assertEqual(repr(p('1+2+3')),
|
||||
'BinOp(PLUS, BinOp(PLUS, Num(1), Num(2)), Num(3))')
|
||||
|
||||
def test_mul_left(self):
|
||||
# 2*3*4 → (2*3)*4
|
||||
self.assertEqual(repr(p('2*3*4')),
|
||||
'BinOp(STAR, BinOp(STAR, Num(2), Num(3)), Num(4))')
|
||||
|
||||
|
||||
class TestParentheses(unittest.TestCase):
|
||||
def test_parens_override_precedence(self):
|
||||
# (1+2)*3 → STAR at top, PLUS inside
|
||||
self.assertEqual(repr(p('(1+2)*3')),
|
||||
'BinOp(STAR, BinOp(PLUS, Num(1), Num(2)), Num(3))')
|
||||
|
||||
def test_parens_on_right(self):
|
||||
# 3*(1+2)
|
||||
self.assertEqual(repr(p('3*(1+2)')),
|
||||
'BinOp(STAR, Num(3), BinOp(PLUS, Num(1), Num(2)))')
|
||||
|
||||
def test_nested_parens(self):
|
||||
self.assertEqual(repr(p('((2))')), 'Num(2)')
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
def test_leading_unary(self):
|
||||
self.assertEqual(repr(p('-5')), 'Unary(MINUS, Num(5))')
|
||||
|
||||
def test_unary_paren(self):
|
||||
self.assertEqual(repr(p('-(1+2)')),
|
||||
'Unary(MINUS, BinOp(PLUS, Num(1), Num(2)))')
|
||||
|
||||
def test_unary_in_mul(self):
|
||||
self.assertEqual(repr(p('3 * -2')),
|
||||
'BinOp(STAR, Num(3), Unary(MINUS, Num(2)))')
|
||||
|
||||
def test_double_unary(self):
|
||||
self.assertEqual(repr(p('--5')),
|
||||
'Unary(MINUS, Unary(MINUS, Num(5)))')
|
||||
|
||||
|
||||
class TestErrors(unittest.TestCase):
|
||||
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_consecutive_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('')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user