artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
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.
|
||||
@ -0,0 +1,62 @@
|
||||
# REVIEW-eval
|
||||
|
||||
Phase: `eval`
|
||||
Adversary cold-verified at commit `3ff8ae9`.
|
||||
|
||||
## Gates
|
||||
|
||||
| Gate | Status |
|
||||
|------|--------|
|
||||
| D1 — arithmetic | PASS @2026-06-15T |
|
||||
| D2 — division / EvalError | PASS @2026-06-15T |
|
||||
| D3 — result type formatting | PASS @2026-06-15T |
|
||||
| D4 — CLI | PASS @2026-06-15T |
|
||||
| D5 — tests green + end-to-end | PASS @2026-06-15T |
|
||||
|
||||
---
|
||||
|
||||
## review(D1): PASS @2026-06-15
|
||||
|
||||
Cold run of all D1 expressions:
|
||||
|
||||
| Expression | Expected | Got | Type |
|
||||
|---|---|---|---|
|
||||
| `2+3*4` | 14 | 14 | int ✓ |
|
||||
| `(2+3)*4` | 20 | 20 | int ✓ |
|
||||
| `8-3-2` | 3 | 3 | int ✓ |
|
||||
| `-2+5` | 3 | 3 | int ✓ |
|
||||
| `2*-3` | -6 | -6 | int ✓ |
|
||||
|
||||
Additional edge cases probed: `--5`→5, `-(3+2)`→-5, `0*100`→0. All correct.
|
||||
|
||||
## review(D2): PASS @2026-06-15
|
||||
|
||||
- `7/2` → 3.5 (true division, not integer) ✓
|
||||
- `1/0` raises `EvalError("division by zero")`, not bare `ZeroDivisionError` ✓
|
||||
- `0/5` → 0 ✓
|
||||
- `8/4/2` → 1 (left-associative) ✓
|
||||
|
||||
## review(D3): PASS @2026-06-15
|
||||
|
||||
- `4/2` → `2` type=int ✓ (whole result coerced to int)
|
||||
- `7/2` → `3.5` type=float ✓ (fractional stays float)
|
||||
- `2+3*4` → `14` type=int ✓ (integer arithmetic stays int)
|
||||
- CLI output: `python calc.py "4/2"` prints `2` (no trailing `.0`) ✓
|
||||
- CLI output: `python calc.py "7/2"` prints `3.5` ✓
|
||||
|
||||
## review(D4): PASS @2026-06-15
|
||||
|
||||
- `python calc.py "2+3*4"` → stdout `14`, exit 0 ✓
|
||||
- `python calc.py "(2+3)*4"` → stdout `20`, exit 0 ✓
|
||||
- `python calc.py "1/0"` → `error: division by zero` to stderr, exit 1 ✓ (no traceback)
|
||||
- `python calc.py "1 +"` → `error: unexpected token 'EOF' (None)` to stderr, exit 1 ✓ (no traceback)
|
||||
|
||||
## review(D5): PASS @2026-06-15
|
||||
|
||||
```
|
||||
python -m unittest -q
|
||||
Ran 52 tests in 0.001s
|
||||
OK
|
||||
```
|
||||
|
||||
52 tests, 0 failures, 0 errors. Covers lex + parse (prior phases) + evaluator (D1–D3) + CLI. No regressions.
|
||||
@ -0,0 +1,65 @@
|
||||
# REVIEW-lex
|
||||
|
||||
Adversary review log for phase `lex`.
|
||||
|
||||
<!-- verdicts appended as: review(<id>): PASS|FAIL ... -->
|
||||
|
||||
## review(D1): PASS @2026-06-15T00:00:00Z
|
||||
|
||||
Verified at sha `8d523a2`.
|
||||
|
||||
```
|
||||
NUMBER 42 int EOF # tokenize("42")
|
||||
NUMBER 0.5 # tokenize(".5")
|
||||
NUMBER 10.0 float # tokenize("10.")
|
||||
```
|
||||
|
||||
`tokenize("42")` → `[NUMBER(42), EOF]` with `int` type. `.5` → `0.5 float`. `10.` → `10.0 float`. All correct.
|
||||
|
||||
---
|
||||
|
||||
## review(D2): PASS @2026-06-15T00:00:00Z
|
||||
|
||||
Verified at sha `8d523a2`.
|
||||
|
||||
```
|
||||
['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'] # tokenize("1+2*3")
|
||||
['PLUS', 'MINUS', 'STAR', 'SLASH', 'LPAREN', 'RPAREN', 'EOF'] # tokenize("+-*/()")
|
||||
```
|
||||
|
||||
All six operator/paren kinds correct.
|
||||
|
||||
---
|
||||
|
||||
## review(D3): PASS @2026-06-15T00:00:00Z
|
||||
|
||||
Verified at sha `8d523a2`.
|
||||
|
||||
```
|
||||
['NUMBER', 'PLUS', 'NUMBER', 'EOF'] # tokenize(" 12 + 3 ")
|
||||
calc.lexer.LexError: unexpected character '@' at position 2 # tokenize("1 @ 2")
|
||||
```
|
||||
|
||||
Whitespace skipped; `LexError` raised with offending char and position for `@`.
|
||||
|
||||
**Edge-case warning (non-blocking):** A lone `.` raises `ValueError` (uncaught) rather than `LexError`. Not covered by the DoD but is a latent bug for callers. Also `1..2` silently lexes as `NUMBER(1.0) NUMBER(0.2)` instead of erroring. Neither breaks D1–D4 as specified.
|
||||
|
||||
---
|
||||
|
||||
## review(D4): PASS @2026-06-15T00:00:00Z
|
||||
|
||||
Verified at sha `8d523a2`.
|
||||
|
||||
```
|
||||
Ran 15 tests in 0.000s
|
||||
|
||||
OK
|
||||
```
|
||||
|
||||
Plan cold-verify commands:
|
||||
```
|
||||
[('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]
|
||||
calc.lexer.LexError: unexpected character '@' at position 2
|
||||
```
|
||||
|
||||
Both match expected output from the plan exactly. 15 tests, 0 failures.
|
||||
@ -0,0 +1,45 @@
|
||||
# Adversary Review — parse phase
|
||||
|
||||
Verified cold at commit d97df78.
|
||||
|
||||
## Verdicts
|
||||
|
||||
| Gate | Verdict | Timestamp |
|
||||
|------|---------|-----------|
|
||||
| D1 | PASS | 2026-06-15T03:28Z |
|
||||
| D2 | PASS | 2026-06-15T03:28Z |
|
||||
| D3 | PASS | 2026-06-15T03:28Z |
|
||||
| D4 | PASS | 2026-06-15T03:28Z |
|
||||
| D5 | PASS | 2026-06-15T03:28Z |
|
||||
| D6 | PASS | 2026-06-15T03:28Z |
|
||||
|
||||
## Evidence
|
||||
|
||||
**D6 — test suite:** `python -m unittest -q` → Ran 34 tests in 0.001s OK
|
||||
|
||||
**D1 — precedence:** `parse(tokenize('1+2*3'))` → `BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))` ✓
|
||||
`*` is in the right subtree, proving it binds tighter than `+`.
|
||||
|
||||
**D2 — left associativity:**
|
||||
- `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))` ✓
|
||||
|
||||
**D3 — parentheses:** `parse(tokenize('(1+2)*3'))` → `BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))` ✓
|
||||
|
||||
**D4 — unary minus:**
|
||||
- `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)))` ✓
|
||||
|
||||
**D5 — ParseError for all 5 plan-specified malformed inputs:**
|
||||
- `'1 +'` → `ParseError: unexpected token 'EOF' (None)` ✓
|
||||
- `'(1'` → `ParseError: expected ')' but got 'EOF'` ✓
|
||||
- `'1 2'` → `ParseError: unexpected token 'NUMBER' (2) after expression` ✓
|
||||
- `')('` → `ParseError: unexpected token 'RPAREN' (')')` ✓
|
||||
- `''` → `ParseError: empty input` ✓
|
||||
|
||||
**Adversarial extras (not in plan, all pass):**
|
||||
- `'--5'` → `Unary('-', Unary('-', Num(5)))` (recursive unary) ✓
|
||||
- `'2+3*4-1'` → correct mixed-precedence left-assoc tree ✓
|
||||
- `'-3*-2'` → `BinOp('*', Unary('-', Num(3)), Unary('-', Num(2)))` ✓
|
||||
- `'*5'` → `ParseError` (bare leading operator) ✓
|
||||
@ -0,0 +1,39 @@
|
||||
# STATUS — eval phase
|
||||
|
||||
## Claimed gates: D1, D2, D3, D4, D5
|
||||
|
||||
## Verify commands (cold, run from repo root)
|
||||
|
||||
```bash
|
||||
python -m unittest -q
|
||||
python calc.py "2+3*4"
|
||||
python calc.py "(2+3)*4"
|
||||
python calc.py "7/2"
|
||||
python calc.py "4/2"
|
||||
python calc.py "1/0" # error to stderr, exit 1
|
||||
python calc.py "1 +" # error to stderr, exit 1
|
||||
```
|
||||
|
||||
## Expected results
|
||||
|
||||
| Command | Expected output | Expected exit |
|
||||
|---------|----------------|---------------|
|
||||
| `python -m unittest -q` | `Ran 52 tests in …s OK` | 0 |
|
||||
| `python calc.py "2+3*4"` | `14` | 0 |
|
||||
| `python calc.py "(2+3)*4"` | `20` | 0 |
|
||||
| `python calc.py "7/2"` | `3.5` | 0 |
|
||||
| `python calc.py "4/2"` | `2` | 0 |
|
||||
| `python calc.py "1/0"` | `error: division by zero` (stderr) | 1 |
|
||||
| `python calc.py "1 +"` | `error: …` (stderr) | 1 |
|
||||
|
||||
## Files added
|
||||
|
||||
- `calc/evaluator.py` — `evaluate(node)` walker + `EvalError`
|
||||
- `calc/test_evaluator.py` — 18 unittest cases covering D1–D3
|
||||
- `calc.py` — CLI entry point (D4)
|
||||
|
||||
## Commit SHA
|
||||
|
||||
3ff8ae9
|
||||
|
||||
## DONE
|
||||
@ -0,0 +1,95 @@
|
||||
# STATUS — phase lex
|
||||
|
||||
## DONE
|
||||
|
||||
## claim(D1): numbers tokenize correctly
|
||||
|
||||
**What:** Integers and floats (including `.5`, `10.`) produce a single `NUMBER` token with the correct numeric type (int or float), followed by `EOF`.
|
||||
|
||||
**How to verify:**
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; toks = tokenize('42'); print(toks[0].kind, toks[0].value, type(toks[0].value).__name__, toks[1].kind)"
|
||||
python -c "from calc.lexer import tokenize; toks = tokenize('3.14'); print(toks[0].kind, toks[0].value, type(toks[0].value).__name__)"
|
||||
python -c "from calc.lexer import tokenize; toks = tokenize('.5'); print(toks[0].kind, toks[0].value)"
|
||||
python -c "from calc.lexer import tokenize; toks = tokenize('10.'); print(toks[0].kind, toks[0].value, type(toks[0].value).__name__)"
|
||||
```
|
||||
|
||||
**Expected:**
|
||||
```
|
||||
NUMBER 42 int EOF
|
||||
NUMBER 3.14 float
|
||||
NUMBER 0.5 float
|
||||
NUMBER 10.0 float
|
||||
```
|
||||
|
||||
**Files:** `calc/lexer.py`, `calc/__init__.py`
|
||||
|
||||
---
|
||||
|
||||
## claim(D2): operators and parens tokenize correctly
|
||||
|
||||
**What:** `+ - * / ( )` each produce their respective token kind; `tokenize("1+2*3")` yields `NUMBER PLUS NUMBER STAR NUMBER EOF`.
|
||||
|
||||
**How to verify:**
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; print([t.kind for t in tokenize('1+2*3')])"
|
||||
python -c "from calc.lexer import tokenize; print([t.kind for t in tokenize('+-*/()')] )"
|
||||
```
|
||||
|
||||
**Expected:**
|
||||
```
|
||||
['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF']
|
||||
['PLUS', 'MINUS', 'STAR', 'SLASH', 'LPAREN', 'RPAREN', 'EOF']
|
||||
```
|
||||
|
||||
**Files:** `calc/lexer.py`
|
||||
|
||||
---
|
||||
|
||||
## claim(D3): whitespace skipped, invalid chars raise LexError
|
||||
|
||||
**What:** Spaces/tabs between tokens are silently skipped. Any unrecognized character (e.g. `@`, `$`, letter) raises `LexError` with the offending character and its position in the message.
|
||||
|
||||
**How to verify:**
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; print([t.kind for t in tokenize(' 12 + 3 ')])"
|
||||
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
|
||||
```
|
||||
|
||||
**Expected:**
|
||||
- First command: `['NUMBER', 'PLUS', 'NUMBER', 'EOF']`
|
||||
- Second command: raises `calc.lexer.LexError: unexpected character '@' at position 2`
|
||||
|
||||
**Files:** `calc/lexer.py`
|
||||
|
||||
---
|
||||
|
||||
## claim(D4): all tests pass
|
||||
|
||||
**What:** `calc/test_lexer.py` (15 test cases covering D1–D3, including the three required expressions) passes with 0 failures.
|
||||
|
||||
**How to verify:**
|
||||
```bash
|
||||
python -m unittest -q
|
||||
```
|
||||
|
||||
**Expected:**
|
||||
```
|
||||
Ran 15 tests in 0.000s
|
||||
|
||||
OK
|
||||
```
|
||||
|
||||
**Also run the plan's exact cold-verify commands:**
|
||||
```bash
|
||||
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:**
|
||||
```
|
||||
[('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]
|
||||
Traceback ... LexError: unexpected character '@' at position 2
|
||||
```
|
||||
|
||||
**Files:** `calc/test_lexer.py`
|
||||
@ -0,0 +1,92 @@
|
||||
# STATUS-parse
|
||||
|
||||
Phase: `parse`
|
||||
Builder: CLAIMING D1–D6
|
||||
|
||||
## Claims
|
||||
|
||||
| Gate | DoD item | Status |
|
||||
|------|----------|--------|
|
||||
| D1 | Correct precedence: `*`/`/` bind tighter than `+`/`-` | CLAIMED |
|
||||
| D2 | Left associativity for same-precedence operators | CLAIMED |
|
||||
| D3 | Parentheses override precedence | CLAIMED |
|
||||
| D4 | Unary minus (leading, nested, after operator) | CLAIMED |
|
||||
| D5 | Malformed input raises `ParseError` | CLAIMED |
|
||||
| D6 | `calc/test_parser.py` passes: 34 tests, 0 failures | CLAIMED |
|
||||
|
||||
## Implementation
|
||||
|
||||
- **`calc/parser.py`** — recursive-descent parser exposing `parse(tokens) -> Node`
|
||||
- **`calc/test_parser.py`** — unittest suite covering D1–D5 (34 tests)
|
||||
|
||||
### AST node shapes
|
||||
|
||||
```
|
||||
Num(value) # value: int | float
|
||||
BinOp(op, left, right) # op: '+' | '-' | '*' | '/'
|
||||
Unary(op, operand) # op: '-'
|
||||
```
|
||||
|
||||
## Verify (cold)
|
||||
|
||||
```bash
|
||||
python -m unittest -q
|
||||
# Expected: Ran 34 tests in 0.00xs OK
|
||||
```
|
||||
|
||||
### D1 — precedence assertion
|
||||
```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)))
|
||||
```
|
||||
The `*` is in the subtree (right of `+`), proving `*` binds tighter.
|
||||
|
||||
### D2 — left associativity assertions
|
||||
```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 assertion
|
||||
```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 assertions
|
||||
```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 — error assertions
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize('1 +'))" 2>&1 | grep ParseError
|
||||
# Expected: line containing "calc.parser.ParseError"
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize('(1'))" 2>&1 | grep ParseError
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize('1 2'))" 2>&1 | grep ParseError
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize(')('))" 2>&1 | grep ParseError
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize(''))" 2>&1 | grep ParseError
|
||||
```
|
||||
All five raise `calc.parser.ParseError`.
|
||||
|
||||
## Commit
|
||||
|
||||
Implemented at HEAD (see `git log --oneline -1` after push).
|
||||
|
||||
## DONE
|
||||
|
||||
All D1–D6 gates verified PASS by Adversary at 2026-06-15T03:28Z (commit d97df78). Phase complete.
|
||||
Reference in New Issue
Block a user