artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
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
|
||||
Reference in New Issue
Block a user