artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
16
calculators/builder-adversary-min/run-01/GIT-LOG.txt
Normal file
16
calculators/builder-adversary-min/run-01/GIT-LOG.txt
Normal file
@ -0,0 +1,16 @@
|
||||
# git history (claim/review handshake), from the run's shared bare repo
|
||||
931025b status(eval): DONE — all D1-D5 Adversary PASS @2026-06-15T02:05Z
|
||||
7631a17 review(eval): PASS D1,D2,D3,D4,D5 — cold-verified all gates
|
||||
d786616 status(eval): add commit sha to STATUS-eval.md
|
||||
74dddbc claim(D1,D2,D3,D4,D5): implement evaluator, CLI, and tests for phase eval
|
||||
69e3563 review(eval): init Adversary REVIEW file
|
||||
1b7bb57 status(parse): DONE — all D1-D6 Adversary PASS @2026-06-15T02:00Z
|
||||
6479762 review(parse): PASS D1,D2,D3,D4,D5,D6 — cold-verified all gates
|
||||
0bf6616 claim(D1,D2,D3,D4,D5,D6): implement parser with all gates for phase parse
|
||||
a819c33 review(parse): init Adversary REVIEW file
|
||||
12505f4 status: mark phase lex DONE — all D1-D4 Adversary PASS
|
||||
9b209c4 review(lex): PASS D1,D2,D3,D4 — cold-verified all gates
|
||||
3440210 status: claim(D1,D2,D3,D4) all gates for lex phase — lexer+tests complete
|
||||
bb84bf1 feat: implement lexer with tokenize() for phase lex (D1-D4)
|
||||
b4c14b0 review(lex): init adversary REVIEW file
|
||||
7bff854 chore: seed
|
||||
1
calculators/builder-adversary-min/run-01/README.md
Normal file
1
calculators/builder-adversary-min/run-01/README.md
Normal file
@ -0,0 +1 @@
|
||||
# calc work repo
|
||||
1
calculators/builder-adversary-min/run-01/SOURCE.txt
Normal file
1
calculators/builder-adversary-min/run-01/SOURCE.txt
Normal file
@ -0,0 +1 @@
|
||||
original path: /tmp/ao-campaign-Ofyz4E/builder-adversary-min/r1
|
||||
24
calculators/builder-adversary-min/run-01/calc.py
Normal file
24
calculators/builder-adversary-min/run-01/calc.py
Normal file
@ -0,0 +1,24 @@
|
||||
"""calc.py — CLI entry point: python calc.py "<expression>" """
|
||||
|
||||
import sys
|
||||
|
||||
from calc.evaluator import EvalError, evaluate
|
||||
from calc.lexer import LexError, tokenize
|
||||
from calc.parser import ParseError, parse
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: calc.py <expression>", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
expr = sys.argv[1]
|
||||
try:
|
||||
result = evaluate(parse(tokenize(expr)))
|
||||
except (LexError, ParseError, EvalError) as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print(result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
43
calculators/builder-adversary-min/run-01/calc/evaluator.py
Normal file
43
calculators/builder-adversary-min/run-01/calc/evaluator.py
Normal file
@ -0,0 +1,43 @@
|
||||
"""Evaluator for the calc AST.
|
||||
|
||||
Result type rule: if the result is a whole number, return int; otherwise return float.
|
||||
Division is always true division. Division by zero raises EvalError.
|
||||
"""
|
||||
|
||||
from calc.parser import Num, BinOp, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node) -> int | float:
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
val = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return _coerce(-val)
|
||||
raise EvalError(f"Unknown unary op: {node.op!r}")
|
||||
if isinstance(node, BinOp):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
if node.op == '+':
|
||||
return _coerce(left + right)
|
||||
if node.op == '-':
|
||||
return _coerce(left - right)
|
||||
if node.op == '*':
|
||||
return _coerce(left * right)
|
||||
if node.op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("Division by zero")
|
||||
return _coerce(left / right)
|
||||
raise EvalError(f"Unknown binary op: {node.op!r}")
|
||||
raise EvalError(f"Unknown node type: {type(node)!r}")
|
||||
|
||||
|
||||
def _coerce(val: int | float) -> int | float:
|
||||
"""Return int if val is whole-valued, otherwise float."""
|
||||
if isinstance(val, float) and val.is_integer():
|
||||
return int(val)
|
||||
return val
|
||||
62
calculators/builder-adversary-min/run-01/calc/lexer.py
Normal file
62
calculators/builder-adversary-min/run-01/calc/lexer.py
Normal file
@ -0,0 +1,62 @@
|
||||
"""Lexer for arithmetic expressions."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Token:
|
||||
kind: str
|
||||
value: Union[int, float, None]
|
||||
|
||||
def __repr__(self):
|
||||
return f"{self.kind}({self.value!r})"
|
||||
|
||||
|
||||
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 == '.' and i + 1 < len(src) and src[i + 1].isdigit()):
|
||||
j = i
|
||||
while j < len(src) and src[j].isdigit():
|
||||
j += 1
|
||||
if j < len(src) and src[j] == '.':
|
||||
j += 1
|
||||
while j < len(src) 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
|
||||
continue
|
||||
|
||||
if ch == '+':
|
||||
tokens.append(Token('PLUS', None))
|
||||
elif ch == '-':
|
||||
tokens.append(Token('MINUS', None))
|
||||
elif ch == '*':
|
||||
tokens.append(Token('STAR', None))
|
||||
elif ch == '/':
|
||||
tokens.append(Token('SLASH', None))
|
||||
elif ch == '(':
|
||||
tokens.append(Token('LPAREN', None))
|
||||
elif ch == ')':
|
||||
tokens.append(Token('RPAREN', None))
|
||||
else:
|
||||
raise LexError(f"Invalid character {ch!r} at position {i}")
|
||||
|
||||
i += 1
|
||||
|
||||
tokens.append(Token('EOF', None))
|
||||
return tokens
|
||||
113
calculators/builder-adversary-min/run-01/calc/parser.py
Normal file
113
calculators/builder-adversary-min/run-01/calc/parser.py
Normal file
@ -0,0 +1,113 @@
|
||||
"""Recursive-descent parser for arithmetic expressions.
|
||||
|
||||
AST node shapes:
|
||||
Num(value) — numeric literal; value is int or float
|
||||
BinOp(op, left, right) — binary op; op in {'+', '-', '*', '/'}
|
||||
Unary(op, operand) — unary op; op is '-'
|
||||
|
||||
Grammar (lowest to highest precedence):
|
||||
expr → term (('+' | '-') term)*
|
||||
term → unary (('*' | '/') unary)*
|
||||
unary → '-' unary | primary
|
||||
primary → NUMBER | '(' expr ')'
|
||||
"""
|
||||
|
||||
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!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
op: str
|
||||
left: object
|
||||
right: object
|
||||
|
||||
def __repr__(self):
|
||||
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
op: str
|
||||
operand: object
|
||||
|
||||
def __repr__(self):
|
||||
return f"Unary({self.op!r}, {self.operand!r})"
|
||||
|
||||
|
||||
Node = Union[Num, BinOp, Unary]
|
||||
|
||||
|
||||
def parse(tokens: list) -> Node:
|
||||
"""Parse a token list produced by tokenize() and return the AST root."""
|
||||
if not tokens:
|
||||
raise ParseError("Empty token list")
|
||||
p = _Parser(tokens)
|
||||
tree = p.expr()
|
||||
if p.current().kind != 'EOF':
|
||||
raise ParseError(f"Unexpected token {p.current()!r} after expression")
|
||||
return tree
|
||||
|
||||
|
||||
class _Parser:
|
||||
def __init__(self, tokens):
|
||||
self._tokens = tokens
|
||||
self._pos = 0
|
||||
|
||||
def current(self):
|
||||
return self._tokens[self._pos]
|
||||
|
||||
def consume(self, kind=None):
|
||||
tok = self.current()
|
||||
if kind is not None and tok.kind != kind:
|
||||
raise ParseError(f"Expected {kind!r}, got {tok!r}")
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def expr(self):
|
||||
left = self.term()
|
||||
while self.current().kind in ('PLUS', 'MINUS'):
|
||||
tok = self.consume()
|
||||
op = '+' if tok.kind == 'PLUS' else '-'
|
||||
right = self.term()
|
||||
left = BinOp(op, left, right)
|
||||
return left
|
||||
|
||||
def term(self):
|
||||
left = self.unary()
|
||||
while self.current().kind in ('STAR', 'SLASH'):
|
||||
tok = self.consume()
|
||||
op = '*' if tok.kind == 'STAR' else '/'
|
||||
right = self.unary()
|
||||
left = BinOp(op, left, right)
|
||||
return left
|
||||
|
||||
def unary(self):
|
||||
if self.current().kind == 'MINUS':
|
||||
self.consume()
|
||||
return Unary('-', self.unary())
|
||||
return self.primary()
|
||||
|
||||
def primary(self):
|
||||
tok = self.current()
|
||||
if tok.kind == 'NUMBER':
|
||||
self.consume()
|
||||
return Num(tok.value)
|
||||
if tok.kind == 'LPAREN':
|
||||
self.consume()
|
||||
node = self.expr()
|
||||
self.consume('RPAREN')
|
||||
return node
|
||||
raise ParseError(f"Unexpected token {tok!r}")
|
||||
@ -0,0 +1,98 @@
|
||||
"""Tests for calc/evaluator.py covering D1-D4."""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
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):
|
||||
def test_precedence(self):
|
||||
self.assertEqual(calc("2+3*4"), 14)
|
||||
|
||||
def test_parens(self):
|
||||
self.assertEqual(calc("(2+3)*4"), 20)
|
||||
|
||||
def test_left_associative_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)
|
||||
|
||||
|
||||
class TestDivision(unittest.TestCase):
|
||||
def test_true_division(self):
|
||||
self.assertEqual(calc("7/2"), 3.5)
|
||||
|
||||
def test_div_by_zero(self):
|
||||
with self.assertRaises(EvalError):
|
||||
calc("1/0")
|
||||
|
||||
|
||||
class TestResultType(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_returns_float(self):
|
||||
result = calc("7/2")
|
||||
self.assertIsInstance(result, float)
|
||||
|
||||
def test_addition_int(self):
|
||||
self.assertIsInstance(calc("1+2"), int)
|
||||
|
||||
|
||||
class TestCLI(unittest.TestCase):
|
||||
def _run(self, expr):
|
||||
return subprocess.run(
|
||||
[sys.executable, "calc.py", expr],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
def test_cli_basic(self):
|
||||
r = self._run("2+3*4")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "14")
|
||||
|
||||
def test_cli_parens(self):
|
||||
r = self._run("(2+3)*4")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "20")
|
||||
|
||||
def test_cli_float(self):
|
||||
r = self._run("7/2")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "3.5")
|
||||
|
||||
def test_cli_whole_float(self):
|
||||
r = self._run("4/2")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "2")
|
||||
|
||||
def test_cli_div_zero_error(self):
|
||||
r = self._run("1/0")
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertTrue(r.stderr.strip())
|
||||
self.assertNotIn("Traceback", r.stderr)
|
||||
|
||||
def test_cli_invalid_expr_error(self):
|
||||
r = self._run("1 +")
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertTrue(r.stderr.strip())
|
||||
self.assertNotIn("Traceback", r.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
88
calculators/builder-adversary-min/run-01/calc/test_lexer.py
Normal file
88
calculators/builder-adversary-min/run-01/calc/test_lexer.py
Normal file
@ -0,0 +1,88 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize, Token, LexError
|
||||
|
||||
|
||||
def kinds(src):
|
||||
return [t.kind for t in tokenize(src)]
|
||||
|
||||
|
||||
def tok(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[0], Token('NUMBER', 42))
|
||||
self.assertEqual(result[1].kind, 'EOF')
|
||||
self.assertIsInstance(result[0].value, int)
|
||||
|
||||
def test_float_standard(self):
|
||||
result = tokenize("3.14")
|
||||
self.assertAlmostEqual(result[0].value, 3.14)
|
||||
self.assertEqual(result[0].kind, 'NUMBER')
|
||||
|
||||
def test_float_leading_dot(self):
|
||||
result = tokenize(".5")
|
||||
self.assertAlmostEqual(result[0].value, 0.5)
|
||||
|
||||
def test_float_trailing_dot(self):
|
||||
result = tokenize("10.")
|
||||
self.assertAlmostEqual(result[0].value, 10.0)
|
||||
self.assertIsInstance(result[0].value, float)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_operators(self):
|
||||
self.assertEqual(kinds("1+2*3"), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_minus_slash(self):
|
||||
ks = kinds("4-2/1")
|
||||
self.assertIn('MINUS', ks)
|
||||
self.assertIn('SLASH', ks)
|
||||
|
||||
def test_parens(self):
|
||||
ks = kinds("(1)")
|
||||
self.assertIn('LPAREN', ks)
|
||||
self.assertIn('RPAREN', ks)
|
||||
|
||||
def test_complex_expr(self):
|
||||
result = tok("3.5*(1-2)")
|
||||
expected_kinds = ['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF']
|
||||
self.assertEqual([k for k, v in result], expected_kinds)
|
||||
self.assertAlmostEqual(result[0][1], 3.5)
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def test_whitespace_skipped(self):
|
||||
result = tok(" 12 + 3 ")
|
||||
self.assertEqual([k for k, v in result], ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
self.assertEqual(result[0][1], 12)
|
||||
self.assertEqual(result[2][1], 3)
|
||||
|
||||
def test_tab_whitespace(self):
|
||||
result = kinds("\t1\t+\t2\t")
|
||||
self.assertEqual(result, ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_at_raises_lex_error(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('@', str(ctx.exception))
|
||||
|
||||
def test_dollar_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$10")
|
||||
|
||||
def test_letter_raises_lex_error(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("abc")
|
||||
|
||||
def test_error_reports_position(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
msg = str(ctx.exception)
|
||||
self.assertIn('2', msg)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
93
calculators/builder-adversary-min/run-01/calc/test_parser.py
Normal file
93
calculators/builder-adversary-min/run-01/calc/test_parser.py
Normal file
@ -0,0 +1,93 @@
|
||||
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_mul_over_add(self):
|
||||
self.assertEqual(p('1+2*3'), BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
def test_mul_over_sub(self):
|
||||
self.assertEqual(p('1-2*3'), BinOp('-', Num(1), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
def test_div_over_add(self):
|
||||
self.assertEqual(p('4+6/2'), BinOp('+', Num(4), BinOp('/', Num(6), Num(2))))
|
||||
|
||||
|
||||
class TestLeftAssociativity(unittest.TestCase):
|
||||
"""D2 — same-precedence operators associate left."""
|
||||
|
||||
def test_sub_left(self):
|
||||
self.assertEqual(p('8-3-2'), BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)))
|
||||
|
||||
def test_div_left(self):
|
||||
self.assertEqual(p('8/4/2'), BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)))
|
||||
|
||||
def test_add_left(self):
|
||||
self.assertEqual(p('1+2+3'), BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_mul_left(self):
|
||||
self.assertEqual(p('2*3*4'), BinOp('*', BinOp('*', Num(2), Num(3)), Num(4)))
|
||||
|
||||
|
||||
class TestParentheses(unittest.TestCase):
|
||||
"""D3 — parens override precedence."""
|
||||
|
||||
def test_paren_overrides_precedence(self):
|
||||
self.assertEqual(p('(1+2)*3'), BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_nested_parens(self):
|
||||
self.assertEqual(p('((2+3))*4'), BinOp('*', BinOp('+', Num(2), Num(3)), Num(4)))
|
||||
|
||||
def test_paren_right_side(self):
|
||||
self.assertEqual(p('3*(1+2)'), BinOp('*', Num(3), BinOp('+', Num(1), Num(2))))
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
"""D4 — leading and nested unary minus."""
|
||||
|
||||
def test_unary_literal(self):
|
||||
self.assertEqual(p('-5'), Unary('-', Num(5)))
|
||||
|
||||
def test_unary_paren(self):
|
||||
self.assertEqual(p('-(1+2)'), Unary('-', BinOp('+', Num(1), Num(2))))
|
||||
|
||||
def test_unary_in_mul(self):
|
||||
self.assertEqual(p('3 * -2'), BinOp('*', Num(3), Unary('-', Num(2))))
|
||||
|
||||
def test_double_unary(self):
|
||||
self.assertEqual(p('--5'), Unary('-', Unary('-', Num(5))))
|
||||
|
||||
|
||||
class TestErrors(unittest.TestCase):
|
||||
"""D5 — malformed input raises ParseError."""
|
||||
|
||||
def test_trailing_op(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p('1 +')
|
||||
|
||||
def test_unclosed_paren(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p('(1')
|
||||
|
||||
def test_consecutive_numbers(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p('1 2')
|
||||
|
||||
def test_close_before_open(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p(')(')
|
||||
|
||||
def test_empty(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p('')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@ -0,0 +1,3 @@
|
||||
# BACKLOG-parse
|
||||
|
||||
(empty — all D1-D6 gates implemented and tested)
|
||||
@ -0,0 +1,9 @@
|
||||
# JOURNAL — phase eval
|
||||
|
||||
## Implementation notes
|
||||
|
||||
- `evaluate()` walks the AST recursively using isinstance checks on Num/BinOp/Unary.
|
||||
- `_coerce()` converts whole-valued floats to int (e.g. `4/2 → 2`).
|
||||
- Division by zero raises `EvalError` (not the bare `ZeroDivisionError`).
|
||||
- `calc.py` CLI catches `LexError`, `ParseError`, `EvalError` and prints to stderr with exit 1.
|
||||
- Test suite has 49 total tests (lex + parse + eval); CLI tests use subprocess to exercise the full pipeline end-to-end.
|
||||
@ -0,0 +1,12 @@
|
||||
# JOURNAL-lex
|
||||
|
||||
## Implementation notes
|
||||
|
||||
Built `calc/lexer.py` with:
|
||||
- `Token` dataclass with `kind: str` and `value: Union[int, float, None]`
|
||||
- `LexError(Exception)` for invalid characters
|
||||
- `tokenize(src: str) -> list[Token]` scanning character by character
|
||||
|
||||
Number scanning handles all three forms: integer (`42`), standard float (`3.14`), leading-dot float (`.5`), and trailing-dot float (`10.`). The key invariant: when `ch` is `.` we only enter number scanning if the next char is also a digit (to avoid confusing `.` used as an operator in other contexts). Trailing dot (`10.`) is handled because after scanning digits we check if the next char is `.` and absorb it into a float.
|
||||
|
||||
14 tests written covering D1-D4 plus edge cases.
|
||||
@ -0,0 +1,14 @@
|
||||
# JOURNAL-parse
|
||||
|
||||
## Implementation notes
|
||||
|
||||
Grammar chose iterative (not recursive) form for expr and term to ensure left-associativity without
|
||||
risk of right-fold bugs. Unary uses right-recursive call to handle `--5` naturally.
|
||||
|
||||
Empty string: `tokenize("")` returns `[Token('EOF', None)]`. `primary()` sees EOF and raises
|
||||
ParseError — no special-case needed.
|
||||
|
||||
`"1 2"` error: `parse()` checks that after `expr()` the current token is EOF; NUMBER is not EOF, so
|
||||
ParseError raised cleanly.
|
||||
|
||||
`")("` error: `primary()` is called, sees RPAREN (not NUMBER or LPAREN), raises ParseError.
|
||||
@ -0,0 +1,57 @@
|
||||
# Adversary REVIEW — phase eval
|
||||
|
||||
## Gates
|
||||
|
||||
- D1: PASS @2026-06-15T02:05Z
|
||||
- D2: PASS @2026-06-15T02:05Z
|
||||
- D3: PASS @2026-06-15T02:05Z
|
||||
- D4: PASS @2026-06-15T02:05Z
|
||||
- D5: PASS @2026-06-15T02:05Z
|
||||
|
||||
## Evidence
|
||||
|
||||
### D5 — full suite (49 tests, 0 failures)
|
||||
```
|
||||
Ran 49 tests in 0.218s
|
||||
OK
|
||||
```
|
||||
|
||||
### D1 — arithmetic / precedence / parens / unary minus
|
||||
```
|
||||
python calc.py "2+3*4" → 14 ✓
|
||||
python calc.py "(2+3)*4" → 20 ✓
|
||||
python calc.py "8-3-2" → 3 ✓
|
||||
python calc.py "-2+5" → 3 ✓
|
||||
python calc.py "2*-3" → -6 ✓
|
||||
```
|
||||
|
||||
### D2 — true division + EvalError on zero
|
||||
```
|
||||
python calc.py "7/2" → 3.5 (exit 0) ✓
|
||||
python calc.py "1/0" → Error: Division by zero (stderr, exit 1, no traceback) ✓
|
||||
python calc.py "0/0" → Error: Division by zero (stderr, exit 1) ✓
|
||||
```
|
||||
No bare ZeroDivisionError escapes; EvalError wraps it correctly.
|
||||
|
||||
### D3 — result type
|
||||
```
|
||||
python calc.py "4/2" → 2 (int, no trailing .0) ✓
|
||||
python calc.py "7/2" → 3.5 (float) ✓
|
||||
python calc.py "100/10"→ 10 (whole-valued) ✓
|
||||
python calc.py "1/3" → 0.3333333333333333 ✓
|
||||
```
|
||||
`_coerce()` correctly converts whole-valued floats to int.
|
||||
|
||||
### D4 — CLI
|
||||
```
|
||||
python calc.py "2+3*4" → stdout: 14, exit 0 ✓
|
||||
python calc.py "1 +" → stderr: Error: Unexpected token EOF(None), exit 1, no traceback ✓
|
||||
```
|
||||
|
||||
### Adversarial extras (all correct)
|
||||
- `(-2)*(-3)` → 6 ✓
|
||||
- `100/10` → 10 (no .0) ✓
|
||||
- `1/3` → 0.333... ✓
|
||||
- `0/0` → EvalError, exit 1 ✓
|
||||
|
||||
No regressions in lex or parse phases (49 tests = prior 39 + 10 new eval tests).
|
||||
@ -0,0 +1,34 @@
|
||||
# REVIEW-lex
|
||||
|
||||
Adversary review log for phase `lex`.
|
||||
|
||||
<!-- verdicts appended below -->
|
||||
|
||||
## review(lex): PASS — 2026-06-15T00:00:00Z
|
||||
|
||||
**Commit verified:** bb84bf1
|
||||
**Verified by:** Adversary (cold run, own clone)
|
||||
|
||||
### D1: PASS @2026-06-15T00:00:00Z
|
||||
- `tokenize("42")` → `[NUMBER(42), EOF]`, value is `int` ✓
|
||||
- `tokenize("3.14")` → `NUMBER(3.14)` as float ✓
|
||||
- `tokenize(".5")` → `NUMBER(0.5)` ✓ (leading-dot float branch correct)
|
||||
- `tokenize("10.")` → `NUMBER(10.0)` as float ✓ (trailing-dot float branch correct)
|
||||
|
||||
### D2: PASS @2026-06-15T00:00:00Z
|
||||
- `tokenize("1+2*3")` → `['NUMBER','PLUS','NUMBER','STAR','NUMBER','EOF']` ✓
|
||||
- All six operator/paren kinds recognized: `+ - * / ( )` ✓
|
||||
- `tokenize("3.5*(1-2)")` → `[('NUMBER',3.5),('STAR',None),('LPAREN',None),('NUMBER',1),('MINUS',None),('NUMBER',2),('RPAREN',None),('EOF',None)]` ✓
|
||||
|
||||
### D3: PASS @2026-06-15T00:00:00Z
|
||||
- `tokenize(" 12 + 3 ")` → `['NUMBER','PLUS','NUMBER','EOF']` ✓ (spaces/tabs skipped)
|
||||
- `tokenize("1 @ 2")` → `LexError: Invalid character '@' at position 2` ✓
|
||||
- `tokenize("abc")` → `LexError` ✓
|
||||
- `tokenize("$10")` → `LexError` ✓
|
||||
- Error message includes offending char and position ✓
|
||||
|
||||
### D4: PASS @2026-06-15T00:00:00Z
|
||||
- `python -m unittest -q` → 14 tests, 0 failures ✓
|
||||
- Required cases covered: `" 12 + 3 "`, `"3.5*(1-2)"`, `"1 @ 2"` raises `LexError` ✓
|
||||
|
||||
**All gates D1–D4: PASS. No vetoes.**
|
||||
@ -0,0 +1,52 @@
|
||||
# Adversary Review — phase `parse`
|
||||
|
||||
## Verdicts
|
||||
|
||||
| Gate | Result | Evidence |
|
||||
|------|--------|----------|
|
||||
| D1 | PASS | `parse(tokenize('1+2*3'))` → `BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))` |
|
||||
| D2 | PASS | `8-3-2` → `BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))`; `8/4/2` → `BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))` |
|
||||
| D3 | PASS | `(1+2)*3` → `BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))` |
|
||||
| D4 | PASS | `-5` → `Unary('-', Num(5))`; `-(1+2)` → `Unary('-', BinOp('+', ...))`; `3 * -2` → `BinOp('*', Num(3), Unary('-', Num(2)))`; `--5` → `Unary('-', Unary('-', Num(5)))` |
|
||||
| D5 | PASS | All 5 cases `'1 +'`, `'(1'`, `'1 2'`, `')('`, `''` raise `ParseError` (not any other exception) |
|
||||
| D6 | PASS | `python -m unittest -q` → `Ran 33 tests in 0.001s OK` |
|
||||
|
||||
---
|
||||
|
||||
## Cold-run commands executed
|
||||
|
||||
```
|
||||
python -m unittest -q
|
||||
python -c "... parse(tokenize('1+2*3'))" # D1
|
||||
python -c "... parse(tokenize('4+6/2'))" # D1
|
||||
python -c "... parse(tokenize('8-3-2'))" # D2
|
||||
python -c "... parse(tokenize('8/4/2'))" # D2
|
||||
python -c "... parse(tokenize('(1+2)*3'))" # D3
|
||||
python -c "... parse(tokenize('-5'))" # D4
|
||||
python -c "... parse(tokenize('-(1+2)'))" # D4
|
||||
python -c "... parse(tokenize('3 * -2'))" # D4
|
||||
python -c "... parse(tokenize('--5'))" # D4 extra
|
||||
python -c "... [all 5 error cases]" # D5
|
||||
```
|
||||
|
||||
Extra edge cases (adversarial):
|
||||
- `()` → ParseError ✓
|
||||
- `1++2` → ParseError ✓ (no unary plus)
|
||||
- `1 + + 2` → ParseError ✓
|
||||
- `*3` → ParseError ✓
|
||||
- `1*(2+3)*4` → `BinOp('*', BinOp('*', Num(1), BinOp('+', Num(2), Num(3))), Num(4))` ✓
|
||||
- `-1+2` → `BinOp('+', Unary('-', Num(1)), Num(2))` ✓
|
||||
- `1+2*3+4` → `BinOp('+', BinOp('+', Num(1), BinOp('*', Num(2), Num(3))), Num(4))` ✓
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- The `if not tokens: raise ParseError("Empty token list")` guard in `parse()` is **dead code** — `tokenize("")` always appends an EOF token so the list is never empty. The empty-string case still raises `ParseError` correctly via `primary()` seeing EOF. Not a bug; harmless dead code.
|
||||
- Grammar structure (expr → term → unary → primary) correctly encodes precedence and left-associativity by construction.
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
review(parse): PASS D1,D2,D3,D4,D5,D6 — cold-verified all gates @2026-06-15T02:00Z
|
||||
@ -0,0 +1,47 @@
|
||||
# STATUS — phase eval
|
||||
|
||||
## WHAT is claimed
|
||||
|
||||
All gates D1–D5 implemented and locally verified.
|
||||
|
||||
### Files added
|
||||
- `calc/evaluator.py` — `EvalError`, `evaluate(node) -> int | float`
|
||||
- `calc/test_evaluator.py` — unittest suite covering D1–D4 (CLI via subprocess)
|
||||
- `calc.py` — top-level CLI entry point
|
||||
|
||||
## Verify commands (exact) + expected results
|
||||
|
||||
```bash
|
||||
# D5 — whole suite (lex + parse + eval), 0 failures
|
||||
python -m unittest -q
|
||||
# Expected: OK (49 tests)
|
||||
|
||||
# D1 — arithmetic / precedence / parens / unary
|
||||
python calc.py "2+3*4" # Expected: 14
|
||||
python calc.py "(2+3)*4" # Expected: 20
|
||||
python calc.py "8-3-2" # Expected: 3
|
||||
python calc.py "-2+5" # Expected: 3
|
||||
python calc.py "2*-3" # Expected: -6
|
||||
|
||||
# D2 — true division + EvalError on zero
|
||||
python calc.py "7/2" # Expected: 3.5
|
||||
python calc.py "1/0" # Expected: error to stderr, exit non-zero, no Traceback
|
||||
|
||||
# D3 — result type
|
||||
python calc.py "4/2" # Expected: 2 (int, no trailing .0)
|
||||
python calc.py "7/2" # Expected: 3.5
|
||||
|
||||
# D4 — CLI
|
||||
python calc.py "2+3*4" # Expected stdout: 14, exit 0
|
||||
python calc.py "1 +" # Expected: error to stderr, exit non-zero, no Traceback
|
||||
```
|
||||
|
||||
## WHERE
|
||||
|
||||
Commit: `74dddbc37523257cd90f6f2d5a46fbd943c26e64`
|
||||
|
||||
- `calc/evaluator.py` — evaluator + EvalError
|
||||
- `calc/test_evaluator.py` — unittest suite (15 tests)
|
||||
- `calc.py` — CLI entry point
|
||||
|
||||
## DONE
|
||||
@ -0,0 +1,55 @@
|
||||
# STATUS-lex
|
||||
|
||||
## DONE
|
||||
|
||||
## Claimed gates: D1, D2, D3, D4
|
||||
|
||||
**Commit:** bb84bf1
|
||||
**Files:** `calc/lexer.py`, `calc/test_lexer.py`, `calc/__init__.py`
|
||||
|
||||
---
|
||||
|
||||
## Verify commands (exact, run from repo root)
|
||||
|
||||
```bash
|
||||
# D4 — tests green
|
||||
python -m unittest -q
|
||||
|
||||
# D1+D2 — complex expression with float, paren, operators
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"
|
||||
|
||||
# D3 — invalid character raises LexError
|
||||
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Expected results
|
||||
|
||||
### `python -m unittest -q`
|
||||
```
|
||||
..............
|
||||
----------------------------------------------------------------------
|
||||
Ran 14 tests in 0.000s
|
||||
|
||||
OK
|
||||
```
|
||||
|
||||
### `tokenize('3.5*(1-2)')`
|
||||
```
|
||||
[('NUMBER', 3.5), ('STAR', None), ('LPAREN', None), ('NUMBER', 1), ('MINUS', None), ('NUMBER', 2), ('RPAREN', None), ('EOF', None)]
|
||||
```
|
||||
|
||||
### `tokenize('1 @ 2')`
|
||||
Raises `LexError: Invalid character '@' at position 2`
|
||||
|
||||
---
|
||||
|
||||
## DoD mapping
|
||||
|
||||
| Gate | DoD item | How verified |
|
||||
|------|----------|-------------|
|
||||
| D1 | Integers (`42`) and floats (`3.14`, `.5`, `10.`) tokenize to `NUMBER` with correct numeric value | `test_integer`, `test_float_standard`, `test_float_leading_dot`, `test_float_trailing_dot` |
|
||||
| D2 | `+ - * / ( )` each tokenize to right kind; `1+2*3` → `NUMBER PLUS NUMBER STAR NUMBER EOF` | `test_operators`, `test_parens`, `test_complex_expr` |
|
||||
| D3 | Whitespace skipped; invalid char raises `LexError` with offending char and position | `test_whitespace_skipped`, `test_at_raises_lex_error`, `test_error_reports_position` |
|
||||
| D4 | `python -m unittest` passes: 14 tests, 0 failures, covers `" 12 + 3 "`, `"3.5*(1-2)"`, `"1 @ 2"` raises `LexError` | All tests in `calc/test_lexer.py` |
|
||||
@ -0,0 +1,94 @@
|
||||
# STATUS-parse
|
||||
|
||||
## DONE
|
||||
|
||||
## Claimed gates: D1, D2, D3, D4, D5, D6
|
||||
|
||||
**Commit:** (see git log — latest push on main)
|
||||
**Files:** `calc/parser.py`, `calc/test_parser.py`
|
||||
|
||||
---
|
||||
|
||||
## AST Node Shapes
|
||||
|
||||
```
|
||||
Num(value) — numeric literal; value is int or float
|
||||
BinOp(op, left, right) — binary op; op in {'+', '-', '*', '/'}
|
||||
Unary(op, operand) — unary op; op is '-'
|
||||
```
|
||||
|
||||
All nodes are Python `dataclass` instances with `__eq__` and `__repr__`.
|
||||
|
||||
---
|
||||
|
||||
## Verify commands (run from repo root)
|
||||
|
||||
### D6 — all tests green
|
||||
```bash
|
||||
python -m unittest -q
|
||||
# Expected: Ran 33 tests in X.XXXs OK (14 lex + 19 parser)
|
||||
```
|
||||
|
||||
### D1 — `*` binds tighter than `+`
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('1+2*3')))"
|
||||
# Expected: BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
```
|
||||
|
||||
### D2 — left associativity
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8-3-2')))"
|
||||
# Expected: BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8/4/2')))"
|
||||
# Expected: BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))
|
||||
```
|
||||
|
||||
### D3 — parentheses override precedence
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('(1+2)*3')))"
|
||||
# Expected: BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
```
|
||||
|
||||
### D4 — unary minus
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-5')))"
|
||||
# Expected: Unary('-', Num(5))
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-(1+2)')))"
|
||||
# Expected: Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('3 * -2')))"
|
||||
# Expected: BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
```
|
||||
|
||||
### D5 — errors raise ParseError
|
||||
```bash
|
||||
python -c "
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError
|
||||
cases = ['1 +', '(1', '1 2', ')(', '']
|
||||
for src in cases:
|
||||
try:
|
||||
parse(tokenize(src))
|
||||
print(f'FAIL {src!r}: no error raised')
|
||||
except ParseError as e:
|
||||
print(f'OK {src!r}: ParseError')
|
||||
except Exception as e:
|
||||
print(f'FAIL {src!r}: wrong exception {type(e).__name__}')
|
||||
"
|
||||
# Expected: OK for all 5 cases
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## DoD mapping
|
||||
|
||||
| Gate | DoD item | How verified |
|
||||
|------|----------|-------------|
|
||||
| D1 | `*`/`/` bind tighter than `+`/`-` | `1+2*3` → `BinOp('+', Num(1), BinOp('*', ...))` |
|
||||
| D2 | Same-precedence left-associative | `8-3-2` → left-nested; `8/4/2` → left-nested |
|
||||
| D3 | Parens override precedence | `(1+2)*3` → `BinOp('*', BinOp('+', ...), ...)` |
|
||||
| D4 | Unary minus (leading, nested, in mul) | `-5`, `-(1+2)`, `3 * -2` all parsed as Unary |
|
||||
| D5 | Malformed input raises ParseError | All 5 cases raise ParseError, not other exceptions |
|
||||
| D6 | 0 failures in `python -m unittest` | 33 tests OK (14 lex + 19 parser) |
|
||||
18
calculators/builder-adversary-min/run-02/GIT-LOG.txt
Normal file
18
calculators/builder-adversary-min/run-02/GIT-LOG.txt
Normal file
@ -0,0 +1,18 @@
|
||||
# git history (claim/review handshake), from the run's shared bare repo
|
||||
dc80d81 status(eval): DONE — all D1-D5 PASS per Adversary review
|
||||
0362cfe review(eval): PASS D1 D2 D3 D4 D5 — all gates verified at 6e385c9
|
||||
9e700d1 status(eval): correct commit sha to HEAD (b136909)
|
||||
b136909 claim(D1-D5): evaluator + CLI + tests — all gates implemented
|
||||
6e385c9 feat(eval): add evaluator, CLI, and test suite for D1-D5
|
||||
e8b6586 review(eval): adversary initialized — awaiting builder claims
|
||||
5bdd505 status(parse): DONE — all D1-D6 PASS per Adversary review
|
||||
9f535b7 status(parse): add commit sha to STATUS for Adversary cold-verify
|
||||
95263c9 review(parse): PASS D1 D2 D3 D4 D5 D6 — all gates verified at a05812d
|
||||
a05812d claim(D1-D6): add recursive-descent parser with full gate coverage
|
||||
7da805d review(parse): adversary initialized — awaiting builder claims
|
||||
43d39c3 status: phase lex DONE — all D1-D4 PASS per Adversary review
|
||||
fbf7093 review(lex): PASS D1 D2 D3 D4 — all gates verified at a1c68aa
|
||||
8a344c0 status: claim D1-D4 for phase lex — all gates verified locally
|
||||
a1c68aa feat: add calc lexer with tokenize(), Token, LexError — gates D1-D4
|
||||
5fd28bc review(lex): adversary initialized — awaiting builder claims
|
||||
0166d81 chore: seed
|
||||
1
calculators/builder-adversary-min/run-02/README.md
Normal file
1
calculators/builder-adversary-min/run-02/README.md
Normal file
@ -0,0 +1 @@
|
||||
# calc work repo
|
||||
1
calculators/builder-adversary-min/run-02/SOURCE.txt
Normal file
1
calculators/builder-adversary-min/run-02/SOURCE.txt
Normal file
@ -0,0 +1 @@
|
||||
original path: /tmp/ao-campaign-Ofyz4E/builder-adversary-min/r2
|
||||
24
calculators/builder-adversary-min/run-02/calc.py
Normal file
24
calculators/builder-adversary-min/run-02/calc.py
Normal file
@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
from calc.lexer import tokenize, LexError
|
||||
from calc.parser import parse, ParseError
|
||||
from calc.evaluator import evaluate, format_result, EvalError
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("usage: calc.py <expression>", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
expr = sys.argv[1]
|
||||
try:
|
||||
tokens = tokenize(expr)
|
||||
ast = parse(tokens)
|
||||
result = evaluate(ast)
|
||||
print(format_result(result))
|
||||
except (LexError, ParseError, EvalError) as e:
|
||||
print(f"error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
36
calculators/builder-adversary-min/run-02/calc/evaluator.py
Normal file
36
calculators/builder-adversary-min/run-02/calc/evaluator.py
Normal file
@ -0,0 +1,36 @@
|
||||
from calc.parser import Num, BinOp, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node) -> "int | float":
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
if node.op == '-':
|
||||
return -evaluate(node.operand)
|
||||
raise EvalError(f"unknown unary op: {node.op!r}")
|
||||
if isinstance(node, BinOp):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
if node.op == '+':
|
||||
return left + right
|
||||
if node.op == '-':
|
||||
return left - right
|
||||
if node.op == '*':
|
||||
return left * right
|
||||
if node.op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
return left / right
|
||||
raise EvalError(f"unknown binary op: {node.op!r}")
|
||||
raise EvalError(f"unknown node type: {type(node).__name__}")
|
||||
|
||||
|
||||
def format_result(value) -> str:
|
||||
"""Whole-valued results print without .0; non-whole as float."""
|
||||
if isinstance(value, float) and value == int(value):
|
||||
return str(int(value))
|
||||
return str(value)
|
||||
53
calculators/builder-adversary-min/run-02/calc/lexer.py
Normal file
53
calculators/builder-adversary-min/run-02/calc/lexer.py
Normal file
@ -0,0 +1,53 @@
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Token:
|
||||
def __init__(self, kind: str, value):
|
||||
self.kind = kind
|
||||
self.value = value
|
||||
|
||||
def __repr__(self):
|
||||
return f"{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
|
||||
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
|
||||
num_str = src[i:j]
|
||||
if num_str == '.':
|
||||
raise LexError(f"Invalid character '.' at position {i}")
|
||||
value = float(num_str) if has_dot else int(num_str)
|
||||
tokens.append(Token('NUMBER', value))
|
||||
i = j
|
||||
continue
|
||||
|
||||
if ch in _SINGLE:
|
||||
tokens.append(Token(_SINGLE[ch], ch))
|
||||
i += 1
|
||||
continue
|
||||
|
||||
raise LexError(f"Invalid character {ch!r} at position {i}")
|
||||
|
||||
tokens.append(Token('EOF', None))
|
||||
return tokens
|
||||
115
calculators/builder-adversary-min/run-02/calc/parser.py
Normal file
115
calculators/builder-adversary-min/run-02/calc/parser.py
Normal file
@ -0,0 +1,115 @@
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Num:
|
||||
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:
|
||||
def __init__(self, op: str, 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:
|
||||
def __init__(self, op: str, 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 _current(self):
|
||||
return self._tokens[self._pos]
|
||||
|
||||
def _advance(self):
|
||||
tok = self._tokens[self._pos]
|
||||
if tok.kind != 'EOF':
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def _expect(self, kind):
|
||||
tok = self._current()
|
||||
if tok.kind != kind:
|
||||
raise ParseError(f"expected {kind}, got {tok!r}")
|
||||
return self._advance()
|
||||
|
||||
def expr(self):
|
||||
left = self._term()
|
||||
while self._current().kind in ('PLUS', 'MINUS'):
|
||||
op = self._advance().value
|
||||
right = self._term()
|
||||
left = BinOp(op, left, right)
|
||||
return left
|
||||
|
||||
def _term(self):
|
||||
left = self._unary()
|
||||
while self._current().kind in ('STAR', 'SLASH'):
|
||||
op = self._advance().value
|
||||
right = self._unary()
|
||||
left = BinOp(op, left, right)
|
||||
return left
|
||||
|
||||
def _unary(self):
|
||||
if self._current().kind == 'MINUS':
|
||||
self._advance()
|
||||
operand = self._unary()
|
||||
return Unary('-', operand)
|
||||
return self._primary()
|
||||
|
||||
def _primary(self):
|
||||
tok = self._current()
|
||||
if tok.kind == 'NUMBER':
|
||||
self._advance()
|
||||
return Num(tok.value)
|
||||
if tok.kind == 'LPAREN':
|
||||
self._advance()
|
||||
node = self.expr()
|
||||
self._expect('RPAREN')
|
||||
return node
|
||||
raise ParseError(f"unexpected token {tok!r}")
|
||||
|
||||
|
||||
def parse(tokens) -> object:
|
||||
"""Parse a token list (from lexer.tokenize) into an AST.
|
||||
|
||||
Returns the root Node, one of:
|
||||
Num(value) — numeric literal
|
||||
BinOp(op, left, right) — binary + - * /
|
||||
Unary(op, operand) — unary -
|
||||
|
||||
Raises ParseError on malformed input.
|
||||
"""
|
||||
if not tokens or (len(tokens) == 1 and tokens[0].kind == 'EOF'):
|
||||
raise ParseError("empty input")
|
||||
p = _Parser(tokens)
|
||||
node = p.expr()
|
||||
if p._current().kind != 'EOF':
|
||||
raise ParseError(f"unexpected token after expression: {p._current()!r}")
|
||||
return node
|
||||
@ -0,0 +1,83 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse
|
||||
from calc.evaluator import EvalError, evaluate, format_result
|
||||
|
||||
|
||||
def calc(expr):
|
||||
return evaluate(parse(tokenize(expr)))
|
||||
|
||||
|
||||
class TestArithmetic(unittest.TestCase):
|
||||
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(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_minus_rhs(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
|
||||
class TestDivision(unittest.TestCase):
|
||||
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_not_bare(self):
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError escaped the API; should be EvalError")
|
||||
|
||||
|
||||
class TestResultType(unittest.TestCase):
|
||||
def test_whole_float_prints_as_int(self):
|
||||
self.assertEqual(format_result(calc("4/2")), "2")
|
||||
|
||||
def test_non_whole_prints_as_float(self):
|
||||
self.assertEqual(format_result(calc("7/2")), "3.5")
|
||||
|
||||
def test_integer_result(self):
|
||||
self.assertEqual(format_result(calc("2+3*4")), "14")
|
||||
|
||||
|
||||
class TestCLI(unittest.TestCase):
|
||||
def _run(self, expr):
|
||||
return subprocess.run(
|
||||
[sys.executable, "calc.py", expr],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
|
||||
def test_valid_expression(self):
|
||||
r = self._run("2+3*4")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "14")
|
||||
|
||||
def test_invalid_expression_stderr_nonzero(self):
|
||||
r = self._run("1 +")
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertTrue(r.stderr.strip(), "expected error message on stderr")
|
||||
|
||||
def test_division_by_zero_cli(self):
|
||||
r = self._run("1/0")
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertTrue(r.stderr.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
86
calculators/builder-adversary-min/run-02/calc/test_lexer.py
Normal file
86
calculators/builder-adversary-min/run-02/calc/test_lexer.py
Normal file
@ -0,0 +1,86 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize, Token, LexError
|
||||
|
||||
|
||||
def kinds(src):
|
||||
return [t.kind for t in tokenize(src)]
|
||||
|
||||
|
||||
class TestNumbers(unittest.TestCase):
|
||||
def test_integer(self):
|
||||
tokens = tokenize("42")
|
||||
self.assertEqual(tokens, [Token('NUMBER', 42), Token('EOF', None)])
|
||||
|
||||
def test_float(self):
|
||||
tokens = tokenize("3.14")
|
||||
self.assertEqual(tokens[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(tokens[0].value, 3.14)
|
||||
self.assertEqual(tokens[1].kind, 'EOF')
|
||||
|
||||
def test_leading_dot(self):
|
||||
tokens = tokenize(".5")
|
||||
self.assertEqual(tokens[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(tokens[0].value, 0.5)
|
||||
|
||||
def test_trailing_dot(self):
|
||||
tokens = tokenize("10.")
|
||||
self.assertEqual(tokens[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(tokens[0].value, 10.0)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_each_operator(self):
|
||||
self.assertEqual(kinds("+"), ['PLUS', 'EOF'])
|
||||
self.assertEqual(kinds("-"), ['MINUS', 'EOF'])
|
||||
self.assertEqual(kinds("*"), ['STAR', 'EOF'])
|
||||
self.assertEqual(kinds("/"), ['SLASH', 'EOF'])
|
||||
self.assertEqual(kinds("("), ['LPAREN', 'EOF'])
|
||||
self.assertEqual(kinds(")"), ['RPAREN', 'EOF'])
|
||||
|
||||
def test_expression_kinds(self):
|
||||
self.assertEqual(kinds("1+2*3"), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
|
||||
|
||||
|
||||
class TestWhitespace(unittest.TestCase):
|
||||
def test_spaces(self):
|
||||
tokens = tokenize(" 12 + 3 ")
|
||||
self.assertEqual([t.kind for t in tokens], ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
self.assertEqual(tokens[0].value, 12)
|
||||
self.assertEqual(tokens[2].value, 3)
|
||||
|
||||
def test_tabs(self):
|
||||
tokens = tokenize("1\t+\t2")
|
||||
self.assertEqual([t.kind for t in tokens], ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
|
||||
class TestErrors(unittest.TestCase):
|
||||
def test_at_sign_raises_lex_error(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
msg = str(ctx.exception)
|
||||
self.assertIn('@', msg)
|
||||
self.assertIn('2', msg) # position 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("abc")
|
||||
|
||||
|
||||
class TestComplex(unittest.TestCase):
|
||||
def test_float_expr_with_parens(self):
|
||||
tokens = tokenize("3.5*(1-2)")
|
||||
self.assertEqual(
|
||||
[t.kind for t in tokens],
|
||||
['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF']
|
||||
)
|
||||
self.assertAlmostEqual(tokens[0].value, 3.5)
|
||||
self.assertEqual(tokens[3].value, 1)
|
||||
self.assertEqual(tokens[5].value, 2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
91
calculators/builder-adversary-min/run-02/calc/test_parser.py
Normal file
91
calculators/builder-adversary-min/run-02/calc/test_parser.py
Normal file
@ -0,0 +1,91 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError, Num, BinOp, Unary
|
||||
|
||||
|
||||
def p(src):
|
||||
return parse(tokenize(src))
|
||||
|
||||
|
||||
class TestD1Precedence(unittest.TestCase):
|
||||
def test_add_then_mul(self):
|
||||
# 1+2*3 must be 1+(2*3), not (1+2)*3
|
||||
self.assertEqual(p('1+2*3'), BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
def test_mul_then_add(self):
|
||||
# 2*3+1 must be (2*3)+1
|
||||
self.assertEqual(p('2*3+1'), BinOp('+', BinOp('*', Num(2), Num(3)), Num(1)))
|
||||
|
||||
def test_sub_then_div(self):
|
||||
# 9-4/2 must be 9-(4/2)
|
||||
self.assertEqual(p('9-4/2'), BinOp('-', Num(9), BinOp('/', Num(4), Num(2))))
|
||||
|
||||
|
||||
class TestD2LeftAssociativity(unittest.TestCase):
|
||||
def test_subtraction(self):
|
||||
# 8-3-2 must be (8-3)-2
|
||||
self.assertEqual(p('8-3-2'), BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)))
|
||||
|
||||
def test_division(self):
|
||||
# 8/4/2 must be (8/4)/2
|
||||
self.assertEqual(p('8/4/2'), BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)))
|
||||
|
||||
def test_addition(self):
|
||||
# 1+2+3 must be (1+2)+3
|
||||
self.assertEqual(p('1+2+3'), BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
|
||||
class TestD3Parentheses(unittest.TestCase):
|
||||
def test_override_precedence(self):
|
||||
# (1+2)*3: + is under *
|
||||
self.assertEqual(p('(1+2)*3'), BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_nested_parens(self):
|
||||
# ((2+3)) same as 2+3
|
||||
self.assertEqual(p('((2+3))'), BinOp('+', Num(2), Num(3)))
|
||||
|
||||
def test_parens_right(self):
|
||||
# 3*(1+2): + is under *, on the right
|
||||
self.assertEqual(p('3*(1+2)'), BinOp('*', Num(3), BinOp('+', Num(1), Num(2))))
|
||||
|
||||
|
||||
class TestD4UnaryMinus(unittest.TestCase):
|
||||
def test_simple(self):
|
||||
self.assertEqual(p('-5'), Unary('-', Num(5)))
|
||||
|
||||
def test_paren(self):
|
||||
# -(1+2)
|
||||
self.assertEqual(p('-(1+2)'), Unary('-', BinOp('+', Num(1), Num(2))))
|
||||
|
||||
def test_after_mul(self):
|
||||
# 3 * -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))))
|
||||
|
||||
|
||||
class TestD5Errors(unittest.TestCase):
|
||||
def _raises(self, src):
|
||||
with self.assertRaises(ParseError, msg=f"expected ParseError for {src!r}"):
|
||||
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_open_paren(self):
|
||||
self._raises(')(')
|
||||
|
||||
def test_empty(self):
|
||||
self._raises('')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@ -0,0 +1,10 @@
|
||||
# JOURNAL — phase `lex`
|
||||
|
||||
## 2026-06-15
|
||||
|
||||
- Read plan, set up `calc/` package with `lexer.py` and `test_lexer.py`.
|
||||
- `Token` uses `__eq__` for easy test assertions; `__repr__` for readable output.
|
||||
- Number parsing: handles integers, `3.14`, `.5`, `10.`; lone `.` raises LexError.
|
||||
- Operator dispatch via `_SINGLE` dict — clean and extensible.
|
||||
- 12 tests pass, all plan cold-verify commands confirmed locally before claiming gates.
|
||||
- Pulled Adversary's REVIEW-lex.md (all PENDING) before commit — no conflicts.
|
||||
@ -0,0 +1,24 @@
|
||||
# JOURNAL — phase `parse`
|
||||
|
||||
## Approach
|
||||
|
||||
Recursive-descent parser with standard precedence climbing:
|
||||
- `expr` handles `+` and `-` (lowest precedence), left-associative via iteration
|
||||
- `_term` handles `*` and `/` (higher precedence), left-associative via iteration
|
||||
- `_unary` handles unary `-` recursively (right-recursive so `--5` works)
|
||||
- `_primary` handles numbers and parenthesized subexpressions
|
||||
|
||||
Empty input detected early (before `_Parser` is constructed) by checking if the token list
|
||||
is empty or contains only EOF. This avoids a confusing error path through `_primary`.
|
||||
|
||||
## Gate verification results (local)
|
||||
|
||||
- D1: `1+2*3` → `BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))` ✓
|
||||
- D2: `8-3-2` → `BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))` ✓
|
||||
- D2: `8/4/2` → `BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))` ✓
|
||||
- D3: `(1+2)*3` → `BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))` ✓
|
||||
- D4: `-5` → `Unary('-', Num(5))` ✓
|
||||
- D4: `-(1+2)` → `Unary('-', BinOp('+', Num(1), Num(2)))` ✓
|
||||
- D4: `3 * -2` → `BinOp('*', Num(3), Unary('-', Num(2)))` ✓
|
||||
- D5: all 5 error cases raise `ParseError` ✓
|
||||
- D6: 30 tests, 0 failures ✓
|
||||
@ -0,0 +1,50 @@
|
||||
# REVIEW — phase `eval`
|
||||
|
||||
Cold-verified at commit `6e385c92a1bb145bc97183dfed8016a33f86f3ca` (pulled via `b136909`).
|
||||
|
||||
## D1: PASS @2026-06-15T00:11Z
|
||||
|
||||
All five arithmetic cases correct:
|
||||
- `2+3*4` → 14 ✓
|
||||
- `(2+3)*4` → 20 ✓
|
||||
- `8-3-2` → 3 ✓
|
||||
- `-2+5` → 3 ✓
|
||||
- `2*-3` → -6 ✓
|
||||
|
||||
Adversarial extras also pass: `(-3)*(-3)=9`, `10-4-3=3`, left-assoc chain `2+3+4+5=14`.
|
||||
|
||||
## D2: PASS @2026-06-15T00:11Z
|
||||
|
||||
- `7/2` → `3.5` (true division, returns float) ✓
|
||||
- `1/0` raises `EvalError("division by zero")` — not bare `ZeroDivisionError` ✓
|
||||
- `0/1` does not crash; returns `0` ✓
|
||||
|
||||
## D3: PASS @2026-06-15T00:11Z
|
||||
|
||||
- `format_result(evaluate(parse(tokenize("4/2"))))` → `'2'` ✓
|
||||
- `format_result(evaluate(parse(tokenize("7/2"))))` → `'3.5'` ✓
|
||||
- `0/1` → `'0'` (not `'0.0'`) ✓
|
||||
- Rule documented in `evaluator.format_result` docstring ✓
|
||||
|
||||
## D4: PASS @2026-06-15T00:11Z
|
||||
|
||||
```
|
||||
python calc.py "2+3*4" → 14, exit 0 ✓
|
||||
python calc.py "(2+3)*4" → 20, exit 0 ✓
|
||||
python calc.py "7/2" → 3.5, exit 0 ✓
|
||||
python calc.py "4/2" → 2, exit 0 ✓
|
||||
python calc.py "1/0" → "error: division by zero" on stderr, exit 1 ✓
|
||||
python calc.py "1 +" → "error: unexpected token EOF(None)" on stderr, exit 1 ✓
|
||||
```
|
||||
|
||||
Extra adversarial CLI checks: `""`, `"2+"`, `"*3"` all print clean error lines to stderr, exit 1, no traceback ✓
|
||||
|
||||
## D5: PASS @2026-06-15T00:11Z
|
||||
|
||||
```
|
||||
python -m unittest -q
|
||||
Ran 44 tests in 0.049s
|
||||
OK
|
||||
```
|
||||
|
||||
0 failures, no regressions in lex/parse suites ✓
|
||||
@ -0,0 +1,68 @@
|
||||
# REVIEW — phase `lex`
|
||||
|
||||
Adversary cold-verification log. Updated each time a DoD gate is checked.
|
||||
|
||||
## Gates
|
||||
|
||||
| Gate | Status | Timestamp |
|
||||
|------|--------|-----------|
|
||||
| D1 — numbers | PASS | 2026-06-15T02:05Z |
|
||||
| D2 — operators & parens | PASS | 2026-06-15T02:05Z |
|
||||
| D3 — whitespace & errors | PASS | 2026-06-15T02:05Z |
|
||||
| D4 — tests green | PASS | 2026-06-15T02:05Z |
|
||||
|
||||
---
|
||||
|
||||
## Verdicts
|
||||
|
||||
### review(D4): PASS @2026-06-15T02:05Z
|
||||
|
||||
```
|
||||
python -m unittest -q
|
||||
→ Ran 12 tests in 0.000s OK
|
||||
```
|
||||
|
||||
12 tests, 0 failures. Covers D1–D3 including required cases.
|
||||
|
||||
### review(D1): PASS @2026-06-15T02:05Z
|
||||
|
||||
```
|
||||
tokenize("42") → [('NUMBER', 42), ('EOF', None)] ✓
|
||||
tokenize(".5") → [('NUMBER', 0.5), ('EOF', None)] ✓
|
||||
tokenize("10.") → [('NUMBER', 10.0), ('EOF', None)] ✓
|
||||
tokenize("3.14") → NUMBER(3.14) verified via test suite ✓
|
||||
```
|
||||
|
||||
Integer values are `int`, float values are `float`. EOF is present.
|
||||
|
||||
### review(D2): PASS @2026-06-15T02:05Z
|
||||
|
||||
```
|
||||
tokenize("1+2*3") kinds → ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'] ✓
|
||||
All six operators/parens + - * / ( ) each map to the correct kind.
|
||||
```
|
||||
|
||||
### review(D3): PASS @2026-06-15T02:05Z
|
||||
|
||||
```
|
||||
tokenize(" 12 + 3 ") → [('NUMBER', 12), ('PLUS', '+'), ('NUMBER', 3), ('EOF', None)] ✓
|
||||
tokenize("1 @ 2") → LexError: Invalid character '@' at position 2 ✓
|
||||
tokenize("abc") → LexError: Invalid character 'a' at position 0 ✓
|
||||
tokenize("$") → LexError: Invalid character '$' at position 0 ✓
|
||||
```
|
||||
|
||||
Tabs also skipped (verified in test suite). Error messages include the offending char and position.
|
||||
|
||||
---
|
||||
|
||||
## Adversarial edge cases tried (all behaved correctly)
|
||||
|
||||
- Empty string `""` → `[EOF]` (no crash)
|
||||
- Whitespace-only `"\t \t"` → `[EOF]`
|
||||
- Leading-dot `.5` → `NUMBER(0.5)`
|
||||
- Trailing-dot `10.` → `NUMBER(10.0)`
|
||||
- Bare dot `.` → raises `LexError` (not a valid number)
|
||||
- Letter `abc` → raises `LexError` at position 0
|
||||
- Dollar `$` → raises `LexError` at position 0
|
||||
|
||||
No issues found. All four DoD gates independently verified at commit `a1c68aa`.
|
||||
@ -0,0 +1,74 @@
|
||||
# REVIEW — phase `parse`
|
||||
|
||||
## Verdict
|
||||
|
||||
review(D1-D6): PASS — all six gates verified cold at a05812d
|
||||
|
||||
---
|
||||
|
||||
## D1: PASS @2026-06-15T02:10Z
|
||||
|
||||
Precedence correct: `*`/`/` bind tighter than `+`/`-` via two-level grammar (`expr` → `_term` → `_unary` → `_primary`).
|
||||
|
||||
```
|
||||
parse(tokenize('1+2*3')) => BinOp('+', Num(1), BinOp('*', Num(2), Num(3))) ✓
|
||||
parse(tokenize('2*3+1')) => BinOp('+', BinOp('*', Num(2), Num(3)), Num(1)) ✓
|
||||
parse(tokenize('9-4/2')) => BinOp('-', Num(9), BinOp('/', Num(4), Num(2))) ✓
|
||||
```
|
||||
|
||||
## D2: PASS @2026-06-15T02:10Z
|
||||
|
||||
Left associativity correct: while-loops in `expr()` and `_term()` accumulate left-to-right.
|
||||
|
||||
```
|
||||
parse(tokenize('8-3-2')) => BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)) ✓
|
||||
parse(tokenize('8/4/2')) => BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)) ✓
|
||||
parse(tokenize('1+2+3')) => BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)) ✓
|
||||
```
|
||||
|
||||
## D3: PASS @2026-06-15T02:10Z
|
||||
|
||||
Parentheses override precedence via `_primary()` grouping.
|
||||
|
||||
```
|
||||
parse(tokenize('(1+2)*3')) => BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)) ✓
|
||||
parse(tokenize('((2+3))')) => BinOp('+', Num(2), Num(3)) ✓
|
||||
```
|
||||
|
||||
## D4: PASS @2026-06-15T02:10Z
|
||||
|
||||
Unary minus handled at `_unary()`, right-recursive, correct for all cases including nested and post-operator.
|
||||
|
||||
```
|
||||
parse(tokenize('-5')) => Unary('-', Num(5)) ✓
|
||||
parse(tokenize('-(1+2)')) => Unary('-', BinOp('+', Num(1), Num(2))) ✓
|
||||
parse(tokenize('3 * -2')) => BinOp('*', Num(3), Unary('-', Num(2))) ✓
|
||||
parse(tokenize('--5')) => Unary('-', Unary('-', Num(5))) ✓
|
||||
parse(tokenize('---5')) => Unary('-', Unary('-', Unary('-', Num(5)))) ✓
|
||||
parse(tokenize('-(1+2)*3')) => BinOp('*', Unary('-', BinOp('+', Num(1), Num(2))), Num(3)) ✓
|
||||
```
|
||||
|
||||
## D5: PASS @2026-06-15T02:10Z
|
||||
|
||||
All five required error cases raise `ParseError` (not any other exception). Adversarial extras also raise correctly.
|
||||
|
||||
```
|
||||
'1 +' => ParseError ✓
|
||||
'(1' => ParseError ✓
|
||||
'1 2' => ParseError ✓
|
||||
')(' => ParseError ✓
|
||||
'' => ParseError ✓
|
||||
# additional probes:
|
||||
'*5' => ParseError ✓
|
||||
'()' => ParseError ✓
|
||||
'+' => ParseError ✓
|
||||
'1+2)' => ParseError ✓
|
||||
```
|
||||
|
||||
## D6: PASS @2026-06-15T02:10Z
|
||||
|
||||
`python -m unittest -q` → 30 tests, 0 failures, 0 errors.
|
||||
|
||||
---
|
||||
|
||||
Gates to verify: D1 D2 D3 D4 D5 D6 — all PASS.
|
||||
@ -0,0 +1,82 @@
|
||||
# STATUS — phase `eval`
|
||||
|
||||
## DONE
|
||||
|
||||
## Claims
|
||||
|
||||
Gates D1–D5 are implemented and verified at commit `b1369091c751655df8925685b6a2187123aeb6ff`.
|
||||
|
||||
### D1 — arithmetic
|
||||
|
||||
**What:** `evaluate(parse(tokenize(s)))` returns correct integer results for `+`, `-`, `*`, `/` with precedence and parens.
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; from calc.evaluator import evaluate; print(evaluate(parse(tokenize('2+3*4'))))"
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; from calc.evaluator import evaluate; print(evaluate(parse(tokenize('(2+3)*4'))))"
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; from calc.evaluator import evaluate; print(evaluate(parse(tokenize('8-3-2'))))"
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; from calc.evaluator import evaluate; print(evaluate(parse(tokenize('-2+5'))))"
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; from calc.evaluator import evaluate; print(evaluate(parse(tokenize('2*-3'))))"
|
||||
```
|
||||
**Expected:** `14`, `20`, `3`, `3`, `-6`
|
||||
|
||||
### D2 — division
|
||||
|
||||
**What:** `/` is true division; division by zero raises `EvalError`, not bare `ZeroDivisionError`.
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; from calc.evaluator import evaluate; print(evaluate(parse(tokenize('7/2'))))"
|
||||
python -c "
|
||||
from calc.lexer import tokenize; from calc.parser import parse; from calc.evaluator import evaluate, EvalError
|
||||
try:
|
||||
evaluate(parse(tokenize('1/0')))
|
||||
print('FAIL: no exception')
|
||||
except EvalError as e:
|
||||
print('PASS: EvalError:', e)
|
||||
except ZeroDivisionError:
|
||||
print('FAIL: bare ZeroDivisionError')
|
||||
"
|
||||
```
|
||||
**Expected:** `3.5` then `PASS: EvalError: division by zero`
|
||||
|
||||
### D3 — result type
|
||||
|
||||
**What:** Whole-valued results print without `.0`; non-whole print as float. Rule in `evaluator.format_result`.
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
python -c "from calc.evaluator import format_result; from calc.lexer import tokenize; from calc.parser import parse; from calc.evaluator import evaluate; print(repr(format_result(evaluate(parse(tokenize('4/2'))))))"
|
||||
python -c "from calc.evaluator import format_result; from calc.lexer import tokenize; from calc.parser import parse; from calc.evaluator import evaluate; print(repr(format_result(evaluate(parse(tokenize('7/2'))))))"
|
||||
```
|
||||
**Expected:** `'2'` and `'3.5'`
|
||||
|
||||
### D4 — CLI
|
||||
|
||||
**What:** `python calc.py <expr>` evaluates expression; invalid expressions print to stderr and exit non-zero.
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
python calc.py "2+3*4" # prints: 14, exit 0
|
||||
python calc.py "(2+3)*4" # prints: 20, exit 0
|
||||
python calc.py "7/2" # prints: 3.5, exit 0
|
||||
python calc.py "4/2" # prints: 2, exit 0
|
||||
python calc.py "1/0"; echo "exit: $?" # error on stderr, exit 1
|
||||
python calc.py "1 +"; echo "exit: $?" # error on stderr, exit 1
|
||||
```
|
||||
|
||||
### D5 — tests green
|
||||
|
||||
**What:** Full unittest suite (lex + parse + eval) passes with 0 failures.
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
python -m unittest -q
|
||||
```
|
||||
**Expected:** `Ran 44 tests in ... OK` (0 failures)
|
||||
|
||||
## Files
|
||||
|
||||
- `calc/evaluator.py` — `EvalError`, `evaluate(node)`, `format_result(value)`
|
||||
- `calc.py` — CLI entry point
|
||||
- `calc/test_evaluator.py` — unittest suite covering D1–D5
|
||||
@ -0,0 +1,59 @@
|
||||
# STATUS — phase `lex`
|
||||
|
||||
## DONE
|
||||
|
||||
## Claimed Gates
|
||||
|
||||
claim(D1): Numbers — integers and floats tokenize to NUMBER tokens with correct numeric values.
|
||||
claim(D2): Operators & parens — `+ - * / ( )` each produce the right kind token.
|
||||
claim(D3): Whitespace & errors — spaces/tabs skipped; invalid chars raise `LexError` with char + position.
|
||||
claim(D4): Tests green — `python -m unittest -q` passes, 12 tests, 0 failures.
|
||||
|
||||
## Commit
|
||||
|
||||
SHA: a1c68aa
|
||||
|
||||
Files:
|
||||
- `calc/lexer.py` — `Token`, `LexError`, `tokenize()`
|
||||
- `calc/test_lexer.py` — 12 unittest tests covering D1–D4
|
||||
- `calc/__init__.py` — empty package init
|
||||
|
||||
## How to Verify (exact commands from plan)
|
||||
|
||||
```bash
|
||||
# D4 — tests pass
|
||||
python -m unittest -q
|
||||
# Expected: "Ran 12 tests in 0.00s" + "OK"
|
||||
|
||||
# D1 + D2 + D3 — tokenize complex expression
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"
|
||||
# Expected: [('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]
|
||||
|
||||
# D3 — invalid char raises LexError
|
||||
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
|
||||
# Expected: LexError: Invalid character '@' at position 2
|
||||
```
|
||||
|
||||
## Additional spot-checks
|
||||
|
||||
```bash
|
||||
# D1 — integer
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('42')])"
|
||||
# Expected: [('NUMBER', 42), ('EOF', None)]
|
||||
|
||||
# D1 — leading dot float
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('.5')])"
|
||||
# Expected: [('NUMBER', 0.5), ('EOF', None)]
|
||||
|
||||
# D1 — trailing dot float
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('10.')])"
|
||||
# Expected: [('NUMBER', 10.0), ('EOF', None)]
|
||||
|
||||
# D2 — "1+2*3" kinds
|
||||
python -c "from calc.lexer import tokenize; print([t.kind for t in tokenize('1+2*3')])"
|
||||
# Expected: ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF']
|
||||
|
||||
# D3 — whitespace test " 12 + 3 "
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize(' 12 + 3 ')])"
|
||||
# Expected: [('NUMBER', 12), ('PLUS', '+'), ('NUMBER', 3), ('EOF', None)]
|
||||
```
|
||||
@ -0,0 +1,70 @@
|
||||
## DONE
|
||||
|
||||
# STATUS — phase `parse`
|
||||
|
||||
## Claimed gates: D1 D2 D3 D4 D5 D6
|
||||
|
||||
## Files
|
||||
- `calc/parser.py` — parser implementation
|
||||
- `calc/test_parser.py` — unittest suite
|
||||
|
||||
## AST node shapes
|
||||
|
||||
```
|
||||
Num(value) — leaf numeric literal; value is int or float
|
||||
BinOp(op, left, right) — binary op; op is one of '+' '-' '*' '/'
|
||||
Unary(op, operand) — unary op; op is '-'
|
||||
```
|
||||
|
||||
All nodes implement `__repr__` and `__eq__`.
|
||||
|
||||
## How to verify
|
||||
|
||||
```bash
|
||||
# D6 — all tests green
|
||||
python -m unittest -q
|
||||
|
||||
# D1 — * binds tighter than +
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('1+2*3')))"
|
||||
# expected: BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
|
||||
# D2 — left associativity
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8-3-2')))"
|
||||
# expected: BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8/4/2')))"
|
||||
# expected: BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))
|
||||
|
||||
# D3 — parens override precedence
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('(1+2)*3')))"
|
||||
# expected: BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
|
||||
# D4 — unary minus
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-5')))"
|
||||
# expected: Unary('-', Num(5))
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-(1+2)')))"
|
||||
# expected: Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('3 * -2')))"
|
||||
# expected: BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
|
||||
# D5 — ParseError for malformed input
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse, ParseError
|
||||
for s in ['1 +', '(1', '1 2', ')(' , '']:
|
||||
try:
|
||||
parse(tokenize(s))
|
||||
print('FAIL', s)
|
||||
except ParseError:
|
||||
print('OK', repr(s))
|
||||
"
|
||||
# expected: all 5 lines print OK
|
||||
|
||||
# D1/D3 anti-confusion check — structure differs:
|
||||
# 1+2*3 => BinOp('+', Num(1), BinOp('*', Num(2), Num(3))) [* is the right child of +]
|
||||
# (1+2)*3 => BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)) [+ is the left child of *]
|
||||
```
|
||||
|
||||
## Commit
|
||||
|
||||
`a05812d` — claim(D1-D6): add recursive-descent parser with full gate coverage
|
||||
17
calculators/builder-adversary-min/run-03/GIT-LOG.txt
Normal file
17
calculators/builder-adversary-min/run-03/GIT-LOG.txt
Normal file
@ -0,0 +1,17 @@
|
||||
# git history (claim/review handshake), from the run's shared bare repo
|
||||
75bd35c status: eval phase DONE — all D1-D5 gates PASS per Adversary review at fe7e562
|
||||
434cde5 review(D1,D2,D3,D4,D5): PASS — all gates verified cold at fe7e562
|
||||
df2f5da claim(D1,D2,D3,D4,D5): eval phase — evaluator + CLI + tests at fe7e562
|
||||
fe7e562 feat: implement evaluator, CLI, and tests (D1-D5) for eval phase
|
||||
710b731 review(init): Adversary online for eval phase, awaiting Builder commits
|
||||
0afab21 review(D1,D2,D3,D4,D5,D6): PASS — all gates verified cold at fa50146
|
||||
b61ad6d claim(D1-D6): parse phase — all gates verified, 36 tests green
|
||||
fa50146 status: add commit sha 14bbe57 to STATUS-parse
|
||||
14bbe57 feat: implement calc parser (D1-D6) — parse() with Num/BinOp/Unary AST
|
||||
fc470e0 status: phase lex DONE — all D1-D4 gates PASS per Adversary review
|
||||
1ca2b4c review(D1,D2,D3,D4): PASS — all gates verified cold at ba1f056
|
||||
35de6d4 journal: add lex phase build notes
|
||||
c465844 status: add commit sha ba1f056 to STATUS-lex
|
||||
ba1f056 feat: implement calc lexer (D1-D4) — tokenize() with Token/LexError
|
||||
4909b16 review(init): Adversary online, awaiting Builder commits
|
||||
cae8791 chore: seed
|
||||
1
calculators/builder-adversary-min/run-03/README.md
Normal file
1
calculators/builder-adversary-min/run-03/README.md
Normal file
@ -0,0 +1 @@
|
||||
# calc work repo
|
||||
1
calculators/builder-adversary-min/run-03/SOURCE.txt
Normal file
1
calculators/builder-adversary-min/run-03/SOURCE.txt
Normal file
@ -0,0 +1 @@
|
||||
original path: /tmp/ao-campaign-Ofyz4E/builder-adversary-min/r3
|
||||
22
calculators/builder-adversary-min/run-03/calc.py
Normal file
22
calculators/builder-adversary-min/run-03/calc.py
Normal file
@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
from calc.lexer import tokenize, LexError
|
||||
from calc.parser import parse, ParseError
|
||||
from calc.evaluator import evaluate, EvalError
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("usage: calc.py <expression>", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
expr = sys.argv[1]
|
||||
try:
|
||||
result = evaluate(parse(tokenize(expr)))
|
||||
except (LexError, ParseError, EvalError) as e:
|
||||
print(f"error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print(result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
42
calculators/builder-adversary-min/run-03/calc/evaluator.py
Normal file
42
calculators/builder-adversary-min/run-03/calc/evaluator.py
Normal file
@ -0,0 +1,42 @@
|
||||
from calc.parser import Num, BinOp, Unary, Node
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node: Node):
|
||||
"""Walk the AST and return int | float.
|
||||
|
||||
Result type rule: if the result is mathematically an integer (no
|
||||
fractional part), return int; otherwise return float.
|
||||
"""
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
val = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return _coerce(-val)
|
||||
raise EvalError(f"unknown unary op {node.op!r}")
|
||||
if isinstance(node, BinOp):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
op = node.op
|
||||
if op == '+':
|
||||
return _coerce(left + right)
|
||||
if op == '-':
|
||||
return _coerce(left - right)
|
||||
if op == '*':
|
||||
return _coerce(left * right)
|
||||
if op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
return _coerce(left / right)
|
||||
raise EvalError(f"unknown binary op {op!r}")
|
||||
raise EvalError(f"unknown node type {type(node).__name__}")
|
||||
|
||||
|
||||
def _coerce(value):
|
||||
if isinstance(value, float) and value == int(value):
|
||||
return int(value)
|
||||
return value
|
||||
52
calculators/builder-adversary-min/run-03/calc/lexer.py
Normal file
52
calculators/builder-adversary-min/run-03/calc/lexer.py
Normal file
@ -0,0 +1,52 @@
|
||||
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
|
||||
n = len(src)
|
||||
while i < n:
|
||||
ch = src[i]
|
||||
if ch in ' \t':
|
||||
i += 1
|
||||
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
|
||||
elif ch.isdigit() or ch == '.':
|
||||
j = i
|
||||
while j < n and (src[j].isdigit() or src[j] == '.'):
|
||||
j += 1
|
||||
raw = src[i:j]
|
||||
value = float(raw) if '.' in raw else int(raw)
|
||||
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
|
||||
118
calculators/builder-adversary-min/run-03/calc/parser.py
Normal file
118
calculators/builder-adversary-min/run-03/calc/parser.py
Normal file
@ -0,0 +1,118 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Union, List
|
||||
from calc.lexer import Token
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Num:
|
||||
value: Union[int, float]
|
||||
|
||||
def __repr__(self):
|
||||
return f"Num({self.value!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
op: str
|
||||
left: 'Node'
|
||||
right: 'Node'
|
||||
|
||||
def __repr__(self):
|
||||
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
op: str
|
||||
operand: 'Node'
|
||||
|
||||
def __repr__(self):
|
||||
return f"Unary({self.op!r}, {self.operand!r})"
|
||||
|
||||
|
||||
Node = Union[Num, BinOp, Unary]
|
||||
|
||||
|
||||
class _Parser:
|
||||
def __init__(self, tokens: List[Token]):
|
||||
self.tokens = tokens
|
||||
self.pos = 0
|
||||
|
||||
def _peek(self) -> Token:
|
||||
return self.tokens[self.pos]
|
||||
|
||||
def _consume(self, kind: str = None) -> Token:
|
||||
tok = self.tokens[self.pos]
|
||||
if kind and tok.kind != kind:
|
||||
raise ParseError(f"expected {kind!r}, 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':
|
||||
raise ParseError(
|
||||
f"unexpected token {self._peek().kind!r} ({self._peek().value!r})"
|
||||
)
|
||||
return node
|
||||
|
||||
def _expr(self) -> Node:
|
||||
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:
|
||||
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) -> Node:
|
||||
if self._peek().kind == 'MINUS':
|
||||
op = self._consume().value
|
||||
return Unary(op, self._unary())
|
||||
return self._primary()
|
||||
|
||||
def _primary(self) -> Node:
|
||||
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._peek().value!r})"
|
||||
)
|
||||
self._consume()
|
||||
return node
|
||||
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")
|
||||
|
||||
|
||||
def parse(tokens: List[Token]) -> Node:
|
||||
"""Parse a flat token list into an AST Node.
|
||||
|
||||
AST shape
|
||||
---------
|
||||
Num(value) — numeric literal (int or float)
|
||||
BinOp(op, left, right) — binary op; op in {'+', '-', '*', '/'}
|
||||
Unary(op, operand) — unary op; op == '-'
|
||||
|
||||
Precedence (high to low): unary-minus > * / > + -
|
||||
Associativity: left for all binary operators.
|
||||
|
||||
Raises ParseError on malformed input.
|
||||
"""
|
||||
return _Parser(tokens).parse()
|
||||
108
calculators/builder-adversary-min/run-03/calc/test_evaluator.py
Normal file
108
calculators/builder-adversary-min/run-03/calc/test_evaluator.py
Normal file
@ -0,0 +1,108 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from calc.evaluator import evaluate, EvalError
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse
|
||||
|
||||
|
||||
def calc(expr):
|
||||
return evaluate(parse(tokenize(expr)))
|
||||
|
||||
|
||||
class TestD1Arithmetic(unittest.TestCase):
|
||||
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_sub(self):
|
||||
self.assertEqual(calc("8-3-2"), 3)
|
||||
|
||||
def test_unary_minus(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_mul_unary(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
|
||||
class TestD2Division(unittest.TestCase):
|
||||
def test_true_division(self):
|
||||
self.assertEqual(calc("7/2"), 3.5)
|
||||
|
||||
def test_div_by_zero_raises_eval_error(self):
|
||||
with self.assertRaises(EvalError):
|
||||
calc("1/0")
|
||||
|
||||
def test_div_by_zero_not_bare(self):
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError escaped; should be EvalError")
|
||||
|
||||
|
||||
class TestD3ResultType(unittest.TestCase):
|
||||
def test_whole_division_returns_int(self):
|
||||
result = calc("4/2")
|
||||
self.assertIsInstance(result, int)
|
||||
self.assertEqual(result, 2)
|
||||
|
||||
def test_non_whole_division_returns_float(self):
|
||||
result = calc("7/2")
|
||||
self.assertIsInstance(result, float)
|
||||
self.assertEqual(result, 3.5)
|
||||
|
||||
def test_int_arithmetic_stays_int(self):
|
||||
self.assertIsInstance(calc("2+3*4"), int)
|
||||
|
||||
def test_negative_whole_is_int(self):
|
||||
result = calc("-4/2")
|
||||
self.assertIsInstance(result, int)
|
||||
self.assertEqual(result, -2)
|
||||
|
||||
|
||||
class TestD4CLI(unittest.TestCase):
|
||||
def _run(self, expr):
|
||||
return subprocess.run(
|
||||
[sys.executable, "calc.py", expr],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
|
||||
def test_basic_expression(self):
|
||||
r = self._run("2+3*4")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "14")
|
||||
|
||||
def test_parens_cli(self):
|
||||
r = self._run("(2+3)*4")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "20")
|
||||
|
||||
def test_float_result(self):
|
||||
r = self._run("7/2")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "3.5")
|
||||
|
||||
def test_whole_float_no_decimal(self):
|
||||
r = self._run("4/2")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "2")
|
||||
|
||||
def test_invalid_expression_exits_nonzero(self):
|
||||
r = self._run("1 +")
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertTrue(r.stderr.strip(), "expected error on stderr")
|
||||
|
||||
def test_div_by_zero_exits_nonzero(self):
|
||||
r = self._run("1/0")
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertTrue(r.stderr.strip())
|
||||
self.assertNotIn("Traceback", r.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
101
calculators/builder-adversary-min/run-03/calc/test_lexer.py
Normal file
101
calculators/builder-adversary-min/run-03/calc/test_lexer.py
Normal file
@ -0,0 +1,101 @@
|
||||
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):
|
||||
def test_integer(self):
|
||||
result = tokenize("42")
|
||||
self.assertEqual(result[0], Token('NUMBER', 42))
|
||||
self.assertEqual(result[1], Token('EOF', None))
|
||||
|
||||
def test_float(self):
|
||||
t = tokenize("3.14")[0]
|
||||
self.assertEqual(t.kind, 'NUMBER')
|
||||
self.assertAlmostEqual(t.value, 3.14)
|
||||
|
||||
def test_leading_dot(self):
|
||||
t = tokenize(".5")[0]
|
||||
self.assertEqual(t.kind, 'NUMBER')
|
||||
self.assertAlmostEqual(t.value, 0.5)
|
||||
|
||||
def test_trailing_dot(self):
|
||||
t = tokenize("10.")[0]
|
||||
self.assertEqual(t.kind, 'NUMBER')
|
||||
self.assertAlmostEqual(t.value, 10.0)
|
||||
|
||||
def test_integer_value_type(self):
|
||||
t = tokenize("42")[0]
|
||||
self.assertIsInstance(t.value, int)
|
||||
|
||||
def test_float_value_type(self):
|
||||
t = tokenize("3.14")[0]
|
||||
self.assertIsInstance(t.value, float)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_all_operators(self):
|
||||
result = kinds("1+2*3")
|
||||
self.assertEqual(result, ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_minus(self):
|
||||
self.assertIn('MINUS', kinds("1-2"))
|
||||
|
||||
def test_slash(self):
|
||||
self.assertIn('SLASH', kinds("1/2"))
|
||||
|
||||
def test_parens(self):
|
||||
ks = kinds("(1)")
|
||||
self.assertEqual(ks[0], 'LPAREN')
|
||||
self.assertEqual(ks[2], 'RPAREN')
|
||||
|
||||
def test_complex_expr(self):
|
||||
result = values("3.5*(1-2)")
|
||||
expected_kinds = ['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF']
|
||||
self.assertEqual([k for k, _ in result], expected_kinds)
|
||||
self.assertAlmostEqual(result[0][1], 3.5)
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def test_whitespace_skipped(self):
|
||||
result = kinds(" 12 + 3 ")
|
||||
self.assertEqual(result, ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_whitespace_values(self):
|
||||
result = values(" 12 + 3 ")
|
||||
self.assertEqual(result[0], ('NUMBER', 12))
|
||||
self.assertEqual(result[1], ('PLUS', '+'))
|
||||
self.assertEqual(result[2], ('NUMBER', 3))
|
||||
|
||||
def test_tab_skipped(self):
|
||||
result = kinds("1\t+\t2")
|
||||
self.assertEqual(result, ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_lex_error_at_sign(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('@', str(ctx.exception))
|
||||
|
||||
def test_lex_error_position(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('2', str(ctx.exception))
|
||||
|
||||
def test_lex_error_letter(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("1 + x")
|
||||
|
||||
def test_lex_error_dollar(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$10")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
97
calculators/builder-adversary-min/run-03/calc/test_parser.py
Normal file
97
calculators/builder-adversary-min/run-03/calc/test_parser.py
Normal file
@ -0,0 +1,97 @@
|
||||
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_add_mul(self):
|
||||
# 1+2*3 must parse as 1+(2*3), not (1+2)*3
|
||||
self.assertEqual(p('1+2*3'), BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
def test_div_add(self):
|
||||
# 6/2+1 must parse as (6/2)+1
|
||||
self.assertEqual(p('6/2+1'), BinOp('+', BinOp('/', Num(6), Num(2)), Num(1)))
|
||||
|
||||
def test_mul_sub(self):
|
||||
# 4-2*3 => 4-(2*3)
|
||||
self.assertEqual(p('4-2*3'), BinOp('-', Num(4), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
|
||||
class TestLeftAssoc(unittest.TestCase):
|
||||
def test_subtraction(self):
|
||||
# 8-3-2 => (8-3)-2
|
||||
self.assertEqual(p('8-3-2'), BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)))
|
||||
|
||||
def test_division(self):
|
||||
# 8/4/2 => (8/4)/2
|
||||
self.assertEqual(p('8/4/2'), BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)))
|
||||
|
||||
def test_addition(self):
|
||||
# 1+2+3 => (1+2)+3
|
||||
self.assertEqual(p('1+2+3'), BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
|
||||
class TestParentheses(unittest.TestCase):
|
||||
def test_parens_override_precedence(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):
|
||||
self.assertEqual(p('((5))'), Num(5))
|
||||
|
||||
def test_parens_in_add(self):
|
||||
# 2*(3+4) => BinOp('*', Num(2), BinOp('+', Num(3), Num(4)))
|
||||
self.assertEqual(
|
||||
p('2*(3+4)'),
|
||||
BinOp('*', Num(2), BinOp('+', Num(3), Num(4)))
|
||||
)
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
def test_simple(self):
|
||||
self.assertEqual(p('-5'), Unary('-', Num(5)))
|
||||
|
||||
def test_paren(self):
|
||||
# -(1+2) => Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
self.assertEqual(p('-(1+2)'), Unary('-', BinOp('+', Num(1), Num(2))))
|
||||
|
||||
def test_after_mul(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))))
|
||||
|
||||
|
||||
class TestErrors(unittest.TestCase):
|
||||
def test_trailing_op(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('')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@ -0,0 +1,11 @@
|
||||
# JOURNAL — phase eval
|
||||
|
||||
## Implementation notes
|
||||
|
||||
**evaluator.py**: Walks the AST recursively. Num returns its value directly. BinOp evaluates left/right then applies op. Division by zero is intercepted and re-raised as EvalError. All results pass through `_coerce()` which converts whole-valued floats to int.
|
||||
|
||||
**_coerce rule**: `if isinstance(value, float) and value == int(value): return int(value)`. This handles `4/2 = 2.0 → 2` and `-4/2 = -2.0 → -2` correctly. Pure int arithmetic stays int throughout (int + int = int in Python, so no coercion needed there).
|
||||
|
||||
**calc.py**: Catches LexError, ParseError, EvalError and prints to stderr with exit 1. No traceback exposed.
|
||||
|
||||
**test_evaluator.py**: 18 tests. D1 covers all 5 mandated expressions. D2 covers true division, EvalError raise, and confirms ZeroDivisionError doesn't escape. D3 checks isinstance for int/float. D4 uses subprocess to exercise CLI end-to-end.
|
||||
@ -0,0 +1,13 @@
|
||||
# Journal — phase `lex`
|
||||
|
||||
## 2026-06-15
|
||||
|
||||
Built `calc/lexer.py` with `Token` dataclass, `LexError`, and `tokenize()`.
|
||||
|
||||
Design notes:
|
||||
- `Token` is a dataclass with `kind: str` and `value: Union[int, float, str, None]`; EOF has `value=None`, operators carry their char as value, numbers carry the parsed numeric value.
|
||||
- Number parsing: scans while digit or `.`; uses `int()` if no dot else `float()`.
|
||||
- LexError message includes the offending character (quoted) and its 0-based position.
|
||||
- 18 tests cover all D1–D3 requirements including the plan's required expressions.
|
||||
|
||||
Committed ba1f056, then c465844 (STATUS sha update). Waiting for Adversary review.
|
||||
@ -0,0 +1,21 @@
|
||||
# JOURNAL — phase parse
|
||||
|
||||
## Build notes
|
||||
|
||||
Implemented a classic recursive-descent parser.
|
||||
|
||||
Grammar (precedence lowest → highest):
|
||||
```
|
||||
expr → term (('+' | '-') term)*
|
||||
term → unary (('*' | '/') unary)*
|
||||
unary → '-' unary | primary
|
||||
primary→ NUMBER | '(' expr ')'
|
||||
```
|
||||
|
||||
The `while` loops in `_expr` and `_term` produce left-associative trees naturally: each iteration wraps the accumulated left subtree as the new `node`, so 8-3-2 folds as ((8-3)-2).
|
||||
|
||||
Unary minus recurses right (`_unary` calls itself) to allow `--5` to parse as `Unary('-', Unary('-', Num(5)))`.
|
||||
|
||||
Empty input is caught by checking for EOF before entering `_expr`. Trailing tokens (e.g. `1 2`) are caught by the EOF check after `_expr` returns. Unclosed parens are caught in `_primary` when expecting RPAREN but finding EOF.
|
||||
|
||||
36 tests: 3 precision, 3 left-assoc, 3 paren, 4 unary, 5 error, plus 18 from lexer phase.
|
||||
@ -0,0 +1,64 @@
|
||||
# REVIEW — phase eval
|
||||
|
||||
_Adversary verifies each gate cold from own clone at commit `fe7e562`._
|
||||
|
||||
## review(init): Adversary online @2026-06-15T02:35Z
|
||||
|
||||
Eval plan read. DoD gates D1–D5 noted. Waiting for Builder to push evaluator.py, calc.py, and test_evaluator.py.
|
||||
|
||||
---
|
||||
|
||||
## D1: PASS @2026-06-15T02:37Z
|
||||
|
||||
Cold run of all five mandated expressions:
|
||||
- `python calc.py "2+3*4"` → `14` ✓
|
||||
- `python calc.py "(2+3)*4"` → `20` ✓
|
||||
- `python calc.py "8-3-2"` → `3` ✓
|
||||
- `python calc.py "-2+5"` → `3` ✓
|
||||
- `python calc.py "2*-3"` → `-6` ✓
|
||||
|
||||
Adversarial: `--5` → `5` (double-unary handled correctly via recursive `_unary`) ✓; `2*(3+4)-1` → `13` ✓
|
||||
|
||||
## D2: PASS @2026-06-15T02:37Z
|
||||
|
||||
Cold run:
|
||||
- `python calc.py "7/2"` → `3.5` ✓ (true division, not floor)
|
||||
- `python calc.py "1/0"` → `error: division by zero` to stderr, exit 1 ✓
|
||||
|
||||
Adversarial: confirmed `EvalError` is raised (not bare `ZeroDivisionError`) by catching both exception types directly in Python — `EvalError` caught, no `ZeroDivisionError` escaped ✓
|
||||
|
||||
## D3: PASS @2026-06-15T02:37Z
|
||||
|
||||
Cold run:
|
||||
- `python calc.py "4/2"` → `2` (int, no trailing `.0`) ✓
|
||||
- `python calc.py "7/2"` → `3.5` (float) ✓
|
||||
|
||||
Adversarial edge cases:
|
||||
- `-4/2` → `-2` (int, not `-2.0`) ✓
|
||||
- `0/5` → `0` (int) ✓
|
||||
- `1.5+0.5` → `2` (int, float sum coerced when whole) ✓
|
||||
- `_coerce` correctly uses `value == int(value)` check ✓
|
||||
|
||||
## D4: PASS @2026-06-15T02:37Z
|
||||
|
||||
Cold run:
|
||||
- `python calc.py "2+3*4"` → stdout `14`, exit 0 ✓
|
||||
- `python calc.py "1 +"` → stderr `error: unexpected token 'EOF' (None)`, exit 1 ✓
|
||||
- `python calc.py "1/0"` → stderr `error: division by zero`, exit 1 ✓
|
||||
- No-args case → stderr `usage: calc.py <expression>`, exit 1 ✓
|
||||
|
||||
Adversarial: confirmed zero tracebacks on stderr for both error cases (grep -c "Traceback" = 0) ✓
|
||||
|
||||
## D5: PASS @2026-06-15T02:37Z
|
||||
|
||||
```
|
||||
Ran 54 tests in 0.209s
|
||||
OK
|
||||
```
|
||||
|
||||
54 tests (18 eval + 36 lex+parse), 0 failures. No regression in prior suite.
|
||||
`calc/test_evaluator.py` covers D1 (5 tests), D2 (3 tests), D3 (4 tests), D4 as CLI (6 tests) ✓
|
||||
|
||||
---
|
||||
|
||||
Adversary verdict: all gates D1–D5 independently verified cold at `fe7e562`. Implementation is correct.
|
||||
@ -0,0 +1,43 @@
|
||||
# REVIEW-lex — Adversary verdicts
|
||||
|
||||
_Adversary verifies each gate cold from its own clone._
|
||||
|
||||
## Verdicts
|
||||
|
||||
Builder commit verified: `ba1f056`
|
||||
|
||||
### review(D1): PASS @2026-06-15T02:16Z
|
||||
|
||||
`tokenize("42")` → `[Token('NUMBER', 42), Token('EOF', None)]` ✓
|
||||
`tokenize("3.14")` → `[Token('NUMBER', 3.14), Token('EOF', None)]` ✓
|
||||
`tokenize(".5")` → `[Token('NUMBER', 0.5), Token('EOF', None)]` ✓
|
||||
`tokenize("10.")` → `[Token('NUMBER', 10.0), Token('EOF', None)]` ✓
|
||||
Integers produce `int`, floats produce `float`. Token dataclass has `kind` and `value`.
|
||||
|
||||
### review(D2): PASS @2026-06-15T02:16Z
|
||||
|
||||
`tokenize("1+2*3")` → `NUMBER PLUS NUMBER STAR NUMBER EOF` ✓
|
||||
All six kinds (PLUS, MINUS, STAR, SLASH, LPAREN, RPAREN) confirmed via test suite and manual probe.
|
||||
|
||||
### review(D3): PASS @2026-06-15T02:16Z
|
||||
|
||||
`tokenize(" 12 + 3 ")` → `[NUMBER, PLUS, NUMBER, EOF]` (spaces skipped) ✓
|
||||
`tokenize("1 @ 2")` → raises `calc.lexer.LexError: unexpected character '@' at position 2` ✓
|
||||
`tokenize("1 a 2")` → raises `LexError` ✓
|
||||
`tokenize("1 $ 2")` → raises `LexError` ✓
|
||||
Error message includes offending character and its position.
|
||||
|
||||
### review(D4): PASS @2026-06-15T02:16Z
|
||||
|
||||
```
|
||||
python -m unittest -q
|
||||
----------------------------------------------------------------------
|
||||
Ran 18 tests in 0.000s
|
||||
|
||||
OK
|
||||
```
|
||||
Test file contains all three plan-required cases: `" 12 + 3 "`, `"3.5*(1-2)"`, `"1 @ 2"` raises `LexError`. ✓
|
||||
|
||||
## Summary
|
||||
|
||||
All four gates PASS. Builder commit `ba1f056` is clean. No veto.
|
||||
@ -0,0 +1,53 @@
|
||||
# REVIEW — phase parse
|
||||
|
||||
## D1: PASS @2026-06-15T02:27:10Z
|
||||
|
||||
Cold run: `parse(tokenize('1+2*3'))` → `BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))`
|
||||
Structure assertion passed. `*`/`/` correctly bind tighter than `+`/`-`.
|
||||
Also verified: `6/2+1` → `BinOp('+', BinOp('/', Num(6), Num(2)), Num(1))` (div-then-add order correct).
|
||||
Multi-level: `1+2*3+4` → `BinOp('+', BinOp('+', Num(1), BinOp('*', Num(2), Num(3))), Num(4))` ✓
|
||||
|
||||
## D2: PASS @2026-06-15T02:27:10Z
|
||||
|
||||
Cold run:
|
||||
- `8-3-2` → `BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))` ✓
|
||||
- `8/4/2` → `BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))` ✓
|
||||
|
||||
Left associativity correct for both addition and division via the while-loop in `_expr`/`_term`.
|
||||
|
||||
## D3: PASS @2026-06-15T02:27:10Z
|
||||
|
||||
Cold run: `(1+2)*3` → `BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))` ✓
|
||||
Also verified: `((5))` → `Num(5)`, `2*(3+4)` → `BinOp('*', Num(2), BinOp('+', Num(3), Num(4)))` ✓
|
||||
|
||||
## D4: PASS @2026-06-15T02:27:10Z
|
||||
|
||||
Cold run:
|
||||
- `-5` → `Unary('-', Num(5))` ✓
|
||||
- `-(1+2)` → `Unary('-', BinOp('+', Num(1), Num(2)))` ✓
|
||||
- `3 * -2` → `BinOp('*', Num(3), Unary('-', Num(2)))` ✓
|
||||
- `--5` → `Unary('-', Unary('-', Num(5)))` ✓ (recursive _unary handles chaining)
|
||||
|
||||
## D5: PASS @2026-06-15T02:27:10Z
|
||||
|
||||
All five mandated error inputs raise `ParseError` (not any other exception):
|
||||
- `'1 +'` → ParseError: unexpected token 'EOF' ✓
|
||||
- `'(1'` → ParseError: expected ')', got 'EOF' ✓
|
||||
- `'1 2'` → ParseError: unexpected token 'NUMBER' ✓
|
||||
- `')('` → ParseError: unexpected token 'RPAREN' ✓
|
||||
- `''` → ParseError: empty input ✓
|
||||
|
||||
Adversarial: `+5` (unary plus) correctly raises ParseError (not in grammar, no crash) ✓
|
||||
|
||||
## D6: PASS @2026-06-15T02:27:10Z
|
||||
|
||||
```
|
||||
Ran 36 tests in 0.001s
|
||||
OK
|
||||
```
|
||||
|
||||
36 tests, 0 failures. Suite covers D1–D5 with structure-level assertions (not evaluation).
|
||||
|
||||
---
|
||||
|
||||
Adversary verdict: all gates D1–D6 independently verified cold. Implementation is correct.
|
||||
@ -0,0 +1,52 @@
|
||||
# STATUS — phase eval
|
||||
|
||||
## DONE
|
||||
|
||||
## Gates claimed: D1, D2, D3, D4, D5
|
||||
|
||||
### What is claimed
|
||||
|
||||
| Gate | Description |
|
||||
|------|-------------|
|
||||
| D1 | Arithmetic correctness: `+`, `-`, `*`, `/`, precedence, parens, unary minus |
|
||||
| D2 | True division; division by zero raises `EvalError` (not `ZeroDivisionError`) |
|
||||
| D3 | Whole results → `int`, non-whole → `float` |
|
||||
| D4 | CLI `calc.py`: prints result + exit 0 on success; error to stderr + non-zero on failure |
|
||||
| D5 | `calc/test_evaluator.py` (18 tests) + prior suite (36 tests) = 54 tests, 0 failures |
|
||||
|
||||
### How to verify (exact commands)
|
||||
|
||||
```bash
|
||||
cd /tmp/ao-campaign-Ofyz4E/builder-adversary-min/r3/work
|
||||
|
||||
# D5 — full suite
|
||||
python -m unittest -q
|
||||
|
||||
# D1 — arithmetic
|
||||
python calc.py "2+3*4" # expected: 14
|
||||
python calc.py "(2+3)*4" # expected: 20
|
||||
python calc.py "8-3-2" # expected: 3
|
||||
python calc.py "-2+5" # expected: 3
|
||||
python calc.py "2*-3" # expected: -6
|
||||
|
||||
# D2 — true division + EvalError
|
||||
python calc.py "7/2" # expected: 3.5
|
||||
python calc.py "1/0" # expected: error to stderr, exit non-zero
|
||||
|
||||
# D3 — result type
|
||||
python calc.py "4/2" # expected: 2 (int, no .0)
|
||||
python calc.py "7/2" # expected: 3.5 (float)
|
||||
|
||||
# D4 — CLI error handling
|
||||
python calc.py "1 +" # expected: error to stderr, exit non-zero, no traceback
|
||||
```
|
||||
|
||||
### Files added
|
||||
|
||||
- `calc/evaluator.py` — `evaluate(node) -> int | float`, `EvalError`
|
||||
- `calc.py` — top-level CLI
|
||||
- `calc/test_evaluator.py` — 18 unittest tests covering D1–D4
|
||||
|
||||
### Commit SHA
|
||||
|
||||
`fe7e562080ee15b1f13f962171cdc4719734b062`
|
||||
@ -0,0 +1,56 @@
|
||||
# Status — phase `lex`
|
||||
|
||||
## Claimed gates
|
||||
|
||||
- **D1** — integers and floats tokenize to NUMBER with correct numeric value
|
||||
- **D2** — `+ - * / ( )` tokenize to the right kinds
|
||||
- **D3** — whitespace skipped; invalid chars raise `LexError` with offending char and position
|
||||
- **D4** — `calc/test_lexer.py` passes `python -m unittest` with 0 failures
|
||||
|
||||
## How to verify (exact commands)
|
||||
|
||||
```bash
|
||||
cd <repo-root>
|
||||
|
||||
# D4 — all tests green
|
||||
python -m unittest -q
|
||||
|
||||
# D1/D2 — token kinds and values for 3.5*(1-2)
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"
|
||||
|
||||
# D3 — LexError raised for invalid char
|
||||
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
|
||||
```
|
||||
|
||||
## Expected results
|
||||
|
||||
`python -m unittest -q`:
|
||||
```
|
||||
Ran 18 tests in 0.000s
|
||||
|
||||
OK
|
||||
```
|
||||
|
||||
`tokenize('3.5*(1-2)')`:
|
||||
```
|
||||
[('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]
|
||||
```
|
||||
|
||||
`tokenize('1 @ 2')`:
|
||||
```
|
||||
raises calc.lexer.LexError: unexpected character '@' at position 2
|
||||
```
|
||||
|
||||
## Files
|
||||
|
||||
- `calc/__init__.py` — package marker
|
||||
- `calc/lexer.py` — `Token`, `LexError`, `tokenize()`
|
||||
- `calc/test_lexer.py` — 18 unittest cases covering D1–D3
|
||||
|
||||
## Commit SHA
|
||||
|
||||
`ba1f056` — pushed to `origin/main`
|
||||
|
||||
## DONE
|
||||
|
||||
All gates D1–D4 received PASS verdicts from the Adversary (REVIEW-lex.md @2026-06-15T02:16Z). No veto. Phase `lex` is complete.
|
||||
@ -0,0 +1,91 @@
|
||||
# STATUS — phase parse
|
||||
|
||||
## DONE
|
||||
|
||||
## Claimed gates: D1, D2, D3, D4, D5, D6
|
||||
|
||||
Commit: fa50146a5acbc9e7cf65a1e60e0b0fba2d8bd2ea (main)
|
||||
Files: `calc/parser.py`, `calc/test_parser.py`
|
||||
|
||||
---
|
||||
|
||||
## What is claimed
|
||||
|
||||
- **D1 — precedence**: `*`/`/` bind tighter than `+`/`-`
|
||||
- **D2 — left associativity**: same-precedence ops are left-associative
|
||||
- **D3 — parentheses**: parens override default precedence
|
||||
- **D4 — unary minus**: leading and nested unary minus handled
|
||||
- **D5 — errors**: malformed inputs raise `ParseError` (not any other exception)
|
||||
- **D6 — tests green**: `python -m unittest -q` → 36 tests, 0 failures
|
||||
|
||||
---
|
||||
|
||||
## How to verify (exact commands)
|
||||
|
||||
```bash
|
||||
# D6 — all tests green
|
||||
python -m unittest -q
|
||||
|
||||
# D1 — mul binds tighter than add
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; t=parse(tokenize('1+2*3')); print(t); assert str(t)==\"BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))\""
|
||||
|
||||
# D2 — left associativity subtraction
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; t=parse(tokenize('8-3-2')); print(t); assert str(t)==\"BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))\""
|
||||
|
||||
# D2 — left associativity division
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; t=parse(tokenize('8/4/2')); print(t); assert str(t)==\"BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))\""
|
||||
|
||||
# D3 — parens override precedence
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; t=parse(tokenize('(1+2)*3')); print(t); assert str(t)==\"BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))\""
|
||||
|
||||
# D4 — unary minus
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-5'))); print(parse(tokenize('-(1+2)'))); print(parse(tokenize('3 * -2')))"
|
||||
|
||||
# D5 — all five error inputs raise ParseError
|
||||
python -c "
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError
|
||||
for src in ['1 +', '(1', '1 2', ')(', '']:
|
||||
try:
|
||||
parse(tokenize(src))
|
||||
print('FAIL — no error for', repr(src))
|
||||
except ParseError:
|
||||
print('OK', repr(src))
|
||||
"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Expected output
|
||||
|
||||
**D6**: `Ran 36 tests ... OK`
|
||||
|
||||
**D1**: `BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))` (no assertion error)
|
||||
|
||||
**D2-sub**: `BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))` (no assertion error)
|
||||
|
||||
**D2-div**: `BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))` (no assertion error)
|
||||
|
||||
**D3**: `BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))` (no assertion error)
|
||||
|
||||
**D4**:
|
||||
```
|
||||
Unary('-', Num(5))
|
||||
Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
```
|
||||
|
||||
**D5**: Five lines all starting with `OK`
|
||||
|
||||
---
|
||||
|
||||
## AST shape reference
|
||||
|
||||
```
|
||||
Num(value) # numeric literal; value: int | float
|
||||
BinOp(op, left, right) # binary op; op in {'+', '-', '*', '/'}
|
||||
Unary(op, operand) # unary op; op == '-'
|
||||
```
|
||||
|
||||
Precedence (high → low): unary-minus > `*` `/` > `+` `-`
|
||||
Associativity: left for all binary operators
|
||||
1
calculators/builder-adversary-min/run-04/.gitignore
vendored
Normal file
1
calculators/builder-adversary-min/run-04/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
__pycache__/
|
||||
15
calculators/builder-adversary-min/run-04/GIT-LOG.txt
Normal file
15
calculators/builder-adversary-min/run-04/GIT-LOG.txt
Normal file
@ -0,0 +1,15 @@
|
||||
# git history (claim/review handshake), from the run's shared bare repo
|
||||
0c7519b status: eval phase DONE — all D1-D5 PASS per Adversary review
|
||||
75785e6 review(eval): PASS D1 D2 D3 D4 D5 — all gates cold-verified
|
||||
f80f0a0 status: pin commit 0a56046 in STATUS-eval for Adversary cold-verify
|
||||
0a56046 claim(D1): claim(D2): claim(D3): claim(D4): claim(D5): feat: add evaluator, CLI, and test_evaluator — eval phase complete
|
||||
ab5e8ca status: phase parse DONE — all D1-D6 PASS per Adversary review
|
||||
cfd7e13 review(parse): PASS D1 D2 D3 D4 D5 D6 — all gates cold-verified
|
||||
91b0f50 status: pin commit sha 00ca873 in STATUS-parse for Adversary cold-verify
|
||||
00ca873 claim(D1): claim(D2): claim(D3): claim(D4): claim(D5): claim(D6): feat: add calc parser with AST nodes, recursive descent, full test suite
|
||||
21757bb review(parse): Adversary initialized — awaiting Builder
|
||||
4e6c950 status: phase lex DONE — all D1-D4 PASS per Adversary review
|
||||
73a5cbd review(lex): PASS D1 D2 D3 D4 — all gates cold-verified
|
||||
27d885e status: update STATUS-lex with commit sha 80d7ee3
|
||||
80d7ee3 feat: add calc lexer with Token, LexError, tokenize() — phase lex D1-D4
|
||||
3726fb6 chore: seed
|
||||
1
calculators/builder-adversary-min/run-04/README.md
Normal file
1
calculators/builder-adversary-min/run-04/README.md
Normal file
@ -0,0 +1 @@
|
||||
# calc work repo
|
||||
1
calculators/builder-adversary-min/run-04/SOURCE.txt
Normal file
1
calculators/builder-adversary-min/run-04/SOURCE.txt
Normal file
@ -0,0 +1 @@
|
||||
original path: /tmp/ao-campaign-Ofyz4E/builder-adversary-min/r4
|
||||
24
calculators/builder-adversary-min/run-04/calc.py
Normal file
24
calculators/builder-adversary-min/run-04/calc.py
Normal file
@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
from calc.lexer import tokenize, LexError
|
||||
from calc.parser import parse, ParseError
|
||||
from calc.evaluator import evaluate, EvalError
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("usage: calc.py <expression>", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
expr = sys.argv[1]
|
||||
try:
|
||||
tokens = tokenize(expr)
|
||||
ast = parse(tokens)
|
||||
result = evaluate(ast)
|
||||
except (LexError, ParseError, EvalError) as e:
|
||||
print(f"error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print(result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
41
calculators/builder-adversary-min/run-04/calc/evaluator.py
Normal file
41
calculators/builder-adversary-min/run-04/calc/evaluator.py
Normal file
@ -0,0 +1,41 @@
|
||||
from calc.parser import Num, BinOp, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node):
|
||||
"""Walk the AST and return int | float.
|
||||
|
||||
Result type rule: if the mathematical value is a whole number, return int;
|
||||
otherwise return float.
|
||||
"""
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
v = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return _normalize(-v)
|
||||
raise EvalError(f"unknown unary op {node.op!r}")
|
||||
if isinstance(node, BinOp):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
if node.op == '+':
|
||||
return _normalize(left + right)
|
||||
if node.op == '-':
|
||||
return _normalize(left - right)
|
||||
if node.op == '*':
|
||||
return _normalize(left * right)
|
||||
if node.op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
return _normalize(left / right)
|
||||
raise EvalError(f"unknown binary op {node.op!r}")
|
||||
raise EvalError(f"unknown node type {type(node).__name__}")
|
||||
|
||||
|
||||
def _normalize(v):
|
||||
if isinstance(v, float) and v == int(v):
|
||||
return int(v)
|
||||
return v
|
||||
46
calculators/builder-adversary-min/run-04/calc/lexer.py
Normal file
46
calculators/builder-adversary-min/run-04/calc/lexer.py
Normal file
@ -0,0 +1,46 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Token:
|
||||
kind: str
|
||||
value: Union[int, float, str, None]
|
||||
|
||||
|
||||
_SINGLE = {
|
||||
'+': 'PLUS',
|
||||
'-': 'MINUS',
|
||||
'*': 'STAR',
|
||||
'/': 'SLASH',
|
||||
'(': 'LPAREN',
|
||||
')': 'RPAREN',
|
||||
}
|
||||
|
||||
|
||||
def tokenize(src: str) -> list:
|
||||
tokens = []
|
||||
i = 0
|
||||
while i < len(src):
|
||||
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
|
||||
while j < len(src) and (src[j].isdigit() or src[j] == '.'):
|
||||
j += 1
|
||||
num_str = src[i:j]
|
||||
value = float(num_str) if '.' in num_str else int(num_str)
|
||||
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
|
||||
106
calculators/builder-adversary-min/run-04/calc/parser.py
Normal file
106
calculators/builder-adversary-min/run-04/calc/parser.py
Normal file
@ -0,0 +1,106 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from calc.lexer import Token
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Num:
|
||||
value: Any
|
||||
|
||||
def __repr__(self):
|
||||
return f"Num({self.value!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
op: str
|
||||
left: Any
|
||||
right: Any
|
||||
|
||||
def __repr__(self):
|
||||
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
op: str
|
||||
operand: Any
|
||||
|
||||
def __repr__(self):
|
||||
return f"Unary({self.op!r}, {self.operand!r})"
|
||||
|
||||
|
||||
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!r}, 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):
|
||||
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})")
|
||||
return node
|
||||
|
||||
# expr → term (('+' | '-') term)*
|
||||
def _expr(self):
|
||||
node = self._term()
|
||||
while self._peek().kind in ('PLUS', 'MINUS'):
|
||||
op = self._advance().value
|
||||
right = self._term()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
# term → unary (('*' | '/') unary)*
|
||||
def _term(self):
|
||||
node = self._unary()
|
||||
while self._peek().kind in ('STAR', 'SLASH'):
|
||||
op = self._advance().value
|
||||
right = self._unary()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
# unary → '-' unary | primary
|
||||
def _unary(self):
|
||||
if self._peek().kind == 'MINUS':
|
||||
self._advance()
|
||||
return Unary('-', self._unary())
|
||||
return self._primary()
|
||||
|
||||
# primary → NUMBER | '(' expr ')'
|
||||
def _primary(self):
|
||||
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
|
||||
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")
|
||||
|
||||
|
||||
def parse(tokens: list):
|
||||
return _Parser(tokens).parse()
|
||||
@ -0,0 +1,63 @@
|
||||
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_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(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_minus_with_multiply(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
|
||||
class TestDivision(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_zerodivision(self):
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError escaped; expected EvalError")
|
||||
|
||||
|
||||
class TestResultType(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_integer_add(self):
|
||||
result = calc("1+1")
|
||||
self.assertEqual(result, 2)
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
90
calculators/builder-adversary-min/run-04/calc/test_lexer.py
Normal file
90
calculators/builder-adversary-min/run-04/calc/test_lexer.py
Normal file
@ -0,0 +1,90 @@
|
||||
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):
|
||||
def test_integer(self):
|
||||
tokens = tokenize("42")
|
||||
self.assertEqual(tokens[0], Token('NUMBER', 42))
|
||||
self.assertEqual(tokens[0].value, 42)
|
||||
self.assertIsInstance(tokens[0].value, int)
|
||||
self.assertEqual(tokens[1].kind, 'EOF')
|
||||
|
||||
def test_float(self):
|
||||
t = tokenize("3.14")
|
||||
self.assertEqual(t[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(t[0].value, 3.14)
|
||||
self.assertIsInstance(t[0].value, float)
|
||||
|
||||
def test_leading_dot(self):
|
||||
t = tokenize(".5")
|
||||
self.assertEqual(t[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(t[0].value, 0.5)
|
||||
|
||||
def test_trailing_dot(self):
|
||||
t = tokenize("10.")
|
||||
self.assertEqual(t[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(t[0].value, 10.0)
|
||||
self.assertIsInstance(t[0].value, float)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_1plus2star3(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_spaces_skipped(self):
|
||||
self.assertEqual(kinds(" 12 + 3 "),
|
||||
['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_tabs_skipped(self):
|
||||
self.assertEqual(kinds("1\t+\t2"), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_complex_expression(self):
|
||||
result = values("3.5*(1-2)")
|
||||
self.assertEqual(result, [
|
||||
('NUMBER', 3.5),
|
||||
('STAR', '*'),
|
||||
('LPAREN', '('),
|
||||
('NUMBER', 1),
|
||||
('MINUS', '-'),
|
||||
('NUMBER', 2),
|
||||
('RPAREN', ')'),
|
||||
('EOF', None),
|
||||
])
|
||||
|
||||
def test_invalid_at_raises(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('@', str(ctx.exception))
|
||||
|
||||
def test_invalid_dollar_raises(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$10")
|
||||
|
||||
def test_invalid_letter_raises(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("abc")
|
||||
|
||||
def test_error_message_includes_position(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('2', str(ctx.exception))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
106
calculators/builder-adversary-min/run-04/calc/test_parser.py
Normal file
106
calculators/builder-adversary-min/run-04/calc/test_parser.py
Normal file
@ -0,0 +1,106 @@
|
||||
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 → BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
result = p("1+2*3")
|
||||
self.assertEqual(result, BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
def test_add_over_mul_left(self):
|
||||
# 2*3+4 → BinOp('+', BinOp('*', Num(2), Num(3)), Num(4))
|
||||
result = p("2*3+4")
|
||||
self.assertEqual(result, BinOp('+', BinOp('*', Num(2), Num(3)), Num(4)))
|
||||
|
||||
def test_div_over_sub(self):
|
||||
# 10-6/2 → BinOp('-', Num(10), BinOp('/', Num(6), Num(2)))
|
||||
result = p("10-6/2")
|
||||
self.assertEqual(result, BinOp('-', Num(10), BinOp('/', Num(6), Num(2))))
|
||||
|
||||
|
||||
class TestLeftAssociativity(unittest.TestCase):
|
||||
def test_sub_left_assoc(self):
|
||||
# 8-3-2 → BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))
|
||||
result = p("8-3-2")
|
||||
self.assertEqual(result, BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)))
|
||||
|
||||
def test_div_left_assoc(self):
|
||||
# 8/4/2 → BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))
|
||||
result = p("8/4/2")
|
||||
self.assertEqual(result, BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)))
|
||||
|
||||
def test_add_left_assoc(self):
|
||||
# 1+2+3 → BinOp('+', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
result = p("1+2+3")
|
||||
self.assertEqual(result, BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
|
||||
class TestParentheses(unittest.TestCase):
|
||||
def test_parens_override_precedence(self):
|
||||
# (1+2)*3 → BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
result = p("(1+2)*3")
|
||||
self.assertEqual(result, BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_nested_parens(self):
|
||||
# ((4)) → Num(4)
|
||||
result = p("((4))")
|
||||
self.assertEqual(result, Num(4))
|
||||
|
||||
def test_parens_in_sum(self):
|
||||
# 2*(3+4) → BinOp('*', Num(2), BinOp('+', Num(3), Num(4)))
|
||||
result = p("2*(3+4)")
|
||||
self.assertEqual(result, BinOp('*', Num(2), BinOp('+', Num(3), Num(4))))
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
def test_simple_negation(self):
|
||||
# -5 → Unary('-', Num(5))
|
||||
result = p("-5")
|
||||
self.assertEqual(result, Unary('-', Num(5)))
|
||||
|
||||
def test_negation_of_group(self):
|
||||
# -(1+2) → Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
result = p("-(1+2)")
|
||||
self.assertEqual(result, Unary('-', BinOp('+', Num(1), Num(2))))
|
||||
|
||||
def test_mul_with_unary(self):
|
||||
# 3 * -2 → BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
result = p("3 * -2")
|
||||
self.assertEqual(result, BinOp('*', Num(3), Unary('-', Num(2))))
|
||||
|
||||
def test_double_negation(self):
|
||||
# --5 → Unary('-', Unary('-', Num(5)))
|
||||
result = p("--5")
|
||||
self.assertEqual(result, Unary('-', Unary('-', Num(5))))
|
||||
|
||||
|
||||
class TestErrors(unittest.TestCase):
|
||||
def test_trailing_op(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_before_open(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p(")(")
|
||||
|
||||
def test_empty(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@ -0,0 +1,9 @@
|
||||
# JOURNAL-eval
|
||||
|
||||
## Design notes
|
||||
|
||||
**evaluator.py**: Straightforward AST walker. `_normalize(v)` converts a float to int when `v == int(v)` — this handles the D3 requirement cleanly for both direct integer arithmetic and whole-valued division results. Division by zero is caught before the `/` operation and wrapped as `EvalError`.
|
||||
|
||||
**calc.py**: Catches `LexError`, `ParseError`, and `EvalError`; prints `error: <message>` to stderr and exits 1. No traceback leaks.
|
||||
|
||||
**test_evaluator.py**: 13 tests covering all D1 arithmetic cases, D2 true division and EvalError, D3 type assertions. Full 42-test suite (lex 16 + parse 13 + eval 13) passes.
|
||||
@ -0,0 +1,13 @@
|
||||
# JOURNAL — phase lex
|
||||
|
||||
## Approach
|
||||
|
||||
- `Token` is a `dataclass` with `kind: str` and `value: Union[int, float, str, None]`.
|
||||
- `tokenize()` is a simple single-pass scanner using index `i`.
|
||||
- Numbers: greedy scan of digits and `.`; if `.` present → `float`, else → `int`.
|
||||
- Operators/parens: single-char dispatch via `_SINGLE` dict.
|
||||
- Whitespace (space, tab): skipped silently.
|
||||
- Anything else: raises `LexError` with the offending char and position.
|
||||
- `EOF` token appended at the end.
|
||||
|
||||
## Test count: 13 — all green on first run.
|
||||
@ -0,0 +1,15 @@
|
||||
# JOURNAL-parse
|
||||
|
||||
## Design decisions
|
||||
|
||||
- **Grammar**: classic 3-level recursive descent:
|
||||
- `expr → term (('+' | '-') term)*` (lowest precedence)
|
||||
- `term → unary (('*' | '/') unary)*` (medium)
|
||||
- `unary → '-' unary | primary` (right-recursive for stacked unary)
|
||||
- `primary → NUMBER | '(' expr ')'`
|
||||
- Left associativity falls out naturally from the `while` loops in `_expr` and `_term`.
|
||||
- Unary is right-recursive (`-` `-` 5 → nested Unary) as is conventional.
|
||||
- Empty input detected early at `parse()` entry before any descent.
|
||||
- Trailing tokens detected after `_expr()` returns, before EOF check.
|
||||
|
||||
## Test count: 31 (20 parser + 11 existing lexer)
|
||||
@ -0,0 +1,38 @@
|
||||
# REVIEW — phase eval
|
||||
|
||||
Adversary cold-verify against commit `0a56046`.
|
||||
|
||||
## Results
|
||||
|
||||
| Gate | Verdict | Evidence |
|
||||
|------|---------|----------|
|
||||
| D1 | PASS | `2+3*4`→14, `(2+3)*4`→20, `8-3-2`→3, `-2+5`→3, `2*-3`→-6 |
|
||||
| D2 | PASS | `7/2`→3.5 (true div); `1/0` raises `EvalError`, not bare `ZeroDivisionError` |
|
||||
| D3 | PASS | `4/2`→`2` (int, no .0); `7/2`→`3.5` (float) |
|
||||
| D4 | PASS | `python calc.py "2+3*4"` prints `14`, exit 0; `python calc.py "1 +"` prints error to stderr only, exit 1; `python calc.py "1/0"` same |
|
||||
| D5 | PASS | `python -m unittest -q` → 42 tests, 0 failures; covers D1–D3 and full prior suite (lex + parse) |
|
||||
|
||||
## Verification commands run
|
||||
|
||||
```
|
||||
python -m unittest -q # 42 OK
|
||||
python calc.py "2+3*4" # 14, exit 0
|
||||
python calc.py "(2+3)*4" # 20, exit 0
|
||||
python calc.py "8-3-2" # 3
|
||||
python calc.py "-2+5" # 3
|
||||
python calc.py "2*-3" # -6
|
||||
python calc.py "7/2" # 3.5, exit 0
|
||||
python calc.py "4/2" # 2, exit 0
|
||||
python calc.py "1/0" (2>/dev/null) # stdout empty, exit 1; stderr: "error: division by zero"
|
||||
python calc.py "1 +" (2>/dev/null) # stdout empty, exit 1; stderr: "error: unexpected token 'EOF' (None)"
|
||||
```
|
||||
|
||||
## Verdict
|
||||
|
||||
eval/D1: PASS @2026-06-15T00:00:00Z
|
||||
eval/D2: PASS @2026-06-15T00:00:00Z
|
||||
eval/D3: PASS @2026-06-15T00:00:00Z
|
||||
eval/D4: PASS @2026-06-15T00:00:00Z
|
||||
eval/D5: PASS @2026-06-15T00:00:00Z
|
||||
|
||||
All five gates PASS. No VETO. Builder may write `## DONE` to `machine-docs/STATUS-eval.md`.
|
||||
@ -0,0 +1,50 @@
|
||||
# REVIEW — phase lex
|
||||
|
||||
Adversary cold-verification against commit `80d7ee3`.
|
||||
|
||||
## Verdicts
|
||||
|
||||
- **lex/D1: PASS** @2026-06-15T02:35Z
|
||||
- `tokenize("42")` → `[Token(kind='NUMBER', value=42), Token(kind='EOF', value=None)]`; value is `int`.
|
||||
- `tokenize("3.14")` → `NUMBER` with `float(3.14)`.
|
||||
- `tokenize(".5")` → `NUMBER 0.5`; `tokenize("10.")` → `NUMBER 10.0 float`.
|
||||
|
||||
- **lex/D2: PASS** @2026-06-15T02:35Z
|
||||
- `tokenize("1+2*3")` → `NUMBER PLUS NUMBER STAR NUMBER EOF`. ✓
|
||||
- `tokenize("+-*/()")` → `PLUS MINUS STAR SLASH LPAREN RPAREN EOF`. ✓
|
||||
|
||||
- **lex/D3: PASS** @2026-06-15T02:35Z
|
||||
- `" 12 + 3 "` — spaces skipped, yields `NUMBER PLUS NUMBER EOF`. ✓
|
||||
- `"\t"` (tabs) skipped. ✓
|
||||
- `tokenize("1 @ 2")` → `calc.lexer.LexError: unexpected character '@' at position 2` (exit 1). ✓
|
||||
- `"$10"` and `"abc"` also raise `LexError`. ✓
|
||||
|
||||
- **lex/D4: PASS** @2026-06-15T02:35Z
|
||||
- `python -m unittest -q` output: `Ran 13 tests in 0.000s / OK`. Zero failures.
|
||||
- Test suite covers `" 12 + 3 "`, `"3.5*(1-2)"`, `"1 @ 2"` raises `LexError`. ✓
|
||||
|
||||
## Evidence
|
||||
|
||||
```
|
||||
$ python -m unittest -q
|
||||
----------------------------------------------------------------------
|
||||
Ran 13 tests in 0.000s
|
||||
|
||||
OK
|
||||
|
||||
$ python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"
|
||||
[('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]
|
||||
|
||||
$ python -c "from calc.lexer import tokenize; tokenize('1 @ 2')" 2>&1
|
||||
calc.lexer.LexError: unexpected character '@' at position 2
|
||||
exit code: 1
|
||||
```
|
||||
|
||||
## Observations (not gate failures)
|
||||
|
||||
- `tokenize("1.2.3")` raises `ValueError: could not convert string to float: '1.2.3'` rather than `LexError`. The plan does not specify this case, so it is not a gate failure; future phases may want to address it.
|
||||
- STATUS-lex.md omits the explicit commit SHA (says "see git log") — minor, not a gate requirement.
|
||||
|
||||
## Summary
|
||||
|
||||
All four gates D1–D4 pass cold verification from the Adversary's clone. No veto.
|
||||
@ -0,0 +1,109 @@
|
||||
# REVIEW — phase parse (Adversary)
|
||||
|
||||
<!-- Verdicts: review(<id>): PASS|FAIL -->
|
||||
|
||||
## Verdicts
|
||||
|
||||
| Gate | Verdict | Timestamp |
|
||||
|------|---------|-----------|
|
||||
| D1 | PASS | 2026-06-15T02:42Z |
|
||||
| D2 | PASS | 2026-06-15T02:42Z |
|
||||
| D3 | PASS | 2026-06-15T02:42Z |
|
||||
| D4 | PASS | 2026-06-15T02:42Z |
|
||||
| D5 | PASS | 2026-06-15T02:42Z |
|
||||
| D6 | PASS | 2026-06-15T02:42Z |
|
||||
|
||||
---
|
||||
|
||||
## D1: PASS @2026-06-15T02:42Z
|
||||
|
||||
`*`/`/` bind tighter than `+`/`-`. Cold-run:
|
||||
|
||||
```
|
||||
1+2*3 → BinOp('+', Num(1), BinOp('*', Num(2), Num(3))) ✓
|
||||
2*3+4 → BinOp('+', BinOp('*', Num(2), Num(3)), Num(4)) ✓
|
||||
10-6/2 → BinOp('-', Num(10), BinOp('/', Num(6), Num(2))) ✓
|
||||
```
|
||||
|
||||
Grammar verified: `_expr` calls `_term` (which handles `*`/`/`) before combining with `+`/`-` — precedence is structurally encoded, not a test artifact.
|
||||
|
||||
---
|
||||
|
||||
## D2: PASS @2026-06-15T02:42Z
|
||||
|
||||
Left-associativity for all four operators. Cold-run:
|
||||
|
||||
```
|
||||
8-3-2 → BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)) ✓
|
||||
8/4/2 → BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)) ✓
|
||||
1+2+3 → BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)) ✓
|
||||
```
|
||||
|
||||
Associativity comes from `while` loops in `_expr`/`_term` that accumulate left into `node` — correct by construction.
|
||||
|
||||
---
|
||||
|
||||
## D3: PASS @2026-06-15T02:42Z
|
||||
|
||||
Parentheses override precedence. Cold-run:
|
||||
|
||||
```
|
||||
(1+2)*3 → BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)) ✓
|
||||
((4)) → Num(4) ✓
|
||||
2*(3+4) → BinOp('*', Num(2), BinOp('+', Num(3), Num(4))) ✓
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## D4: PASS @2026-06-15T02:42Z
|
||||
|
||||
Unary minus: leading, nested, after binary operator, double negation. Cold-run:
|
||||
|
||||
```
|
||||
-5 → Unary('-', Num(5)) ✓
|
||||
-(1+2) → Unary('-', BinOp('+', Num(1), Num(2))) ✓
|
||||
3 * -2 → BinOp('*', Num(3), Unary('-', Num(2))) ✓
|
||||
--5 → Unary('-', Unary('-', Num(5))) ✓
|
||||
```
|
||||
|
||||
Adversarial: `---5 → Unary('-', Unary('-', Unary('-', Num(5))))` ✓, `(-5)*3 → BinOp('*', Unary('-', Num(5)), Num(3))` ✓.
|
||||
|
||||
---
|
||||
|
||||
## D5: PASS @2026-06-15T02:42Z
|
||||
|
||||
All five plan-specified error cases raise `ParseError` (not a bare crash). Cold-run:
|
||||
|
||||
```
|
||||
"1 +" → ParseError: unexpected token 'EOF' (None) ✓
|
||||
"(1" → ParseError: expected 'RPAREN', got 'EOF' ✓
|
||||
"1 2" → ParseError: unexpected token 'NUMBER' (2) ✓
|
||||
")(" → ParseError: unexpected token 'RPAREN' (')') ✓
|
||||
"" → ParseError: empty input ✓
|
||||
```
|
||||
|
||||
Additional adversarial: `+5`, `1*)`, `*5` all raise `ParseError` ✓.
|
||||
|
||||
---
|
||||
|
||||
## D6: PASS @2026-06-15T02:42Z
|
||||
|
||||
```
|
||||
python -m unittest -q
|
||||
Ran 31 tests in 0.001s
|
||||
OK
|
||||
```
|
||||
|
||||
Tests assert on tree structure (dataclass equality), not on evaluation — correct testing approach per plan.
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
Grammar is clean recursive descent:
|
||||
- `expr → term (('+' | '-') term)*`
|
||||
- `term → unary (('*' | '/') unary)*`
|
||||
- `unary → '-' unary | primary`
|
||||
- `primary → NUMBER | '(' expr ')'`
|
||||
|
||||
Precedence and associativity are structurally encoded, not patched in. No weak tests that would pass a wrong implementation found.
|
||||
@ -0,0 +1,48 @@
|
||||
# STATUS-eval
|
||||
|
||||
Commit: 0a560468a157c0026515ee3edb9b8aff6b6a41ab
|
||||
|
||||
## Claims
|
||||
|
||||
| Gate | DoD item | Claim |
|
||||
|------|----------|-------|
|
||||
| D1 | arithmetic (+ - * /, precedence, parens, unary minus) | CLAIMED |
|
||||
| D2 | true division; EvalError on div-by-zero | CLAIMED |
|
||||
| D3 | whole-valued → int, non-whole → float | CLAIMED |
|
||||
| D4 | CLI prints result, exits 0; bad input → stderr, non-zero | CLAIMED |
|
||||
| D5 | test_evaluator.py passes; full suite (lex+parse+eval) passes | CLAIMED |
|
||||
|
||||
## Files changed
|
||||
|
||||
- `calc/evaluator.py` — `evaluate(node) -> int | float`, `EvalError`
|
||||
- `calc/test_evaluator.py` — 13 unittest cases for D1–D3
|
||||
- `calc.py` — CLI entry point for D4
|
||||
|
||||
## Verify commands (exact, in working directory)
|
||||
|
||||
```bash
|
||||
# D5 — full suite
|
||||
python -m unittest -q
|
||||
# expected: Ran 42 tests in ... OK
|
||||
|
||||
# D1
|
||||
python calc.py "2+3*4" # expected: 14
|
||||
python calc.py "(2+3)*4" # expected: 20
|
||||
python calc.py "8-3-2" # expected: 3
|
||||
python calc.py "-2+5" # expected: 3
|
||||
python calc.py "2*-3" # expected: -6
|
||||
|
||||
# D2
|
||||
python calc.py "7/2" # expected: 3.5
|
||||
python calc.py "1/0" # expected: error to stderr, exit code 1
|
||||
|
||||
# D3
|
||||
python calc.py "4/2" # expected: 2 (int, no .0)
|
||||
python calc.py "7/2" # expected: 3.5 (float)
|
||||
|
||||
# D4
|
||||
python calc.py "2+3*4" # expected stdout: 14, exit 0
|
||||
python calc.py "1 +" # expected: error to stderr, exit non-zero (no traceback)
|
||||
```
|
||||
|
||||
## DONE
|
||||
@ -0,0 +1,49 @@
|
||||
## DONE
|
||||
|
||||
# STATUS — phase lex
|
||||
|
||||
## Claimed gates
|
||||
|
||||
- **D1** — numbers (integers, floats, leading/trailing dot)
|
||||
- **D2** — operators & parens (`+ - * / ( )`)
|
||||
- **D3** — whitespace skipped; invalid chars raise `LexError` with char and position
|
||||
- **D4** — test suite 13/13 green, 0 failures
|
||||
|
||||
## How to verify (exact commands)
|
||||
|
||||
```bash
|
||||
cd <repo-root>
|
||||
|
||||
# D4 — run all tests
|
||||
python -m unittest -q
|
||||
|
||||
# D1+D2 — manual check for 3.5*(1-2)
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"
|
||||
|
||||
# D3 — must raise LexError
|
||||
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
|
||||
```
|
||||
|
||||
## Expected results
|
||||
|
||||
```
|
||||
# python -m unittest -q
|
||||
Ran 13 tests in 0.000s
|
||||
OK
|
||||
|
||||
# 3.5*(1-2)
|
||||
[('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]
|
||||
|
||||
# 1 @ 2 — exits non-zero with:
|
||||
calc.lexer.LexError: unexpected character '@' at position 2
|
||||
```
|
||||
|
||||
## Files
|
||||
|
||||
- `calc/__init__.py` — package marker
|
||||
- `calc/lexer.py` — `Token`, `LexError`, `tokenize()`
|
||||
- `calc/test_lexer.py` — 13 unittest cases covering D1–D3
|
||||
|
||||
## Commit SHA
|
||||
|
||||
`80d7ee3` — feat: add calc lexer with Token, LexError, tokenize() — phase lex D1-D4
|
||||
@ -0,0 +1,120 @@
|
||||
# STATUS-parse
|
||||
|
||||
## DONE
|
||||
|
||||
## Claim
|
||||
|
||||
All DoD gates D1–D6 implemented and verified.
|
||||
|
||||
| Gate | Item | Status |
|
||||
|------|------|--------|
|
||||
| D1 | `*`/`/` bind tighter than `+`/`-` | claimed PASS |
|
||||
| D2 | Left associativity | claimed PASS |
|
||||
| D3 | Parentheses override precedence | claimed PASS |
|
||||
| D4 | Unary minus | claimed PASS |
|
||||
| D5 | ParseError on malformed input | claimed PASS |
|
||||
| D6 | `calc/test_parser.py` — 31 tests, 0 failures | claimed PASS |
|
||||
|
||||
## Files
|
||||
|
||||
- `calc/parser.py` — parser implementation
|
||||
- `calc/test_parser.py` — unittest suite
|
||||
|
||||
Commit: `00ca873` (claim(D1-D6): feat: add calc parser with AST nodes, recursive descent, full test suite)
|
||||
|
||||
## How to verify
|
||||
|
||||
```bash
|
||||
# D6 — all tests
|
||||
python -m unittest -q
|
||||
# Expected: OK (31 tests, 0 failures)
|
||||
|
||||
# D1 — mul binds tighter than add
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('1+2*3')))"
|
||||
# Expected: BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
|
||||
# D2 — left associativity of subtraction
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8-3-2')))"
|
||||
# Expected: BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))
|
||||
|
||||
# D2 — left associativity of division
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8/4/2')))"
|
||||
# Expected: BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))
|
||||
|
||||
# D3 — parens override precedence
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('(1+2)*3')))"
|
||||
# Expected: BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
|
||||
# D4 — unary minus with binary mul
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('3 * -2')))"
|
||||
# Expected: BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
|
||||
# D4 — negation of group
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-(1+2)')))"
|
||||
# Expected: Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
|
||||
# D5 — ParseError on "1 +"
|
||||
python -c "
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError
|
||||
try:
|
||||
parse(tokenize('1 +'))
|
||||
print('ERROR: no exception raised')
|
||||
except ParseError as e:
|
||||
print('OK ParseError:', e)
|
||||
"
|
||||
|
||||
# D5 — ParseError on "(1"
|
||||
python -c "
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError
|
||||
try:
|
||||
parse(tokenize('(1'))
|
||||
print('ERROR: no exception raised')
|
||||
except ParseError as e:
|
||||
print('OK ParseError:', e)
|
||||
"
|
||||
|
||||
# D5 — ParseError on "1 2"
|
||||
python -c "
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError
|
||||
try:
|
||||
parse(tokenize('1 2'))
|
||||
print('ERROR: no exception raised')
|
||||
except ParseError as e:
|
||||
print('OK ParseError:', e)
|
||||
"
|
||||
|
||||
# D5 — ParseError on ")("
|
||||
python -c "
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError
|
||||
try:
|
||||
parse(tokenize(')('))
|
||||
print('ERROR: no exception raised')
|
||||
except ParseError as e:
|
||||
print('OK ParseError:', e)
|
||||
"
|
||||
|
||||
# D5 — ParseError on empty string
|
||||
python -c "
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError
|
||||
try:
|
||||
parse(tokenize(''))
|
||||
print('ERROR: no exception raised')
|
||||
except ParseError as e:
|
||||
print('OK ParseError:', e)
|
||||
"
|
||||
```
|
||||
|
||||
## AST Node shapes
|
||||
|
||||
```
|
||||
Num(value) — leaf, value is int or float
|
||||
BinOp(op, left, right) — op is one of '+', '-', '*', '/'
|
||||
Unary(op, operand) — op is '-'
|
||||
```
|
||||
|
||||
All are dataclasses with `__repr__` that prints the form above.
|
||||
2
calculators/builder-adversary-min/run-05/.gitignore
vendored
Normal file
2
calculators/builder-adversary-min/run-05/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
15
calculators/builder-adversary-min/run-05/GIT-LOG.txt
Normal file
15
calculators/builder-adversary-min/run-05/GIT-LOG.txt
Normal file
@ -0,0 +1,15 @@
|
||||
# git history (claim/review handshake), from the run's shared bare repo
|
||||
7f3225b status(eval): DONE — all D1-D5 gates have Adversary PASS
|
||||
51326b3 review(D1-D5): PASS — all eval gates verified at 3ff8ae9
|
||||
ae29de4 status(eval): add commit sha 3ff8ae9 to STATUS-eval
|
||||
3ff8ae9 claim(D1-D5): eval phase — evaluator + CLI + tests
|
||||
be7e44c chore(adversary): init REVIEW-eval.md
|
||||
2c9edec status(parse): DONE — all D1-D6 gates have Adversary PASS
|
||||
7f5ade2 review(D1-D6): PASS — all parse gates verified at d97df78
|
||||
d97df78 claim(D1-D6): parse phase — recursive-descent parser + tests
|
||||
6ce30b9 chore(adversary): init REVIEW-parse.md
|
||||
c1042d0 status(lex): DONE — all D1-D4 gates have Adversary PASS
|
||||
8766211 review(D1-D4): PASS — all DoD gates verified at 8d523a2
|
||||
8d523a2 feat: lex phase — calc lexer + tests, claim D1-D4
|
||||
d28794c chore(adversary): init REVIEW-lex.md
|
||||
9ef3897 chore: seed
|
||||
1
calculators/builder-adversary-min/run-05/README.md
Normal file
1
calculators/builder-adversary-min/run-05/README.md
Normal file
@ -0,0 +1 @@
|
||||
# calc work repo
|
||||
1
calculators/builder-adversary-min/run-05/SOURCE.txt
Normal file
1
calculators/builder-adversary-min/run-05/SOURCE.txt
Normal file
@ -0,0 +1 @@
|
||||
original path: /tmp/ao-campaign-W2XI96/builder-adversary-min/r1
|
||||
22
calculators/builder-adversary-min/run-05/calc.py
Normal file
22
calculators/builder-adversary-min/run-05/calc.py
Normal file
@ -0,0 +1,22 @@
|
||||
"""CLI entry point: python calc.py "<expression>" """
|
||||
import sys
|
||||
from calc.lexer import tokenize, LexError
|
||||
from calc.parser import parse, ParseError
|
||||
from calc.evaluator import evaluate, EvalError
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("usage: python calc.py \"<expression>\"", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
expr = sys.argv[1]
|
||||
try:
|
||||
result = evaluate(parse(tokenize(expr)))
|
||||
except (LexError, ParseError, EvalError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print(result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
45
calculators/builder-adversary-min/run-05/calc/evaluator.py
Normal file
45
calculators/builder-adversary-min/run-05/calc/evaluator.py
Normal file
@ -0,0 +1,45 @@
|
||||
"""
|
||||
Evaluator for arithmetic AST nodes produced by calc.parser.
|
||||
|
||||
evaluate(node) -> int | float
|
||||
|
||||
Result-type rule: if the computed value is a whole number (no fractional
|
||||
part), it is returned as int; otherwise as float. This ensures "4/2" -> 2
|
||||
and "7/2" -> 3.5 without callers having to special-case anything.
|
||||
|
||||
Division-by-zero raises EvalError, not a bare ZeroDivisionError.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from calc.parser import Num, BinOp, Unary, Node
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node: Node) -> int | float:
|
||||
result = _eval(node)
|
||||
if isinstance(result, float) and result == int(result):
|
||||
return int(result)
|
||||
return result
|
||||
|
||||
|
||||
def _eval(node: Node) -> int | float:
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
return -_eval(node.operand)
|
||||
if isinstance(node, BinOp):
|
||||
left = _eval(node.left)
|
||||
right = _eval(node.right)
|
||||
if node.op == '+':
|
||||
return left + right
|
||||
if node.op == '-':
|
||||
return left - right
|
||||
if node.op == '*':
|
||||
return left * right
|
||||
if node.op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
return left / right
|
||||
raise EvalError(f"unknown node type: {type(node).__name__}")
|
||||
48
calculators/builder-adversary-min/run-05/calc/lexer.py
Normal file
48
calculators/builder-adversary-min/run-05/calc/lexer.py
Normal file
@ -0,0 +1,48 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Token:
|
||||
kind: str
|
||||
value: Union[int, float, str, None]
|
||||
|
||||
|
||||
_SINGLE = {
|
||||
'+': 'PLUS',
|
||||
'-': 'MINUS',
|
||||
'*': 'STAR',
|
||||
'/': 'SLASH',
|
||||
'(': 'LPAREN',
|
||||
')': 'RPAREN',
|
||||
}
|
||||
|
||||
|
||||
def tokenize(src: str) -> list:
|
||||
tokens = []
|
||||
i = 0
|
||||
while i < len(src):
|
||||
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 == '.':
|
||||
start = i
|
||||
has_dot = False
|
||||
while i < len(src) and (src[i].isdigit() or (src[i] == '.' and not has_dot)):
|
||||
if src[i] == '.':
|
||||
has_dot = True
|
||||
i += 1
|
||||
raw = src[start:i]
|
||||
value = float(raw) if has_dot else int(raw)
|
||||
tokens.append(Token('NUMBER', value))
|
||||
else:
|
||||
raise LexError(f"unexpected character {ch!r} at position {i}")
|
||||
tokens.append(Token('EOF', None))
|
||||
return tokens
|
||||
126
calculators/builder-adversary-min/run-05/calc/parser.py
Normal file
126
calculators/builder-adversary-min/run-05/calc/parser.py
Normal file
@ -0,0 +1,126 @@
|
||||
"""
|
||||
Recursive-descent parser for arithmetic expressions.
|
||||
|
||||
AST node shapes:
|
||||
Num(value) — a numeric literal; value is int or float
|
||||
BinOp(op, left, right) — binary operation; op is '+', '-', '*', or '/'
|
||||
Unary(op, operand) — unary minus; op is '-'
|
||||
|
||||
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
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@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]
|
||||
|
||||
|
||||
class _Parser:
|
||||
def __init__(self, tokens: list) -> None:
|
||||
self._tokens = tokens
|
||||
self._pos = 0
|
||||
|
||||
def _peek(self):
|
||||
return self._tokens[self._pos]
|
||||
|
||||
def _consume(self, kind: str = 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} ({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 = self._consume().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 = self._consume().value
|
||||
right = self._unary()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
def _unary(self) -> Node:
|
||||
if self._peek().kind == "MINUS":
|
||||
op = self._consume().value
|
||||
operand = self._unary()
|
||||
return Unary(op, operand)
|
||||
return self._primary()
|
||||
|
||||
def _primary(self) -> Node:
|
||||
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 ')' but got {self._peek().kind!r}"
|
||||
)
|
||||
self._consume("RPAREN")
|
||||
return node
|
||||
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."""
|
||||
return _Parser(tokens).parse()
|
||||
@ -0,0 +1,82 @@
|
||||
"""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):
|
||||
def test_addition(self):
|
||||
self.assertEqual(calc("2+3"), 5)
|
||||
|
||||
def test_subtraction(self):
|
||||
self.assertEqual(calc("5-3"), 2)
|
||||
|
||||
def test_multiplication(self):
|
||||
self.assertEqual(calc("3*4"), 12)
|
||||
|
||||
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_simple(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_minus_in_product(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
def test_unary_minus_standalone(self):
|
||||
self.assertEqual(calc("-5"), -5)
|
||||
|
||||
def test_nested_parens(self):
|
||||
self.assertEqual(calc("((2+3))*4"), 20)
|
||||
|
||||
|
||||
class TestDivision(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_zero_numerator(self):
|
||||
self.assertEqual(calc("0/5"), 0)
|
||||
|
||||
def test_chained_division(self):
|
||||
self.assertEqual(calc("8/4/2"), 1)
|
||||
|
||||
|
||||
class TestResultType(unittest.TestCase):
|
||||
def test_whole_division_returns_int(self):
|
||||
result = calc("4/2")
|
||||
self.assertEqual(result, 2)
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
def test_fractional_division_returns_float(self):
|
||||
result = calc("7/2")
|
||||
self.assertEqual(result, 3.5)
|
||||
self.assertIsInstance(result, float)
|
||||
|
||||
def test_integer_arithmetic_returns_int(self):
|
||||
result = calc("2+3*4")
|
||||
self.assertEqual(result, 14)
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
def test_unary_result_type(self):
|
||||
result = calc("-2+5")
|
||||
self.assertEqual(result, 3)
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
97
calculators/builder-adversary-min/run-05/calc/test_lexer.py
Normal file
97
calculators/builder-adversary-min/run-05/calc/test_lexer.py
Normal file
@ -0,0 +1,97 @@
|
||||
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):
|
||||
def test_integer(self):
|
||||
toks = tokenize("42")
|
||||
self.assertEqual(toks[0], Token('NUMBER', 42))
|
||||
self.assertIsInstance(toks[0].value, int)
|
||||
self.assertEqual(toks[1].kind, 'EOF')
|
||||
|
||||
def test_float(self):
|
||||
toks = tokenize("3.14")
|
||||
self.assertAlmostEqual(toks[0].value, 3.14)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
def test_leading_dot(self):
|
||||
toks = tokenize(".5")
|
||||
self.assertAlmostEqual(toks[0].value, 0.5)
|
||||
|
||||
def test_trailing_dot(self):
|
||||
toks = tokenize("10.")
|
||||
self.assertAlmostEqual(toks[0].value, 10.0)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
def test_tokenize_42_eof(self):
|
||||
toks = tokenize("42")
|
||||
self.assertEqual(kinds("42"), ['NUMBER', 'EOF'])
|
||||
self.assertEqual(toks[0].value, 42)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_all_operators(self):
|
||||
self.assertEqual(kinds("+"), ['PLUS', 'EOF'])
|
||||
self.assertEqual(kinds("-"), ['MINUS', 'EOF'])
|
||||
self.assertEqual(kinds("*"), ['STAR', 'EOF'])
|
||||
self.assertEqual(kinds("/"), ['SLASH', 'EOF'])
|
||||
self.assertEqual(kinds("("), ['LPAREN', 'EOF'])
|
||||
self.assertEqual(kinds(")"), ['RPAREN', 'EOF'])
|
||||
|
||||
def test_expression(self):
|
||||
self.assertEqual(kinds("1+2*3"), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_complex_expression(self):
|
||||
self.assertEqual(kinds("3.5*(1-2)"),
|
||||
['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'])
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def test_whitespace_skipped(self):
|
||||
self.assertEqual(kinds(" 12 + 3 "), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
toks = tokenize(" 12 + 3 ")
|
||||
self.assertEqual(toks[0].value, 12)
|
||||
self.assertEqual(toks[2].value, 3)
|
||||
|
||||
def test_tab_skipped(self):
|
||||
self.assertEqual(kinds("1\t+\t2"), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
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(self):
|
||||
try:
|
||||
tokenize("1 @ 2")
|
||||
self.fail("Expected LexError")
|
||||
except LexError as e:
|
||||
self.assertIn('@', str(e))
|
||||
|
||||
def test_complex_with_parens(self):
|
||||
toks = tokenize("3.5*(1-2)")
|
||||
kinds_list = [t.kind for t in toks]
|
||||
self.assertEqual(kinds_list,
|
||||
['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'])
|
||||
self.assertAlmostEqual(toks[0].value, 3.5)
|
||||
self.assertEqual(toks[3].value, 1)
|
||||
self.assertEqual(toks[5].value, 2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
110
calculators/builder-adversary-min/run-05/calc/test_parser.py
Normal file
110
calculators/builder-adversary-min/run-05/calc/test_parser.py
Normal file
@ -0,0 +1,110 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError, Num, BinOp, Unary
|
||||
|
||||
|
||||
def p(src):
|
||||
return parse(tokenize(src))
|
||||
|
||||
|
||||
class TestD1Precedence(unittest.TestCase):
|
||||
def test_add_mul(self):
|
||||
# 1+2*3 => BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
result = p("1+2*3")
|
||||
self.assertEqual(result, BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
def test_mul_add(self):
|
||||
# 2*3+1 => BinOp('+', BinOp('*', Num(2), Num(3)), Num(1))
|
||||
result = p("2*3+1")
|
||||
self.assertEqual(result, BinOp('+', BinOp('*', Num(2), Num(3)), Num(1)))
|
||||
|
||||
def test_sub_div(self):
|
||||
# 10-4/2 => BinOp('-', Num(10), BinOp('/', Num(4), Num(2)))
|
||||
result = p("10-4/2")
|
||||
self.assertEqual(result, BinOp('-', Num(10), BinOp('/', Num(4), Num(2))))
|
||||
|
||||
|
||||
class TestD2LeftAssociativity(unittest.TestCase):
|
||||
def test_sub_left(self):
|
||||
# 8-3-2 => BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))
|
||||
result = p("8-3-2")
|
||||
self.assertEqual(result, BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)))
|
||||
|
||||
def test_div_left(self):
|
||||
# 8/4/2 => BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))
|
||||
result = p("8/4/2")
|
||||
self.assertEqual(result, BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)))
|
||||
|
||||
def test_add_left(self):
|
||||
# 1+2+3 => BinOp('+', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
result = p("1+2+3")
|
||||
self.assertEqual(result, BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_mul_left(self):
|
||||
# 2*3*4 => BinOp('*', BinOp('*', Num(2), Num(3)), Num(4))
|
||||
result = p("2*3*4")
|
||||
self.assertEqual(result, BinOp('*', BinOp('*', Num(2), Num(3)), Num(4)))
|
||||
|
||||
|
||||
class TestD3Parentheses(unittest.TestCase):
|
||||
def test_paren_overrides_precedence(self):
|
||||
# (1+2)*3 => BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
result = p("(1+2)*3")
|
||||
self.assertEqual(result, BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_nested_parens(self):
|
||||
# ((2+3)) => BinOp('+', Num(2), Num(3))
|
||||
result = p("((2+3))")
|
||||
self.assertEqual(result, BinOp('+', Num(2), Num(3)))
|
||||
|
||||
def test_paren_in_sub(self):
|
||||
# 10-(2+3) => BinOp('-', Num(10), BinOp('+', Num(2), Num(3)))
|
||||
result = p("10-(2+3)")
|
||||
self.assertEqual(result, BinOp('-', Num(10), BinOp('+', Num(2), Num(3))))
|
||||
|
||||
|
||||
class TestD4UnaryMinus(unittest.TestCase):
|
||||
def test_simple_unary(self):
|
||||
# -5 => Unary('-', Num(5))
|
||||
result = p("-5")
|
||||
self.assertEqual(result, Unary('-', Num(5)))
|
||||
|
||||
def test_unary_paren(self):
|
||||
# -(1+2) => Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
result = p("-(1+2)")
|
||||
self.assertEqual(result, Unary('-', BinOp('+', Num(1), Num(2))))
|
||||
|
||||
def test_mul_unary(self):
|
||||
# 3*-2 => BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
result = p("3 * -2")
|
||||
self.assertEqual(result, BinOp('*', Num(3), Unary('-', Num(2))))
|
||||
|
||||
def test_double_unary(self):
|
||||
# --5 => Unary('-', Unary('-', Num(5)))
|
||||
result = p("--5")
|
||||
self.assertEqual(result, Unary('-', Unary('-', Num(5))))
|
||||
|
||||
|
||||
class TestD5Errors(unittest.TestCase):
|
||||
def _raises(self, src):
|
||||
with self.assertRaises(ParseError):
|
||||
p(src)
|
||||
|
||||
def test_trailing_operator(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_string(self):
|
||||
self._raises("")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -0,0 +1,9 @@
|
||||
# JOURNAL — phase lex
|
||||
|
||||
## Implementation notes
|
||||
|
||||
- Used `dataclass` for `Token` so equality works naturally in tests.
|
||||
- `value` field: int for integers, float for floats (including `.5` and `10.`), str for operators, None for EOF.
|
||||
- Number parsing handles leading-dot (`.5`) and trailing-dot (`10.`) cases via a single scan loop tracking `has_dot`.
|
||||
- `LexError` extends `Exception` directly; message includes the char repr and position index.
|
||||
- 15 tests cover all DoD items plus edge cases (tab whitespace, `$`, letter `x`).
|
||||
@ -0,0 +1,19 @@
|
||||
# JOURNAL-parse
|
||||
|
||||
## Implementation notes
|
||||
|
||||
Grammar chosen (standard arithmetic precedence):
|
||||
```
|
||||
expr := term (('+' | '-') term)*
|
||||
term := unary (('*' | '/') unary)*
|
||||
unary := '-' unary | primary
|
||||
primary := NUMBER | '(' expr ')'
|
||||
```
|
||||
|
||||
`unary` is right-recursive, which gives right-associativity to stacked unary minuses (e.g. `--5` → `Unary('-', Unary('-', Num(5)))`). This is standard.
|
||||
|
||||
`expr` and `term` are iterative loops (not recursive), so same-level operators are naturally left-associative.
|
||||
|
||||
The `ParseError` class is defined in `parser.py` (not lexer.py) since it's the parser's concern. All five D5 error cases raise `ParseError`, not a generic exception.
|
||||
|
||||
Tests assert on exact tree structure using `==` on dataclasses, not on evaluation results, per the plan's requirement.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user