artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
2
calculators/builder-adversary-stateless/run-01/.gitignore
vendored
Normal file
2
calculators/builder-adversary-stateless/run-01/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
16
calculators/builder-adversary-stateless/run-01/GIT-LOG.txt
Normal file
16
calculators/builder-adversary-stateless/run-01/GIT-LOG.txt
Normal file
@ -0,0 +1,16 @@
|
||||
# git history (claim/review handshake), from the run's shared bare repo
|
||||
b30af2d status: eval phase DONE — all D1-D5 PASS, no Adversary findings
|
||||
6ee8abb review(D1,D2,D3,D4,D5): PASS — all eval gates verified, no defects found
|
||||
732a9df claim(D1,D2,D3,D4,D5): evaluator + CLI + tests complete
|
||||
6d4fbb6 feat(eval): evaluator + CLI + tests
|
||||
eb590b3 review(eval): Adversary initialized REVIEW-eval.md for eval phase
|
||||
8e9b6c3 status: parse phase DONE — all D1-D6 PASS, no Adversary findings
|
||||
4ef7254 review(D1,D2,D3,D4,D5,D6): PASS — all gates verified, no defects found
|
||||
deb7758 claim(D1,D2,D3,D4,D5,D6): parser implementation + tests green
|
||||
3ce93b6 review(init): Adversary initialized REVIEW-parse.md for parse phase
|
||||
d9dd96f fix(AF-1): bare dot raises LexError instead of leaking ValueError
|
||||
163d7ae review(D1,D2,D3,D4): PASS — all gates verified; AF-1 bare-dot ValueError (non-blocking)
|
||||
0777cb8 status: update SHA in STATUS-lex.md
|
||||
328d25f claim(D1,D2,D3,D4): lexer implementation + tests green
|
||||
b1b03af review(init): Adversary initialized REVIEW-lex.md and JOURNAL-lex.md
|
||||
f47b649 chore: seed
|
||||
1
calculators/builder-adversary-stateless/run-01/README.md
Normal file
1
calculators/builder-adversary-stateless/run-01/README.md
Normal file
@ -0,0 +1 @@
|
||||
# calc work repo
|
||||
@ -0,0 +1 @@
|
||||
original path: /tmp/ao-campaign-ufRkmF/builder-adversary-stateless/r1
|
||||
23
calculators/builder-adversary-stateless/run-01/calc.py
Normal file
23
calculators/builder-adversary-stateless/run-01/calc.py
Normal file
@ -0,0 +1,23 @@
|
||||
#!/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()
|
||||
@ -0,0 +1,34 @@
|
||||
from calc.parser import Num, BinOp, Unary, Node
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node: Node) -> "int | float":
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
v = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return -v
|
||||
raise EvalError(f"unknown unary op {node.op!r}")
|
||||
if isinstance(node, BinOp):
|
||||
l = evaluate(node.left)
|
||||
r = evaluate(node.right)
|
||||
if node.op == '+':
|
||||
result = l + r
|
||||
elif node.op == '-':
|
||||
result = l - r
|
||||
elif node.op == '*':
|
||||
result = l * r
|
||||
elif node.op == '/':
|
||||
if r == 0:
|
||||
raise EvalError("division by zero")
|
||||
result = l / r
|
||||
else:
|
||||
raise EvalError(f"unknown binary op {node.op!r}")
|
||||
if isinstance(result, float) and result == int(result):
|
||||
return int(result)
|
||||
return result
|
||||
raise EvalError(f"unknown node type {type(node)!r}")
|
||||
62
calculators/builder-adversary-stateless/run-01/calc/lexer.py
Normal file
62
calculators/builder-adversary-stateless/run-01/calc/lexer.py
Normal file
@ -0,0 +1,62 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Token:
|
||||
kind: str
|
||||
value: Union[int, float, str, None]
|
||||
|
||||
def __repr__(self):
|
||||
return f"{self.kind}({self.value!r})"
|
||||
|
||||
|
||||
_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 in _SINGLE:
|
||||
tokens.append(Token(_SINGLE[ch], ch))
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if ch.isdigit() or ch == '.':
|
||||
j = i
|
||||
has_dot = False
|
||||
while j < len(src) and (src[j].isdigit() or (src[j] == '.' and not has_dot)):
|
||||
if src[j] == '.':
|
||||
has_dot = True
|
||||
j += 1
|
||||
raw = src[i:j]
|
||||
try:
|
||||
value = float(raw) if has_dot else int(raw)
|
||||
except ValueError:
|
||||
raise LexError(f"unexpected character '.' at position {i}")
|
||||
tokens.append(Token('NUMBER', value))
|
||||
i = j
|
||||
continue
|
||||
|
||||
raise LexError(f"unexpected character {ch!r} at position {i}")
|
||||
|
||||
tokens.append(Token('EOF', None))
|
||||
return tokens
|
||||
114
calculators/builder-adversary-stateless/run-01/calc/parser.py
Normal file
114
calculators/builder-adversary-stateless/run-01/calc/parser.py
Normal file
@ -0,0 +1,114 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Union
|
||||
|
||||
from calc.lexer import Token
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Num:
|
||||
value: Union[int, float]
|
||||
|
||||
def __repr__(self):
|
||||
return f"Num(value={self.value!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
op: str
|
||||
left: "Node"
|
||||
right: "Node"
|
||||
|
||||
def __repr__(self):
|
||||
return f"BinOp(op={self.op!r}, left={self.left!r}, right={self.right!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
op: str
|
||||
operand: "Node"
|
||||
|
||||
def __repr__(self):
|
||||
return f"Unary(op={self.op!r}, operand={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) -> Token:
|
||||
tok = self._peek()
|
||||
if tok.kind != kind:
|
||||
raise ParseError(
|
||||
f"expected {kind}, got {tok.kind!r} ({tok.value!r})"
|
||||
)
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def _advance(self) -> Token:
|
||||
tok = self._tokens[self._pos]
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def parse(self) -> Node:
|
||||
if self._peek().kind == "EOF":
|
||||
raise ParseError("empty expression")
|
||||
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._advance().value
|
||||
right = self._term()
|
||||
node = BinOp(op=op, left=node, right=right)
|
||||
return node
|
||||
|
||||
def _term(self) -> Node:
|
||||
node = self._unary()
|
||||
while self._peek().kind in ("STAR", "SLASH"):
|
||||
op = self._advance().value
|
||||
right = self._unary()
|
||||
node = BinOp(op=op, left=node, right=right)
|
||||
return node
|
||||
|
||||
def _unary(self) -> Node:
|
||||
if self._peek().kind == "MINUS":
|
||||
op = self._advance().value
|
||||
operand = self._unary()
|
||||
return Unary(op=op, operand=operand)
|
||||
return self._primary()
|
||||
|
||||
def _primary(self) -> Node:
|
||||
tok = self._peek()
|
||||
if tok.kind == "NUMBER":
|
||||
self._advance()
|
||||
return Num(value=tok.value)
|
||||
if tok.kind == "LPAREN":
|
||||
self._advance()
|
||||
node = self._expr()
|
||||
self._consume("RPAREN")
|
||||
return node
|
||||
if tok.kind == "EOF":
|
||||
raise ParseError("unexpected end of input")
|
||||
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")
|
||||
|
||||
|
||||
def parse(tokens: List[Token]) -> Node:
|
||||
"""Parse a token list into an AST. Raises ParseError on malformed input."""
|
||||
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(self):
|
||||
self.assertEqual(calc("(2+3)*4"), 20)
|
||||
|
||||
def test_left_assoc_sub(self):
|
||||
self.assertEqual(calc("8-3-2"), 3)
|
||||
|
||||
def test_unary_minus(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_before_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")
|
||||
|
||||
def test_no_bare_zero_division_error(self):
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError escaped the API")
|
||||
|
||||
|
||||
class TestResultType(unittest.TestCase):
|
||||
def test_whole_division_is_int(self):
|
||||
result = calc("4/2")
|
||||
self.assertEqual(result, 2)
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
def test_fractional_division_is_float(self):
|
||||
result = calc("7/2")
|
||||
self.assertEqual(result, 3.5)
|
||||
self.assertIsInstance(result, float)
|
||||
|
||||
def test_integer_arithmetic_stays_int(self):
|
||||
result = calc("2+3")
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -0,0 +1,91 @@
|
||||
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(len(toks), 2)
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertEqual(toks[0].value, 42)
|
||||
self.assertIsInstance(toks[0].value, int)
|
||||
self.assertEqual(toks[1].kind, 'EOF')
|
||||
|
||||
def test_float_standard(self):
|
||||
toks = tokenize("3.14")
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(toks[0].value, 3.14)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
def test_float_leading_dot(self):
|
||||
toks = tokenize(".5")
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(toks[0].value, 0.5)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
def test_float_trailing_dot(self):
|
||||
toks = tokenize("10.")
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(toks[0].value, 10.0)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_all_operators(self):
|
||||
self.assertEqual(kinds("+-*/()"), ['PLUS', 'MINUS', 'STAR', 'SLASH', 'LPAREN', 'RPAREN', 'EOF'])
|
||||
|
||||
def test_expression(self):
|
||||
self.assertEqual(kinds("1+2*3"), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_operator_values(self):
|
||||
toks = tokenize("+")
|
||||
self.assertEqual(toks[0].value, '+')
|
||||
|
||||
def test_parens_values(self):
|
||||
toks = tokenize("()")
|
||||
self.assertEqual(toks[0].kind, 'LPAREN')
|
||||
self.assertEqual(toks[0].value, '(')
|
||||
self.assertEqual(toks[1].kind, 'RPAREN')
|
||||
self.assertEqual(toks[1].value, ')')
|
||||
|
||||
|
||||
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):
|
||||
self.assertEqual(kinds("3.5*(1-2)"), ['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'])
|
||||
|
||||
def test_at_sign_raises(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('@', str(ctx.exception))
|
||||
|
||||
def test_dollar_raises(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$5")
|
||||
|
||||
def test_letter_raises(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("x")
|
||||
|
||||
def test_error_position_in_message(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
msg = str(ctx.exception)
|
||||
self.assertIn('2', msg) # position 2
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@ -0,0 +1,159 @@
|
||||
import unittest
|
||||
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import BinOp, Num, ParseError, Unary, parse
|
||||
|
||||
|
||||
def p(src):
|
||||
return parse(tokenize(src))
|
||||
|
||||
|
||||
class TestPrecedence(unittest.TestCase):
|
||||
"""D1 — * and / bind tighter than + and -"""
|
||||
|
||||
def test_add_mul(self):
|
||||
# 1+2*3 → 1+(2*3)
|
||||
tree = p("1+2*3")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("+", Num(1), BinOp("*", Num(2), Num(3))),
|
||||
)
|
||||
|
||||
def test_mul_add(self):
|
||||
# 3*2+1 → (3*2)+1
|
||||
tree = p("3*2+1")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("+", BinOp("*", Num(3), Num(2)), Num(1)),
|
||||
)
|
||||
|
||||
def test_sub_div(self):
|
||||
# 10-4/2 → 10-(4/2)
|
||||
tree = p("10-4/2")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("-", Num(10), BinOp("/", Num(4), Num(2))),
|
||||
)
|
||||
|
||||
|
||||
class TestLeftAssociativity(unittest.TestCase):
|
||||
"""D2 — same-precedence operators associate left"""
|
||||
|
||||
def test_sub_left(self):
|
||||
# 8-3-2 → (8-3)-2
|
||||
tree = p("8-3-2")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("-", BinOp("-", Num(8), Num(3)), Num(2)),
|
||||
)
|
||||
|
||||
def test_div_left(self):
|
||||
# 8/4/2 → (8/4)/2
|
||||
tree = p("8/4/2")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("/", BinOp("/", Num(8), Num(4)), Num(2)),
|
||||
)
|
||||
|
||||
def test_add_left(self):
|
||||
# 1+2+3 → (1+2)+3
|
||||
tree = p("1+2+3")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("+", BinOp("+", Num(1), Num(2)), Num(3)),
|
||||
)
|
||||
|
||||
def test_mul_left(self):
|
||||
# 2*3*4 → (2*3)*4
|
||||
tree = p("2*3*4")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("*", BinOp("*", Num(2), Num(3)), Num(4)),
|
||||
)
|
||||
|
||||
|
||||
class TestParentheses(unittest.TestCase):
|
||||
"""D3 — parentheses override precedence"""
|
||||
|
||||
def test_parens_force_add_first(self):
|
||||
# (1+2)*3 → mul at root, add under left
|
||||
tree = p("(1+2)*3")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("*", BinOp("+", Num(1), Num(2)), Num(3)),
|
||||
)
|
||||
|
||||
def test_nested_parens(self):
|
||||
# ((4)) → Num(4)
|
||||
tree = p("((4))")
|
||||
self.assertEqual(tree, Num(4))
|
||||
|
||||
def test_parens_right(self):
|
||||
# 2*(3+4) → mul at root, add under right
|
||||
tree = p("2*(3+4)")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("*", Num(2), BinOp("+", Num(3), Num(4))),
|
||||
)
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
"""D4 — leading and nested unary minus"""
|
||||
|
||||
def test_simple(self):
|
||||
tree = p("-5")
|
||||
self.assertEqual(tree, Unary("-", Num(5)))
|
||||
|
||||
def test_unary_paren(self):
|
||||
# -(1+2) → Unary at root
|
||||
tree = p("-(1+2)")
|
||||
self.assertEqual(tree, Unary("-", BinOp("+", Num(1), Num(2))))
|
||||
|
||||
def test_mul_unary(self):
|
||||
# 3 * -2 → BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
tree = p("3 * -2")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("*", Num(3), Unary("-", Num(2))),
|
||||
)
|
||||
|
||||
def test_double_unary(self):
|
||||
# --5 → Unary('-', Unary('-', Num(5)))
|
||||
tree = p("--5")
|
||||
self.assertEqual(tree, Unary("-", Unary("-", Num(5))))
|
||||
|
||||
|
||||
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_two_numbers(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("1 2")
|
||||
|
||||
def test_close_open(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p(")(")
|
||||
|
||||
def test_empty(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("")
|
||||
|
||||
def test_just_op(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("+")
|
||||
|
||||
def test_mismatched_parens(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("(1+2")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -0,0 +1,7 @@
|
||||
# BACKLOG — phase `eval`
|
||||
|
||||
## Build backlog
|
||||
(Builder's section — read-only for Adversary)
|
||||
|
||||
## Adversary findings
|
||||
(None yet — phase not started)
|
||||
@ -0,0 +1,14 @@
|
||||
# BACKLOG — phase lex
|
||||
|
||||
## Build backlog
|
||||
- [x] Create calc/__init__.py
|
||||
- [ ] Create calc/lexer.py (Token, LexError, tokenize)
|
||||
- [ ] Create calc/test_lexer.py (unittest covering D1-D3)
|
||||
- [ ] Run tests green
|
||||
- [ ] Claim D1
|
||||
- [ ] Claim D2
|
||||
- [ ] Claim D3
|
||||
- [ ] Claim D4
|
||||
|
||||
## Adversary findings
|
||||
<!-- Adversary writes here -->
|
||||
@ -0,0 +1,10 @@
|
||||
# BACKLOG — phase `parse`
|
||||
|
||||
## Build backlog
|
||||
|
||||
- [x] Write calc/parser.py (AST nodes + recursive descent parser)
|
||||
- [x] Write calc/test_parser.py (unittest suite covering D1-D5)
|
||||
- [ ] Claim D1-D6 after tests green
|
||||
|
||||
## Adversary findings
|
||||
(Adversary writes here)
|
||||
@ -0,0 +1,17 @@
|
||||
# JOURNAL — phase `lex`
|
||||
|
||||
## Builder — Wake 1 — 2026-06-15
|
||||
|
||||
- Implemented calc/lexer.py: Token dataclass, LexError, tokenize().
|
||||
- Implemented calc/test_lexer.py: 15 tests covering D1-D3.
|
||||
- Ran `python -m unittest -q`: 15 tests, 0 failures.
|
||||
- Verified:
|
||||
- `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')"` → raises `LexError: unexpected character '@' at position 2`
|
||||
- Claiming D1, D2, D3, D4.
|
||||
|
||||
## Adversary — Wake 1 — 2026-06-15
|
||||
|
||||
- Initialized adversary tracking files.
|
||||
- No Builder claims yet; machine-docs/ empty, only seed commit exists.
|
||||
- Entering idle loop, will check every 10 min for Builder progress.
|
||||
@ -0,0 +1,45 @@
|
||||
# JOURNAL — phase `parse`
|
||||
|
||||
## 2026-06-15 — Initial implementation
|
||||
|
||||
Plan: recursive-descent parser with two precedence levels.
|
||||
- `expr` → additive level (+ -)
|
||||
- `term` → multiplicative level (* /)
|
||||
- `unary` → handle leading -
|
||||
- `primary` → NUMBER or parenthesized expr
|
||||
|
||||
Grammar:
|
||||
```
|
||||
expr ::= term (('+' | '-') term)*
|
||||
term ::= unary (('*' | '/') unary)*
|
||||
unary ::= '-' unary | primary
|
||||
primary ::= NUMBER | '(' expr ')'
|
||||
```
|
||||
|
||||
Left-associativity achieved naturally by the while loop in `expr` and `term`.
|
||||
|
||||
## Test run output
|
||||
```
|
||||
Ran 36 tests in 0.001s
|
||||
OK
|
||||
```
|
||||
|
||||
## AST shape verification
|
||||
```
|
||||
1+2*3: BinOp(op='+', left=Num(value=1), right=BinOp(op='*', left=Num(value=2), right=Num(value=3)))
|
||||
8-3-2: BinOp(op='-', left=BinOp(op='-', left=Num(value=8), right=Num(value=3)), right=Num(value=2))
|
||||
8/4/2: BinOp(op='/', left=BinOp(op='/', left=Num(value=8), right=Num(value=4)), right=Num(value=2))
|
||||
(1+2)*3: BinOp(op='*', left=BinOp(op='+', left=Num(value=1), right=Num(value=2)), right=Num(value=3))
|
||||
-5: Unary(op='-', operand=Num(value=5))
|
||||
-(1+2): Unary(op='-', operand=BinOp(op='+', left=Num(value=1), right=Num(value=2)))
|
||||
3*-2: BinOp(op='*', left=Num(value=3), right=Unary(op='-', operand=Num(value=2)))
|
||||
```
|
||||
|
||||
## Error cases
|
||||
```
|
||||
'1 +': ParseError: unexpected end of input
|
||||
'(1': ParseError: expected RPAREN, got 'EOF' (None)
|
||||
'1 2': ParseError: unexpected token 'NUMBER' (2) after expression
|
||||
')(': ParseError: unexpected token 'RPAREN' (')')
|
||||
'': ParseError: empty expression
|
||||
```
|
||||
@ -0,0 +1,37 @@
|
||||
# REVIEW — phase `eval`
|
||||
|
||||
Adversary verification log. Gates: D1 (arithmetic), D2 (division/EvalError), D3 (result type), D4 (CLI), D5 (tests green + end-to-end).
|
||||
|
||||
## Verdicts
|
||||
|
||||
### D1 — arithmetic: PASS @2026-06-15T03:53Z
|
||||
Cold run of all five plan expressions:
|
||||
- `2+3*4` → 14 ✓
|
||||
- `(2+3)*4` → 20 ✓
|
||||
- `8-3-2` → 3 ✓
|
||||
- `-2+5` → 3 ✓
|
||||
- `2*-3` → -6 ✓
|
||||
|
||||
Extra probes: `--5`→5 (double unary), `-0`→0, `100/4`→25. All correct.
|
||||
|
||||
### D2 — division / EvalError: PASS @2026-06-15T03:53Z
|
||||
- `7/2` → 3.5 ✓
|
||||
- `1/0` → `EvalError("division by zero")` raised (not bare `ZeroDivisionError`); CLI prints `error: division by zero` to stderr, exits 1 ✓
|
||||
|
||||
### D3 — result type: PASS @2026-06-15T03:53Z
|
||||
- `4/2` → `2` (int, no trailing .0) ✓
|
||||
- `7/2` → `3.5` (float) ✓
|
||||
- Extended: `6/3`→int, `9/3`→int, `-2+5`→int; `1/3`→float, `5/4`→float. Rule consistent.
|
||||
|
||||
### D4 — CLI: PASS @2026-06-15T03:53Z
|
||||
- `python calc.py "2+3*4"` → stdout `14`, exit 0 ✓
|
||||
- `python calc.py "1 +"` → stderr `error: unexpected end of input`, exit 1, no traceback ✓
|
||||
- `python calc.py "1/0"` → stderr `error: division by zero`, exit 1, no traceback ✓
|
||||
- Error is to stderr only (stdout clean on error) ✓
|
||||
|
||||
### D5 — tests green + end-to-end: PASS @2026-06-15T03:53Z
|
||||
`python -m unittest -q` → `Ran 47 tests in 0.001s` / `OK` — 0 failures.
|
||||
Covers lex (16 tests) + parse (20 tests) + eval (11+ tests). No regression.
|
||||
|
||||
## Summary
|
||||
All five gates PASS. No defects found. No veto.
|
||||
@ -0,0 +1,38 @@
|
||||
# REVIEW — phase `lex` (Adversary)
|
||||
|
||||
## Gates
|
||||
|
||||
### lex/D1: PASS @2026-06-15T03:33:50Z
|
||||
Cold run from Adversary clone (commit 328d25f).
|
||||
- `tokenize("42")` → `[NUMBER(42), EOF(None)]`, value is `int` ✓
|
||||
- `tokenize("3.14")` → `[NUMBER(3.14), EOF(None)]`, value is `float` ✓
|
||||
- `tokenize(".5")` → `[NUMBER(0.5), EOF(None)]`, value is `float` ✓
|
||||
- `tokenize("10.")` → `[NUMBER(10.0), EOF(None)]`, value is `float` ✓
|
||||
|
||||
### lex/D2: PASS @2026-06-15T03:33:50Z
|
||||
Cold run from Adversary clone.
|
||||
- `tokenize("1+2*3")` → `[NUMBER(1), PLUS('+'), NUMBER(2), STAR('*'), NUMBER(3), EOF(None)]` ✓
|
||||
- `tokenize("+-*/()") ` → `['PLUS', 'MINUS', 'STAR', 'SLASH', 'LPAREN', 'RPAREN', 'EOF']` ✓
|
||||
|
||||
### lex/D3: PASS @2026-06-15T03:33:50Z
|
||||
Cold run from Adversary clone.
|
||||
- `tokenize(" 12 + 3 ")` → `[('NUMBER', 12), ('PLUS', '+'), ('NUMBER', 3), ('EOF', None)]` ✓
|
||||
- `tokenize("1 @ 2")` raises `LexError: unexpected character '@' at position 2` ✓ (char and position in message)
|
||||
- `tokenize("$5")` raises `LexError: unexpected character '$' at position 0` ✓
|
||||
- `tokenize("x")` raises `LexError` ✓
|
||||
|
||||
### lex/D4: PASS @2026-06-15T03:33:50Z
|
||||
Cold run from Adversary clone.
|
||||
- `python -m unittest -q` → Ran 15 tests, OK (0 failures) ✓
|
||||
- `tokenize('3.5*(1-2)')` → `[('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]` ✓
|
||||
- `tokenize('1 @ 2')` → raises `LexError` ✓
|
||||
|
||||
## Adversary findings
|
||||
|
||||
### AF-1 — bare dot raises `ValueError` not `LexError` [non-blocking]
|
||||
`tokenize(".")` raises `ValueError: could not convert string to float: '.'` (from `float(".")` inside
|
||||
the number branch) instead of `LexError`. Not a DoD FAIL — none of D1–D3 test a lone `.` — but
|
||||
the module leaks an internal Python exception for this invalid input. Recommend the Builder guard
|
||||
with `try/except ValueError` in the number branch and re-raise as `LexError`.
|
||||
|
||||
Status: open (non-blocking — Builder may fix in a later phase or now at discretion)
|
||||
@ -0,0 +1,50 @@
|
||||
# REVIEW — parse phase (Adversary)
|
||||
|
||||
## Status
|
||||
All gates verified. Awaiting Builder to write ## DONE to STATUS-parse.md.
|
||||
|
||||
## Gate verdicts
|
||||
|
||||
**D1 (precedence): PASS** @2026-06-15T03:40Z
|
||||
- `parse(tokenize('1+2*3'))` → `BinOp(op='+', left=Num(value=1), right=BinOp(op='*', left=Num(value=2), right=Num(value=3)))` ✓
|
||||
- `parse(tokenize('2*3+1'))` → `BinOp(op='+', left=BinOp(op='*', ...), right=Num(1))` ✓
|
||||
- `parse(tokenize('2+3*4*5'))` → `+` at root, nested `*` tree under right ✓
|
||||
|
||||
**D2 (left assoc): PASS** @2026-06-15T03:40Z
|
||||
- `8-3-2` → `BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))` ✓
|
||||
- `8/4/2` → `BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))` ✓
|
||||
- `12/6*2` → `BinOp('*', BinOp('/', Num(12), Num(6)), Num(2))` ✓ (left-assoc across same-level ops)
|
||||
- `1-2+3` → `BinOp('+', BinOp('-', Num(1), Num(2)), Num(3))` ✓
|
||||
|
||||
**D3 (parentheses): PASS** @2026-06-15T03:40Z
|
||||
- `(1+2)*3` → `BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))` ✓
|
||||
- `((3))` → `Num(3)` ✓
|
||||
|
||||
**D4 (unary minus): PASS** @2026-06-15T03:40Z
|
||||
- `-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)))` ✓ (right-recursive _unary)
|
||||
- `-(-5)` → `Unary('-', Unary('-', Num(5)))` ✓
|
||||
|
||||
**D5 (errors): PASS** @2026-06-15T03:40Z
|
||||
All 5 plan-mandated cases raise `ParseError` (not a Python built-in):
|
||||
- `'1 +'` → ParseError ✓
|
||||
- `'(1'` → ParseError ✓
|
||||
- `'1 2'` → ParseError ✓
|
||||
- `')('` → ParseError ✓
|
||||
- `''` → ParseError ✓
|
||||
Additional probes also raise `ParseError`: `*5`, `()`, `1+2)`, `+-5`, `+` alone.
|
||||
|
||||
**D6 (tests green): PASS** @2026-06-15T03:40Z
|
||||
- `python -m unittest -q` → `Ran 36 tests in 0.001s` / `OK` ✓
|
||||
- Tests assert on tree structure via dataclass equality (not evaluation) ✓
|
||||
- 7 error-case tests, 20 structural tests across D1–D4
|
||||
|
||||
## Adversary findings
|
||||
|
||||
None. No defects found.
|
||||
|
||||
## Implementation notes (post-verdict)
|
||||
Recursive-descent parser is structurally sound: `_expr → _term → _unary → _primary`.
|
||||
`ParseError(Exception)` is a proper subclass. EOF sentinel token prevents index OOB.
|
||||
@ -0,0 +1,49 @@
|
||||
# STATUS — phase `eval`
|
||||
|
||||
## DONE
|
||||
|
||||
## Gates: D1–D5 — all PASS (Adversary-verified 2026-06-15T03:53Z)
|
||||
|
||||
Commit: `6d4fbb6f1c15402148e5e06e2f99e2b1154f4dd6`
|
||||
|
||||
---
|
||||
|
||||
## Verify commands + expected outputs
|
||||
|
||||
Run from repo root (clean clone):
|
||||
|
||||
```bash
|
||||
# D5 — whole suite (lex + parse + eval), must be 0 failures
|
||||
python -m unittest -q
|
||||
# Expected: Ran 47 tests in <t>s / OK
|
||||
|
||||
# D1 — arithmetic
|
||||
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
|
||||
python calc.py "7/2" # → 3.5
|
||||
python calc.py "1/0" # → stderr: "error: division by zero", exit 1
|
||||
|
||||
# D3 — result type
|
||||
python calc.py "4/2" # → 2 (int, no trailing .0)
|
||||
python calc.py "7/2" # → 3.5 (float)
|
||||
|
||||
# D4 — CLI error handling
|
||||
python calc.py "1 +" # → stderr: error message, exit 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Files
|
||||
|
||||
- `calc/evaluator.py` — `evaluate(node)` walking Num/BinOp/Unary, `EvalError`
|
||||
- `calc.py` — CLI: tokenize→parse→evaluate, errors to stderr, exit 1
|
||||
- `calc/test_evaluator.py` — 13 unittest tests covering D1–D3
|
||||
|
||||
## Result-type rule (D3)
|
||||
|
||||
`evaluate` returns `int` when the float result equals its integer value (`result == int(result)`), `float` otherwise. This is applied inside `evaluate` for BinOp division results.
|
||||
@ -0,0 +1,46 @@
|
||||
# STATUS — phase lex
|
||||
|
||||
## DONE
|
||||
|
||||
All gates D1–D4 verified PASS by Adversary @2026-06-15T03:33:50Z.
|
||||
AF-1 fixed: bare dot now raises LexError instead of leaking ValueError.
|
||||
|
||||
## Current state
|
||||
Gate: D1 D2 D3 D4 — all PASS (Adversary verified)
|
||||
|
||||
## Gates
|
||||
|
||||
### D1 — numbers
|
||||
**WHAT:** Integers and floats tokenize to NUMBER tokens with correct Python numeric values.
|
||||
**HOW:** `python -m unittest -q calc.test_lexer.TestNumbers` (or full suite)
|
||||
**EXPECTED:** 4 tests pass; `tokenize("42")` → `[NUMBER(42), EOF]`; `tokenize("3.14")` → `[NUMBER(3.14), EOF]`; `tokenize(".5")` → `[NUMBER(0.5), EOF]`; `tokenize("10.")` → `[NUMBER(10.0), EOF]`
|
||||
**WHERE:** calc/lexer.py, calc/test_lexer.py
|
||||
|
||||
### D2 — operators & parens
|
||||
**WHAT:** `+ - * / ( )` each tokenize to the correct kind.
|
||||
**HOW:** `python -m unittest -q calc.test_lexer.TestOperatorsAndParens`
|
||||
**EXPECTED:** 4 tests pass; `tokenize("1+2*3")` → `[NUMBER(1), PLUS('+'), NUMBER(2), STAR('*'), NUMBER(3), EOF(None)]`
|
||||
**WHERE:** calc/lexer.py, calc/test_lexer.py
|
||||
|
||||
### D3 — whitespace & errors
|
||||
**WHAT:** Spaces/tabs skipped; invalid chars raise LexError with the char and position.
|
||||
**HOW:** `python -m unittest -q calc.test_lexer.TestWhitespaceAndErrors`
|
||||
**EXPECTED:** 7 tests pass; `tokenize(" 12 + 3 ")` → `[NUMBER(12), PLUS, NUMBER(3), EOF]`; `tokenize("1 @ 2")` raises `LexError`
|
||||
**WHERE:** calc/lexer.py, calc/test_lexer.py
|
||||
|
||||
### D4 — tests green
|
||||
**WHAT:** Full test suite 0 failures.
|
||||
**HOW:**
|
||||
```bash
|
||||
python -m unittest -q
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"
|
||||
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
|
||||
```
|
||||
**EXPECTED:**
|
||||
- `python -m unittest -q` → 15 tests, 0 failures
|
||||
- Second command → `[('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]`
|
||||
- Third command → raises `LexError: unexpected character '@' at position 2`
|
||||
**WHERE:** calc/test_lexer.py (commit sha: see below)
|
||||
|
||||
## Commit SHA
|
||||
328d25f — claim(D1,D2,D3,D4): lexer implementation + tests green
|
||||
@ -0,0 +1,105 @@
|
||||
# STATUS — phase `parse`
|
||||
|
||||
## DONE
|
||||
|
||||
## Gates
|
||||
- D1 (precedence): PASS @2026-06-15T03:40Z
|
||||
- D2 (left assoc): PASS @2026-06-15T03:40Z
|
||||
- D3 (parentheses): PASS @2026-06-15T03:40Z
|
||||
- D4 (unary minus): PASS @2026-06-15T03:40Z
|
||||
- D5 (errors): PASS @2026-06-15T03:40Z
|
||||
- D6 (tests green): PASS @2026-06-15T03:40Z
|
||||
|
||||
## Source files
|
||||
- `calc/parser.py` — AST node definitions + recursive-descent parser
|
||||
- `calc/test_parser.py` — 20 unittest cases covering D1–D5
|
||||
|
||||
## AST shape
|
||||
|
||||
Nodes are dataclasses defined in `calc/parser.py`:
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class Num:
|
||||
value: Union[int, float]
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
op: str # '+', '-', '*', '/'
|
||||
left: Node
|
||||
right: Node
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
op: str # '-'
|
||||
operand: Node
|
||||
```
|
||||
|
||||
## Verify commands (cold)
|
||||
|
||||
```bash
|
||||
python -m unittest -q
|
||||
```
|
||||
Expected: `Ran 36 tests in Xs` / `OK` (0 failures)
|
||||
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('1+2*3')))"
|
||||
```
|
||||
Expected: `BinOp(op='+', left=Num(value=1), right=BinOp(op='*', left=Num(value=2), right=Num(value=3)))`
|
||||
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8-3-2')))"
|
||||
```
|
||||
Expected: `BinOp(op='-', left=BinOp(op='-', left=Num(value=8), right=Num(value=3)), right=Num(value=2))`
|
||||
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8/4/2')))"
|
||||
```
|
||||
Expected: `BinOp(op='/', left=BinOp(op='/', left=Num(value=8), right=Num(value=4)), right=Num(value=2))`
|
||||
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('(1+2)*3')))"
|
||||
```
|
||||
Expected: `BinOp(op='*', left=BinOp(op='+', left=Num(value=1), right=Num(value=2)), right=Num(value=3))`
|
||||
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-5')))"
|
||||
```
|
||||
Expected: `Unary(op='-', operand=Num(value=5))`
|
||||
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-(1+2)')))"
|
||||
```
|
||||
Expected: `Unary(op='-', operand=BinOp(op='+', left=Num(value=1), right=Num(value=2)))`
|
||||
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('3 * -2')))"
|
||||
```
|
||||
Expected: `BinOp(op='*', left=Num(value=3), right=Unary(op='-', operand=Num(value=2)))`
|
||||
|
||||
```bash
|
||||
python -c "
|
||||
from calc.lexer import tokenize; from calc.parser import parse, ParseError
|
||||
for expr in ['1 +', '(1', '1 2', ')(', '']:
|
||||
try:
|
||||
parse(tokenize(expr))
|
||||
print(f'{expr!r}: NO ERROR (FAIL)')
|
||||
except ParseError as e:
|
||||
print(f'{expr!r}: ParseError OK')
|
||||
"
|
||||
```
|
||||
Expected: all 5 lines print `ParseError OK`
|
||||
|
||||
## Gate-specific DoD mapping
|
||||
|
||||
**D1 — precedence:** `1+2*3` parses as `1+(2*3)` — `*` is under the right child of `+`, not the other way.
|
||||
|
||||
**D2 — left assoc:** `8-3-2` → left-leaning tree; `8/4/2` → left-leaning tree. The while-loop in `_expr`/`_term` naturally accumulates left.
|
||||
|
||||
**D3 — parens:** `(1+2)*3` → `BinOp('*', BinOp('+', ...), Num(3))` — `+` is under `*`'s left child.
|
||||
|
||||
**D4 — unary:** `-5` → `Unary`, `-(1+2)` → `Unary(BinOp(...))`, `3*-2` → `BinOp('*', Num(3), Unary(...))`.
|
||||
|
||||
**D5 — errors:** `"1 +"`, `"(1"`, `"1 2"`, `")("`, `""` all raise `ParseError` (not Python built-ins).
|
||||
|
||||
**D6 — tests:** `python -m unittest -q` → 36 tests, 0 failures.
|
||||
Reference in New Issue
Block a user