artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
3
calculators/builder-adversary-deferred/run-04/.gitignore
vendored
Normal file
3
calculators/builder-adversary-deferred/run-04/.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
14
calculators/builder-adversary-deferred/run-04/GIT-LOG.txt
Normal file
14
calculators/builder-adversary-deferred/run-04/GIT-LOG.txt
Normal file
@ -0,0 +1,14 @@
|
||||
# git history (claim/review handshake), from the run's shared bare repo
|
||||
539c392 status(review): ## DONE — Adversary PASS on all D1–D4, no findings
|
||||
6d89215 review(all): PASS — comprehensive cold-verification complete, 0 findings
|
||||
e0066b4 claim(all): review phase — full build ready for Adversary cold-verification
|
||||
0d4ee30 status(eval): add commit sha to STATUS-eval.md
|
||||
4fada74 feat(eval): implement evaluator, CLI, and test suite — eval phase complete
|
||||
50838d8 review(init): Adversary eval phase initialization — DEFERRED protocol adopted
|
||||
f839449 feat(parse): implement recursive-descent parser, AST nodes, ParseError, and test suite
|
||||
ed8ade3 review(init): Adversary parse phase initialization — DEFERRED protocol adopted
|
||||
c3c1512 status(lex): update commit sha in STATUS, phase DONE
|
||||
0092890 chore: add .gitignore, remove tracked pycache
|
||||
009755c feat(lex): implement lexer, Token, LexError, and test suite
|
||||
aa566e2 review(init): Adversary lex phase initialization — DEFERRED protocol adopted
|
||||
071f92b chore: seed
|
||||
1
calculators/builder-adversary-deferred/run-04/README.md
Normal file
1
calculators/builder-adversary-deferred/run-04/README.md
Normal file
@ -0,0 +1 @@
|
||||
# calc work repo
|
||||
1
calculators/builder-adversary-deferred/run-04/SOURCE.txt
Normal file
1
calculators/builder-adversary-deferred/run-04/SOURCE.txt
Normal file
@ -0,0 +1 @@
|
||||
original path: /tmp/ao-campaign-WXwoUv/builder-adversary-deferred/r5
|
||||
23
calculators/builder-adversary-deferred/run-04/calc.py
Normal file
23
calculators/builder-adversary-deferred/run-04/calc.py
Normal file
@ -0,0 +1,23 @@
|
||||
"""calc.py — command-line calculator: string → tokens → AST → number."""
|
||||
|
||||
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)))
|
||||
print(result)
|
||||
except (LexError, ParseError, EvalError) as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -0,0 +1,50 @@
|
||||
"""
|
||||
AST evaluator for the calc expression language.
|
||||
|
||||
evaluate(node) -> int | float
|
||||
|
||||
Result type rule:
|
||||
- Integer arithmetic returns int.
|
||||
- Division (/) always uses true division; if the result is whole-valued
|
||||
(e.g. 4/2 == 2.0) it is coerced to int, otherwise returned as float.
|
||||
"""
|
||||
|
||||
from calc.parser import Num, BinOp, Unary
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node):
|
||||
"""Walk an AST node and return an int or float result."""
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
|
||||
if isinstance(node, Unary):
|
||||
val = evaluate(node.operand)
|
||||
if node.op == '-':
|
||||
return -val
|
||||
raise EvalError(f"Unknown unary operator: {node.op!r}")
|
||||
|
||||
if isinstance(node, BinOp):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
if node.op == '+':
|
||||
result = left + right
|
||||
elif node.op == '-':
|
||||
result = left - right
|
||||
elif node.op == '*':
|
||||
result = left * right
|
||||
elif node.op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("Division by zero")
|
||||
result = left / right
|
||||
else:
|
||||
raise EvalError(f"Unknown binary operator: {node.op!r}")
|
||||
# Coerce whole-valued floats to int so "4/2" prints as "2" not "2.0"
|
||||
if isinstance(result, float) and result.is_integer():
|
||||
return int(result)
|
||||
return result
|
||||
|
||||
raise EvalError(f"Unknown AST node type: {type(node).__name__!r}")
|
||||
58
calculators/builder-adversary-deferred/run-04/calc/lexer.py
Normal file
58
calculators/builder-adversary-deferred/run-04/calc/lexer.py
Normal file
@ -0,0 +1,58 @@
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Token:
|
||||
__slots__ = ('kind', 'value')
|
||||
|
||||
def __init__(self, kind: str, value):
|
||||
self.kind = kind
|
||||
self.value = value
|
||||
|
||||
def __repr__(self):
|
||||
return f'Token({self.kind!r}, {self.value!r})'
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Token):
|
||||
return self.kind == other.kind and self.value == other.value
|
||||
return NotImplemented
|
||||
|
||||
|
||||
_SINGLE_CHAR = {
|
||||
'+': 'PLUS',
|
||||
'-': 'MINUS',
|
||||
'*': 'STAR',
|
||||
'/': 'SLASH',
|
||||
'(': 'LPAREN',
|
||||
')': 'RPAREN',
|
||||
}
|
||||
|
||||
|
||||
def tokenize(src: str) -> list:
|
||||
tokens = []
|
||||
i = 0
|
||||
n = len(src)
|
||||
while i < n:
|
||||
c = src[i]
|
||||
if c in ' \t':
|
||||
i += 1
|
||||
elif c in _SINGLE_CHAR:
|
||||
tokens.append(Token(_SINGLE_CHAR[c], c))
|
||||
i += 1
|
||||
elif c.isdigit() or c == '.':
|
||||
start = i
|
||||
has_dot = False
|
||||
while i < n and (src[i].isdigit() or (src[i] == '.' and not has_dot)):
|
||||
if src[i] == '.':
|
||||
has_dot = True
|
||||
i += 1
|
||||
num_str = src[start:i]
|
||||
try:
|
||||
value = float(num_str) if has_dot else int(num_str)
|
||||
except ValueError:
|
||||
raise LexError(f"Invalid number {num_str!r} at position {start}")
|
||||
tokens.append(Token('NUMBER', value))
|
||||
else:
|
||||
raise LexError(f"Unexpected character {c!r} at position {i}")
|
||||
tokens.append(Token('EOF', None))
|
||||
return tokens
|
||||
149
calculators/builder-adversary-deferred/run-04/calc/parser.py
Normal file
149
calculators/builder-adversary-deferred/run-04/calc/parser.py
Normal file
@ -0,0 +1,149 @@
|
||||
"""
|
||||
Recursive-descent parser for the calc expression grammar.
|
||||
|
||||
Grammar:
|
||||
expr = term ( ('+' | '-') term )*
|
||||
term = unary ( ('*' | '/') unary )*
|
||||
unary = '-' unary | primary
|
||||
primary = NUMBER | '(' expr ')'
|
||||
|
||||
AST node shapes (stable contract for the evaluator):
|
||||
Num(value) — numeric literal; .value is int or float
|
||||
BinOp(op, left, right) — binary operation; .op is '+', '-', '*', or '/'
|
||||
Unary(op, operand) — unary prefix; .op is '-'
|
||||
"""
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AST nodes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Num:
|
||||
__slots__ = ('value',)
|
||||
|
||||
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:
|
||||
__slots__ = ('op', 'left', 'right')
|
||||
|
||||
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:
|
||||
__slots__ = ('op', 'operand')
|
||||
|
||||
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)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Parser
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class _Parser:
|
||||
def __init__(self, tokens):
|
||||
self._tokens = tokens
|
||||
self._pos = 0
|
||||
|
||||
def _peek(self):
|
||||
return self._tokens[self._pos]
|
||||
|
||||
def _advance(self):
|
||||
tok = self._tokens[self._pos]
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def _expect(self, kind):
|
||||
tok = self._peek()
|
||||
if tok.kind != kind:
|
||||
raise ParseError(
|
||||
f"Expected {kind}, got {tok.kind!r} ({tok.value!r})"
|
||||
)
|
||||
return self._advance()
|
||||
|
||||
# expr = term ( ('+' | '-') term )*
|
||||
def _expr(self):
|
||||
node = self._term()
|
||||
while self._peek().kind in ('PLUS', 'MINUS'):
|
||||
op = self._advance().value
|
||||
node = BinOp(op, node, self._term())
|
||||
return node
|
||||
|
||||
# term = unary ( ('*' | '/') unary )*
|
||||
def _term(self):
|
||||
node = self._unary()
|
||||
while self._peek().kind in ('STAR', 'SLASH'):
|
||||
op = self._advance().value
|
||||
node = BinOp(op, node, self._unary())
|
||||
return node
|
||||
|
||||
# unary = '-' unary | primary
|
||||
def _unary(self):
|
||||
if self._peek().kind == 'MINUS':
|
||||
self._advance()
|
||||
return Unary('-', self._unary())
|
||||
return self._primary()
|
||||
|
||||
# primary = NUMBER | '(' expr ')'
|
||||
def _primary(self):
|
||||
tok = self._peek()
|
||||
if tok.kind == 'NUMBER':
|
||||
self._advance()
|
||||
return Num(tok.value)
|
||||
if tok.kind == 'LPAREN':
|
||||
self._advance()
|
||||
node = self._expr()
|
||||
self._expect('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(self):
|
||||
if self._peek().kind == 'EOF':
|
||||
raise ParseError("Empty input")
|
||||
node = self._expr()
|
||||
if self._peek().kind != 'EOF':
|
||||
tok = self._peek()
|
||||
raise ParseError(
|
||||
f"Unexpected token after expression: {tok.kind!r} ({tok.value!r})"
|
||||
)
|
||||
return node
|
||||
|
||||
|
||||
def parse(tokens) -> object:
|
||||
"""Parse a token list produced by `calc.lexer.tokenize` into an AST."""
|
||||
return _Parser(tokens).parse()
|
||||
@ -0,0 +1,131 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from calc.evaluator import EvalError, evaluate
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse
|
||||
|
||||
|
||||
def calc(s):
|
||||
return evaluate(parse(tokenize(s)))
|
||||
|
||||
|
||||
class TestArithmetic(unittest.TestCase):
|
||||
"""D1 — arithmetic operators, precedence, parens, unary minus."""
|
||||
|
||||
def test_addition(self):
|
||||
self.assertEqual(calc("1+2"), 3)
|
||||
|
||||
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_precedence_paren(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_mul(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
def test_negative_literal(self):
|
||||
self.assertEqual(calc("-5"), -5)
|
||||
|
||||
def test_nested_parens(self):
|
||||
self.assertEqual(calc("((2+3))*4"), 20)
|
||||
|
||||
|
||||
class TestDivision(unittest.TestCase):
|
||||
"""D2 — true division and EvalError on divide-by-zero."""
|
||||
|
||||
def test_true_division(self):
|
||||
self.assertEqual(calc("7/2"), 3.5)
|
||||
|
||||
def test_division_by_zero_raises_eval_error(self):
|
||||
with self.assertRaises(EvalError):
|
||||
calc("1/0")
|
||||
|
||||
def test_division_by_zero_no_bare_exception(self):
|
||||
"""ZeroDivisionError must not escape the API."""
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError escaped the evaluate() API")
|
||||
|
||||
def test_division_chain(self):
|
||||
self.assertEqual(calc("8/4/2"), 1)
|
||||
|
||||
|
||||
class TestResultType(unittest.TestCase):
|
||||
"""D3 — result type: whole-valued → int, non-whole → float."""
|
||||
|
||||
def test_whole_division_returns_int(self):
|
||||
result = calc("4/2")
|
||||
self.assertEqual(result, 2)
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
def test_non_whole_division_returns_float(self):
|
||||
result = calc("7/2")
|
||||
self.assertEqual(result, 3.5)
|
||||
self.assertIsInstance(result, float)
|
||||
|
||||
def test_integer_arithmetic_returns_int(self):
|
||||
result = calc("2+3*4")
|
||||
self.assertEqual(result, 14)
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
def test_whole_str_no_dot(self):
|
||||
self.assertEqual(str(calc("4/2")), "2")
|
||||
|
||||
def test_float_str_has_dot(self):
|
||||
self.assertEqual(str(calc("7/2")), "3.5")
|
||||
|
||||
|
||||
class TestCLI(unittest.TestCase):
|
||||
"""D4 — CLI behaviour."""
|
||||
|
||||
def _run(self, expr):
|
||||
return subprocess.run(
|
||||
[sys.executable, 'calc.py', expr],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
|
||||
def test_valid_simple(self):
|
||||
r = self._run("2+3*4")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "14")
|
||||
self.assertEqual(r.stderr, "")
|
||||
|
||||
def test_valid_parens(self):
|
||||
r = self._run("(2+3)*4")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "20")
|
||||
|
||||
def test_invalid_exits_nonzero(self):
|
||||
r = self._run("1 +")
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
|
||||
def test_invalid_error_to_stderr(self):
|
||||
r = self._run("1 +")
|
||||
self.assertEqual(r.stdout, "")
|
||||
self.assertTrue(r.stderr.strip(), "expected error message on stderr")
|
||||
|
||||
def test_invalid_no_traceback(self):
|
||||
r = self._run("1 +")
|
||||
self.assertNotIn("Traceback", r.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
118
calculators/builder-adversary-deferred/run-04/calc/test_lexer.py
Normal file
118
calculators/builder-adversary-deferred/run-04/calc/test_lexer.py
Normal file
@ -0,0 +1,118 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize, Token, LexError
|
||||
|
||||
|
||||
class TestNumbers(unittest.TestCase):
|
||||
def test_integer(self):
|
||||
result = tokenize("42")
|
||||
self.assertEqual(result, [Token('NUMBER', 42), Token('EOF', None)])
|
||||
self.assertIsInstance(result[0].value, int)
|
||||
|
||||
def test_float_standard(self):
|
||||
result = tokenize("3.14")
|
||||
self.assertEqual(result[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(result[0].value, 3.14)
|
||||
self.assertIsInstance(result[0].value, float)
|
||||
|
||||
def test_float_leading_dot(self):
|
||||
result = tokenize(".5")
|
||||
self.assertEqual(result[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(result[0].value, 0.5)
|
||||
self.assertIsInstance(result[0].value, float)
|
||||
|
||||
def test_float_trailing_dot(self):
|
||||
result = tokenize("10.")
|
||||
self.assertEqual(result[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(result[0].value, 10.0)
|
||||
self.assertIsInstance(result[0].value, float)
|
||||
|
||||
def test_eof_is_last(self):
|
||||
result = tokenize("42")
|
||||
self.assertEqual(result[-1].kind, 'EOF')
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def _kinds(self, src):
|
||||
return [t.kind for t in tokenize(src)]
|
||||
|
||||
def test_plus(self):
|
||||
self.assertEqual(self._kinds("+"), ['PLUS', 'EOF'])
|
||||
|
||||
def test_minus(self):
|
||||
self.assertEqual(self._kinds("-"), ['MINUS', 'EOF'])
|
||||
|
||||
def test_star(self):
|
||||
self.assertEqual(self._kinds("*"), ['STAR', 'EOF'])
|
||||
|
||||
def test_slash(self):
|
||||
self.assertEqual(self._kinds("/"), ['SLASH', 'EOF'])
|
||||
|
||||
def test_lparen(self):
|
||||
self.assertEqual(self._kinds("("), ['LPAREN', 'EOF'])
|
||||
|
||||
def test_rparen(self):
|
||||
self.assertEqual(self._kinds(")"), ['RPAREN', 'EOF'])
|
||||
|
||||
def test_expression_1_plus_2_star_3(self):
|
||||
self.assertEqual(
|
||||
self._kinds("1+2*3"),
|
||||
['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'],
|
||||
)
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def _kinds(self, src):
|
||||
return [t.kind for t in tokenize(src)]
|
||||
|
||||
def test_whitespace_around_tokens(self):
|
||||
result = tokenize(" 12 + 3 ")
|
||||
self.assertEqual(
|
||||
[t.kind for t in result],
|
||||
['NUMBER', 'PLUS', 'NUMBER', 'EOF'],
|
||||
)
|
||||
nums = [t.value for t in result if t.kind == 'NUMBER']
|
||||
self.assertEqual(nums, [12, 3])
|
||||
|
||||
def test_complex_expression(self):
|
||||
result = tokenize("3.5*(1-2)")
|
||||
self.assertEqual(
|
||||
[t.kind for t in result],
|
||||
['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'],
|
||||
)
|
||||
self.assertAlmostEqual(result[0].value, 3.5)
|
||||
self.assertEqual(result[3].value, 1)
|
||||
self.assertEqual(result[5].value, 2)
|
||||
|
||||
def test_lex_error_at_sign(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("1 @ 2")
|
||||
|
||||
def test_lex_error_dollar(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$")
|
||||
|
||||
def test_lex_error_letter(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("x + 1")
|
||||
|
||||
def test_lex_error_message_contains_char(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('@', str(ctx.exception))
|
||||
|
||||
def test_lex_error_message_contains_position(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
# '@' is at position 2
|
||||
self.assertIn('2', str(ctx.exception))
|
||||
|
||||
def test_tab_whitespace(self):
|
||||
result = tokenize("1\t+\t2")
|
||||
self.assertEqual(
|
||||
[t.kind for t in result],
|
||||
['NUMBER', 'PLUS', 'NUMBER', 'EOF'],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@ -0,0 +1,128 @@
|
||||
import unittest
|
||||
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError, Num, BinOp, Unary
|
||||
|
||||
|
||||
def p(src):
|
||||
return parse(tokenize(src))
|
||||
|
||||
|
||||
class TestPrecedence(unittest.TestCase):
|
||||
"""D1 — * and / bind tighter than + and -."""
|
||||
|
||||
def test_add_then_mul(self):
|
||||
# 1+2*3 → BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
self.assertEqual(p('1+2*3'), BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
def test_mul_then_add(self):
|
||||
# 2*3+4 → BinOp('+', BinOp('*', Num(2), Num(3)), Num(4))
|
||||
self.assertEqual(p('2*3+4'), BinOp('+', BinOp('*', Num(2), Num(3)), Num(4)))
|
||||
|
||||
def test_add_then_div(self):
|
||||
# 1+6/2 → BinOp('+', Num(1), BinOp('/', Num(6), Num(2)))
|
||||
self.assertEqual(p('1+6/2'), BinOp('+', Num(1), BinOp('/', Num(6), Num(2))))
|
||||
|
||||
def test_sub_then_mul(self):
|
||||
# 10-2*3 → BinOp('-', Num(10), BinOp('*', Num(2), Num(3)))
|
||||
self.assertEqual(p('10-2*3'), BinOp('-', Num(10), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
|
||||
class TestLeftAssociativity(unittest.TestCase):
|
||||
"""D2 — same-precedence operators associate left."""
|
||||
|
||||
def test_sub_sub(self):
|
||||
# 8-3-2 → BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))
|
||||
self.assertEqual(p('8-3-2'), BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)))
|
||||
|
||||
def test_div_div(self):
|
||||
# 8/4/2 → BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))
|
||||
self.assertEqual(p('8/4/2'), BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)))
|
||||
|
||||
def test_add_add(self):
|
||||
# 1+2+3 → BinOp('+', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
self.assertEqual(p('1+2+3'), BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_mul_mul(self):
|
||||
# 2*3*4 → BinOp('*', BinOp('*', Num(2), Num(3)), Num(4))
|
||||
self.assertEqual(p('2*3*4'), BinOp('*', BinOp('*', Num(2), Num(3)), Num(4)))
|
||||
|
||||
|
||||
class TestParentheses(unittest.TestCase):
|
||||
"""D3 — parens override precedence."""
|
||||
|
||||
def test_parens_override_mul(self):
|
||||
# (1+2)*3 → BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
self.assertEqual(p('(1+2)*3'), BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_nested_parens(self):
|
||||
# (1+(2*3)) → BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
self.assertEqual(p('(1+(2*3))'), BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
|
||||
|
||||
def test_parens_on_right(self):
|
||||
# 3*(1+2) → BinOp('*', Num(3), BinOp('+', Num(1), Num(2)))
|
||||
self.assertEqual(p('3*(1+2)'), BinOp('*', Num(3), BinOp('+', Num(1), Num(2))))
|
||||
|
||||
def test_double_parens(self):
|
||||
# ((7)) → Num(7)
|
||||
self.assertEqual(p('((7))'), Num(7))
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
"""D4 — leading and nested unary minus."""
|
||||
|
||||
def test_simple_unary(self):
|
||||
# -5 → Unary('-', Num(5))
|
||||
self.assertEqual(p('-5'), Unary('-', Num(5)))
|
||||
|
||||
def test_unary_paren(self):
|
||||
# -(1+2) → Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
self.assertEqual(p('-(1+2)'), Unary('-', BinOp('+', Num(1), Num(2))))
|
||||
|
||||
def test_unary_in_binop(self):
|
||||
# 3 * -2 → BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
self.assertEqual(p('3 * -2'), BinOp('*', Num(3), Unary('-', Num(2))))
|
||||
|
||||
def test_double_unary(self):
|
||||
# --5 → Unary('-', Unary('-', Num(5)))
|
||||
self.assertEqual(p('--5'), Unary('-', Unary('-', Num(5))))
|
||||
|
||||
def test_unary_in_add(self):
|
||||
# 1 + -2 → BinOp('+', Num(1), Unary('-', Num(2)))
|
||||
self.assertEqual(p('1 + -2'), BinOp('+', Num(1), Unary('-', Num(2))))
|
||||
|
||||
|
||||
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_before_open(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p(')(')
|
||||
|
||||
def test_empty_string(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p('')
|
||||
|
||||
def test_only_operator(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p('*')
|
||||
|
||||
def test_double_op(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p('1 + + 2')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@ -0,0 +1,9 @@
|
||||
# BACKLOG — eval phase
|
||||
|
||||
## Build backlog
|
||||
|
||||
_(Builder's items — read-only for Adversary)_
|
||||
|
||||
## Adversary findings
|
||||
|
||||
_(To be populated after comprehensive cold-verification of eval phase build.)_
|
||||
@ -0,0 +1,14 @@
|
||||
# BACKLOG — lex phase
|
||||
|
||||
## Build backlog
|
||||
|
||||
- [x] D1 — NUMBER token for integers and floats (int/float value)
|
||||
- [x] D2 — PLUS, MINUS, STAR, SLASH, LPAREN, RPAREN, EOF tokens
|
||||
- [x] D3 — skip whitespace (space/tab); raise LexError on invalid char
|
||||
- [x] D4 — calc/test_lexer.py passing 20 unittest cases
|
||||
|
||||
All items complete.
|
||||
|
||||
## Adversary findings
|
||||
|
||||
_(No findings yet.)_
|
||||
@ -0,0 +1,9 @@
|
||||
# BACKLOG — parse phase
|
||||
|
||||
## Build backlog
|
||||
|
||||
_(Builder manages this section.)_
|
||||
|
||||
## Adversary findings
|
||||
|
||||
_(No findings yet — comprehensive verification deferred to review phase.)_
|
||||
@ -0,0 +1,10 @@
|
||||
# BACKLOG — review phase
|
||||
|
||||
## Build backlog
|
||||
|
||||
- [ ] Address any findings filed by Adversary in REVIEW-review.md
|
||||
- [ ] Write "## DONE" to STATUS-review.md after Adversary's comprehensive PASS
|
||||
|
||||
## Adversary findings
|
||||
|
||||
(Adversary writes here)
|
||||
@ -0,0 +1,7 @@
|
||||
# DECISIONS — shared (append-only)
|
||||
|
||||
## 2026-06-16T01:44Z
|
||||
|
||||
Adversary adopting DEFERRED review cadence per standing role instructions.
|
||||
Per-gate verdicts will NOT be written during build phases (lex/parse/eval).
|
||||
Comprehensive cold-verification deferred to the `review` phase.
|
||||
@ -0,0 +1,10 @@
|
||||
# JOURNAL — eval phase (Adversary)
|
||||
|
||||
## 2026-06-16 — Initialization
|
||||
|
||||
- Pulled repo: 44 tests passing (lex + parse baseline clean).
|
||||
- Eval phase not yet built: no evaluator.py, no calc.py, no STATUS-eval.md.
|
||||
- Initialized REVIEW-eval.md, BACKLOG-eval.md, JOURNAL-eval.md.
|
||||
- Early probes on existing AST shapes confirm correct parse output for all D1 eval test cases.
|
||||
- Key risks identified: EvalError vs ZeroDivisionError boundary (D2), whole-value formatting (D3), traceback suppression in CLI (D4).
|
||||
- Waiting for Builder to implement eval phase.
|
||||
@ -0,0 +1,43 @@
|
||||
# JOURNAL — lex phase
|
||||
|
||||
## 2026-06-16T01:44Z — Adversary initialized
|
||||
|
||||
Adversary loop started. Phase plan read. DEFERRED review protocol noted.
|
||||
Working directory is clean (only seed commit). Waiting for Builder to push code.
|
||||
|
||||
Coordination files created:
|
||||
- machine-docs/STATUS-lex.md
|
||||
- machine-docs/REVIEW-lex.md
|
||||
- machine-docs/BACKLOG-lex.md
|
||||
- machine-docs/JOURNAL-lex.md (this file)
|
||||
|
||||
## 2026-06-16T01:46Z — Builder: implementation complete
|
||||
|
||||
**Plan read:** lex.md — tokenizer for arithmetic calculator.
|
||||
|
||||
**Design decisions:**
|
||||
- `Token` uses `__slots__` for efficiency; has `__eq__` for test assertions.
|
||||
- `LexError(Exception)` with message including char and position.
|
||||
- Number parsing: scan while digit or (`.` and not yet seen dot) → convert to `int` or `float` based on `has_dot`.
|
||||
- Handles `.5`, `10.`, `3.14` per spec.
|
||||
- Single-char dispatch table for operators/parens.
|
||||
|
||||
**Test run output:**
|
||||
```
|
||||
Ran 20 tests in 0.001s
|
||||
OK
|
||||
```
|
||||
|
||||
**Plan verify commands output:**
|
||||
```
|
||||
python -m unittest -q
|
||||
→ Ran 20 tests in 0.001s / OK
|
||||
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"
|
||||
→ [('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]
|
||||
|
||||
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
|
||||
→ LexError: Unexpected character '@' at position 2
|
||||
```
|
||||
|
||||
All DoD items D1–D4 satisfied. Self-certifying as BUILD phase.
|
||||
@ -0,0 +1,23 @@
|
||||
# JOURNAL — review phase
|
||||
|
||||
## 2026-06-16 — review phase start
|
||||
|
||||
Read phase plan. Prior phases (lex, parse, eval) all self-certified DONE under DEFERRED protocol.
|
||||
|
||||
Full test suite pre-run:
|
||||
```
|
||||
python -m unittest -q
|
||||
Ran 68 tests in 0.077s
|
||||
OK
|
||||
```
|
||||
|
||||
Cross-feature D3 cases manually verified:
|
||||
- `-(-(1+2))` → 3 (exit 0) ✓
|
||||
- `2+3*4-5/5` → 13 (exit 0) ✓
|
||||
- `1 @ 2` → Error: Unexpected character '@' at position 2 (stderr, exit 1) ✓
|
||||
- `1/0` → Error: Division by zero (stderr, exit 1) ✓
|
||||
- `(1+` → Error: Unexpected end of input (stderr, exit 1) ✓
|
||||
- ` 3.14 * (2 + 1) ` → 9.42 (exit 0) ✓
|
||||
- `1.5 + (2.5 * 2)` → 6.5 (exit 0) ✓
|
||||
|
||||
STATUS-review.md filed with complete verification instructions. Claiming D1/D2/D3 ready for Adversary comprehensive cold-verification.
|
||||
@ -0,0 +1,27 @@
|
||||
# REVIEW — eval phase
|
||||
|
||||
**Protocol:** DEFERRED. Comprehensive verification runs once the eval phase build is complete, covering ALL prior DoD items (lex + parse + eval) in one cold pass.
|
||||
|
||||
## Verdicts
|
||||
|
||||
_No verdicts written yet — awaiting eval phase build completion._
|
||||
|
||||
## Early Probes
|
||||
|
||||
**Baseline (pre-eval):** 44 tests pass (20 lex + 24 parser). No regression risk from prior phases.
|
||||
|
||||
**AST shapes verified for D1 eval cases:**
|
||||
- `2+3*4` → `BinOp('+', Num(2), BinOp('*', Num(3), Num(4)))` ✓ (evaluates to 14)
|
||||
- `(2+3)*4` → `BinOp('*', BinOp('+', Num(2), Num(3)), Num(4))` ✓ (evaluates to 20)
|
||||
- `8-3-2` → `BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))` ✓ (evaluates to 3)
|
||||
- `-2+5` → `BinOp('+', Unary('-', Num(2)), Num(5))` ✓ (evaluates to 3)
|
||||
- `2*-3` → `BinOp('*', Num(2), Unary('-', Num(3)))` ✓ (evaluates to -6)
|
||||
|
||||
**Probe targets to hit once eval is built:**
|
||||
- `1/0` → EvalError (not bare ZeroDivisionError), stderr, non-zero exit
|
||||
- `4/2` → prints `2` (not `2.0`) — D3 whole-value rule
|
||||
- `7/2` → prints `3.5` — D3 non-whole rule
|
||||
- `1 +` → error to stderr, exit non-zero, no Python traceback
|
||||
- `--5` → what does the evaluator do with double unary? (parser accepts it: Unary('-', Unary('-', Num(5))))
|
||||
- Float literals: `2.5*2` → 5.0 or 5?
|
||||
- Whitespace-only: `" "` → ParseError from parser (Empty input after lex strips spaces)
|
||||
@ -0,0 +1,11 @@
|
||||
# REVIEW — lex phase
|
||||
|
||||
**Protocol:** DEFERRED. Comprehensive verification runs in the `review` phase, not per-gate.
|
||||
|
||||
## Verdicts
|
||||
|
||||
_No verdicts written yet — awaiting comprehensive review phase._
|
||||
|
||||
## Early Probes
|
||||
|
||||
_(Findings from early break-it probes logged here as they occur.)_
|
||||
@ -0,0 +1,11 @@
|
||||
# REVIEW — parse phase
|
||||
|
||||
**Protocol:** DEFERRED. Comprehensive verification runs in the `review` phase, not per-gate.
|
||||
|
||||
## Verdicts
|
||||
|
||||
_No verdicts written yet — awaiting comprehensive review phase._
|
||||
|
||||
## Early Probes
|
||||
|
||||
_(Findings from early break-it probes logged here as they occur.)_
|
||||
@ -0,0 +1,83 @@
|
||||
# REVIEW — review phase
|
||||
|
||||
## review(all): PASS @2026-06-16T00:00Z
|
||||
|
||||
Adversary cold-verification of the entire accumulated build (lex + parse + eval).
|
||||
|
||||
---
|
||||
|
||||
## D1 — Full cold re-verify (all prior phase DoD)
|
||||
|
||||
Re-ran from scratch in the work-adv clone (fresh pull, no cached state).
|
||||
|
||||
**Test suite:** `python -m unittest -v` → Ran 68 tests in 0.087s — **OK, 0 failures**
|
||||
|
||||
Subsystems verified:
|
||||
- Lexer (20 tests): tokens, numbers (int/float), operators, parens, whitespace, LexError ✓
|
||||
- Parser (24 tests): AST node shape, precedence, left-assoc, unary, parens, ParseError ✓
|
||||
- Evaluator (24 tests): arithmetic, true division, result types (int/float coercion), CLI, EvalError ✓
|
||||
|
||||
**D1: PASS**
|
||||
|
||||
---
|
||||
|
||||
## D2 — Full suite green
|
||||
|
||||
`python -m unittest -q` → `Ran 68 tests in 0.087s / OK`
|
||||
|
||||
**D2: PASS**
|
||||
|
||||
---
|
||||
|
||||
## D3 — Cross-feature break-it
|
||||
|
||||
All of Builder's pre-verified table confirmed independently:
|
||||
|
||||
| Expression | Expected | Actual | Exit |
|
||||
|----------------------|----------------------|-----------------------------------|------|
|
||||
| `-(-(1+2))` | 3 (int) | 3 (int) | 0 |
|
||||
| `2+3*4-5/5` | 13 (int) | 13 (int) | 0 |
|
||||
| `1 @ 2` | LexError on stderr | Error: Unexpected character '@' at position 2 | 1 |
|
||||
| `1/0` | EvalError on stderr | Error: Division by zero | 1 |
|
||||
| `(1+` | ParseError on stderr | Error: Unexpected end of input | 1 |
|
||||
| ` 3.14 * (2 + 1) ` | 9.42 (float) | 9.42 (float) | 0 |
|
||||
| `1.5 + (2.5 * 2)` | 6.5 (float) | 6.5 (float) | 0 |
|
||||
|
||||
Additional adversary probes (break-it attempts):
|
||||
|
||||
| Expression | Expected | Actual | Status |
|
||||
|------------------------|-------------------|------------------------|--------|
|
||||
| `6.0/2` | 3 (int) | 3 (int) | PASS |
|
||||
| `(.5+.5)*4` | 4 (int) | 4 (int) | PASS |
|
||||
| `-0` | 0 (int) | 0 (int) | PASS |
|
||||
| `---5` | -5 (int) | -5 (int) | PASS |
|
||||
| `1.5+1.5` | 3 (int) | 3 (int) | PASS |
|
||||
| `-2*3` | -6 (int) | -6 (int) | PASS |
|
||||
| `2-1-1` | 0 (int, L-assoc) | 0 (int) | PASS |
|
||||
| `8/4/2` | 1 (int, L-assoc) | 1 (int) | PASS |
|
||||
| `((3+1)*2-(4/2))/3` | 2 (int) | 2 (int) | PASS |
|
||||
| `1+2 3` | ParseError | ParseError: Unexpected token after expression | PASS |
|
||||
| `1++2` | ParseError | ParseError: Unexpected token 'PLUS' | PASS |
|
||||
| `(1+2` | ParseError | ParseError: Expected RPAREN, got 'EOF' | PASS |
|
||||
| `1+2)` | ParseError | ParseError: Unexpected token after expression | PASS |
|
||||
| `)(` (mismatched) | ParseError | ParseError: Unexpected token 'RPAREN' | PASS |
|
||||
| ` ` (whitespace only)| ParseError | ParseError: Empty input | PASS |
|
||||
| `""` (empty string) | ParseError | ParseError: Empty input | PASS |
|
||||
|
||||
No error leaked a bare traceback on any path. ZeroDivisionError does not escape `evaluate()`.
|
||||
|
||||
**D3: PASS**
|
||||
|
||||
---
|
||||
|
||||
## D4 — Findings cleared
|
||||
|
||||
No defects found. No VETOs.
|
||||
|
||||
**D4: PASS**
|
||||
|
||||
---
|
||||
|
||||
## Verdict
|
||||
|
||||
**review(all): PASS** — every DoD item from every phase (lex, parse, eval, review) verified by Adversary from cold state. No findings. No VETOs.
|
||||
@ -0,0 +1,82 @@
|
||||
# STATUS — eval phase
|
||||
|
||||
## DONE
|
||||
|
||||
All DoD gates D1–D5 implemented and self-certified (BUILD phase — DEFERRED review protocol).
|
||||
|
||||
---
|
||||
|
||||
## What was built
|
||||
|
||||
- `calc/evaluator.py` — `EvalError`, `evaluate(node) -> int | float` (AST walker)
|
||||
- `calc.py` — top-level CLI: string → tokens → AST → printed result; errors to stderr, non-zero exit
|
||||
- `calc/test_evaluator.py` — 24 unittest cases covering D1–D4; D5 = whole suite green
|
||||
|
||||
---
|
||||
|
||||
## Gates
|
||||
|
||||
### D1 — Arithmetic ✓
|
||||
|
||||
`evaluate(parse(tokenize(s)))` correct for +, -, *, /, precedence, parens, unary minus.
|
||||
|
||||
| Expression | Expected | Actual |
|
||||
|------------|----------|--------|
|
||||
| `2+3*4` | 14 | 14 |
|
||||
| `(2+3)*4` | 20 | 20 |
|
||||
| `8-3-2` | 3 | 3 |
|
||||
| `-2+5` | 3 | 3 |
|
||||
| `2*-3` | -6 | -6 |
|
||||
|
||||
### D2 — Division ✓
|
||||
|
||||
- `7/2` → 3.5 (true division)
|
||||
- `1/0` → `EvalError("Division by zero")` — NOT bare `ZeroDivisionError`
|
||||
|
||||
### D3 — Result type ✓
|
||||
|
||||
Rule: whole-valued results coerced to `int`; non-whole kept as `float`.
|
||||
|
||||
| Expression | Result | Type | str() |
|
||||
|------------|--------|-------|--------|
|
||||
| `4/2` | 2 | int | `"2"` |
|
||||
| `7/2` | 3.5 | float | `"3.5"`|
|
||||
| `2+3*4` | 14 | int | `"14"` |
|
||||
|
||||
### D4 — CLI ✓
|
||||
|
||||
```
|
||||
python calc.py "2+3*4" → stdout: 14 exit: 0
|
||||
python calc.py "(2+3)*4" → stdout: 20 exit: 0
|
||||
python calc.py "7/2" → stdout: 3.5 exit: 0
|
||||
python calc.py "4/2" → stdout: 2 exit: 0
|
||||
python calc.py "1/0" → stderr: Error: Division by zero exit: 1
|
||||
python calc.py "1 +" → stderr: Error: Unexpected end of input exit: 1
|
||||
```
|
||||
|
||||
No tracebacks on error paths.
|
||||
|
||||
### D5 — Tests green ✓
|
||||
|
||||
```
|
||||
python -m unittest -q
|
||||
→ Ran 68 tests in 0.XXXs / OK
|
||||
```
|
||||
|
||||
68 tests (20 lex + 24 parser + 24 evaluator), 0 failures, no regressions.
|
||||
|
||||
---
|
||||
|
||||
## Verify (cold)
|
||||
|
||||
```bash
|
||||
python -m unittest -q # Ran 68 tests … OK
|
||||
python calc.py "2+3*4" # 14
|
||||
python calc.py "(2+3)*4" # 20
|
||||
python calc.py "7/2" # 3.5
|
||||
python calc.py "4/2" # 2
|
||||
python calc.py "1/0" # Error: Division by zero (stderr, exit 1)
|
||||
python calc.py "1 +" # Error: Unexpected end of input (stderr, exit 1)
|
||||
```
|
||||
|
||||
Expected commit sha: `4fada74cca2255be4619fcffbe824ed6acf89a63`
|
||||
@ -0,0 +1,73 @@
|
||||
# STATUS — lex phase
|
||||
|
||||
## DONE
|
||||
|
||||
All DoD gates D1–D4 implemented and self-certified (BUILD phase — DEFERRED review protocol).
|
||||
|
||||
---
|
||||
|
||||
## What was built
|
||||
|
||||
- `calc/__init__.py` — makes `calc` a package
|
||||
- `calc/lexer.py` — `Token`, `LexError`, `tokenize(src) -> list[Token]`
|
||||
- `calc/test_lexer.py` — 20 unittest cases covering D1–D4
|
||||
|
||||
---
|
||||
|
||||
## D1 — Numbers ✓
|
||||
Integers and floats tokenize to NUMBER with correct Python type (int / float).
|
||||
|
||||
Verify:
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('42')])"
|
||||
# Expected: [('NUMBER', 42), ('EOF', None)]
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('.5')])"
|
||||
# Expected: [('NUMBER', 0.5), ('EOF', None)]
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('10.')])"
|
||||
# Expected: [('NUMBER', 10.0), ('EOF', None)]
|
||||
```
|
||||
|
||||
## D2 — Operators & Parens ✓
|
||||
All six single-char operators tokenize to the right kind.
|
||||
|
||||
Verify:
|
||||
```bash
|
||||
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 & Errors ✓
|
||||
Spaces/tabs skipped; invalid chars raise `LexError` with char + position.
|
||||
|
||||
Verify:
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
|
||||
# Expected: raises calc.lexer.LexError: Unexpected character '@' at position 2
|
||||
```
|
||||
|
||||
## D4 — Tests green ✓
|
||||
20 tests, 0 failures.
|
||||
|
||||
Verify:
|
||||
```bash
|
||||
python -m unittest -q
|
||||
# Expected: Ran 20 tests in 0.00xs / OK
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Plan verify commands (from lex.md)
|
||||
|
||||
```bash
|
||||
python -m unittest -q
|
||||
# → Ran 20 tests in 0.001s / OK
|
||||
|
||||
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"
|
||||
# → [('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]
|
||||
|
||||
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
|
||||
# → LexError: Unexpected character '@' at position 2
|
||||
```
|
||||
|
||||
Commit sha: 0092890 (chore: add .gitignore, remove tracked pycache)
|
||||
009755c (feat(lex): implement lexer, Token, LexError, and test suite)
|
||||
@ -0,0 +1,138 @@
|
||||
# STATUS — parse phase
|
||||
|
||||
## DONE
|
||||
|
||||
All DoD gates D1–D6 implemented and self-certified (BUILD phase — DEFERRED review protocol).
|
||||
|
||||
---
|
||||
|
||||
## What was built
|
||||
|
||||
- `calc/parser.py` — `ParseError`, `Num`, `BinOp`, `Unary`, `parse(tokens) -> Node`
|
||||
- `calc/test_parser.py` — 24 unittest cases covering D1–D5 (D6 = all pass)
|
||||
|
||||
---
|
||||
|
||||
## AST shape (stable contract for the evaluator)
|
||||
|
||||
```
|
||||
Num(value) .value — int or float
|
||||
BinOp(op, left, right) .op — one of '+', '-', '*', '/'
|
||||
.left — any Node
|
||||
.right — any Node
|
||||
Unary(op, operand) .op — '-'
|
||||
.operand — any Node
|
||||
```
|
||||
|
||||
All nodes implement `__repr__` and `__eq__`.
|
||||
|
||||
---
|
||||
|
||||
## D1 — Precedence ✓
|
||||
|
||||
`1+2*3` parses as `BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))` — `*` tighter than `+`.
|
||||
|
||||
Verify:
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('1+2*3')))"
|
||||
# Expected: BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
```
|
||||
|
||||
## D2 — Left associativity ✓
|
||||
|
||||
`8-3-2` → `BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))`
|
||||
`8/4/2` → `BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))`
|
||||
|
||||
Verify:
|
||||
```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 ✓
|
||||
|
||||
`(1+2)*3` → `BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))` — `+` is child of `*`.
|
||||
|
||||
Verify:
|
||||
```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 ✓
|
||||
|
||||
```
|
||||
-5 → Unary('-', Num(5))
|
||||
-(1+2) → Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
3 * -2 → BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
```
|
||||
|
||||
Verify:
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-5')))"
|
||||
# Expected: Unary('-', Num(5))
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-(1+2)')))"
|
||||
# Expected: Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('3 * -2')))"
|
||||
# Expected: BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
```
|
||||
|
||||
## D5 — Errors ✓
|
||||
|
||||
Each of the following raises `ParseError` (not any other exception):
|
||||
|
||||
| Input | ParseError message |
|
||||
|----------|--------------------|
|
||||
| `'1 +'` | `Unexpected end of input` |
|
||||
| `'(1'` | `Expected RPAREN, got 'EOF' (None)` |
|
||||
| `'1 2'` | `Unexpected token after expression: 'NUMBER' (2)` |
|
||||
| `')('` | `Unexpected token 'RPAREN' (')')` |
|
||||
| `''` | `Empty input` |
|
||||
|
||||
Verify:
|
||||
```bash
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize('1 +'))"
|
||||
# Expected: raises ParseError: Unexpected end of input
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize('(1'))"
|
||||
# Expected: raises ParseError: Expected RPAREN...
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize('1 2'))"
|
||||
# Expected: raises ParseError: Unexpected token after expression...
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize(')('))"
|
||||
# Expected: raises ParseError: Unexpected token 'RPAREN'...
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize(''))"
|
||||
# Expected: raises ParseError: Empty input
|
||||
```
|
||||
|
||||
## D6 — Tests green ✓
|
||||
|
||||
44 total tests (20 lex + 24 parser), 0 failures.
|
||||
|
||||
Verify:
|
||||
```bash
|
||||
python -m unittest -q
|
||||
# Expected: Ran 44 tests in 0.00xs / OK
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Plan verify commands (from parse.md)
|
||||
|
||||
```bash
|
||||
python -m unittest -q
|
||||
# → Ran 44 tests in 0.001s / OK
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('1+2*3')))"
|
||||
# → BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
|
||||
python -c "from calc.lexer import tokenize; from calc.parser import parse; parse(tokenize('1 +'))"
|
||||
# → ParseError: Unexpected end of input
|
||||
```
|
||||
@ -0,0 +1,68 @@
|
||||
# STATUS — review phase
|
||||
|
||||
## DONE
|
||||
|
||||
Adversary cold-verification: PASS (commit `6d89215`). All D1–D4 items verified, 0 findings, no VETOs.
|
||||
|
||||
---
|
||||
|
||||
## What the Adversary needs to verify
|
||||
|
||||
The entire accumulated build (lex + parse + eval phases) is complete and self-certified.
|
||||
The Adversary must cold-verify all three prior phases in one pass per the DEFERRED protocol.
|
||||
|
||||
### Commit
|
||||
|
||||
Expected commit sha: `0d4ee30`
|
||||
Branch: `main` (origin/main)
|
||||
|
||||
### D1 — Full cold re-verify (all prior phase DoD)
|
||||
|
||||
**HOW:** From a fresh clone, run:
|
||||
|
||||
```bash
|
||||
cd /tmp/<fresh-clone>
|
||||
python -m unittest -q
|
||||
```
|
||||
|
||||
**EXPECTED:** `Ran 68 tests in 0.XXXs / OK` — 0 failures
|
||||
|
||||
Subsystems verified:
|
||||
- Lexer (`calc/lexer.py`): 20 tests covering tokens, numbers, operators, whitespace, LexError
|
||||
- Parser (`calc/parser.py`): 24 tests covering AST shape, precedence, unary, parens, ParseError
|
||||
- Evaluator (`calc/evaluator.py`): 24 tests covering arithmetic, division, result types, CLI, EvalError
|
||||
|
||||
### D2 — Full suite green
|
||||
|
||||
**HOW:** `python -m unittest -q`
|
||||
**EXPECTED:** `Ran 68 tests in 0.XXXs / OK`
|
||||
|
||||
### D3 — Cross-feature break-it
|
||||
|
||||
Builder pre-verified all D3 cases (results below):
|
||||
|
||||
| Expression | Expected | Actual | Exit |
|
||||
|--------------------|----------|--------|------|
|
||||
| `-(-(1+2))` | 3 | 3 | 0 |
|
||||
| `2+3*4-5/5` | 13 | 13 | 0 |
|
||||
| `1 @ 2` | Error: Unexpected character '@' at position 2 (stderr) | ✓ | 1 |
|
||||
| `1/0` | Error: Division by zero (stderr) | ✓ | 1 |
|
||||
| `(1+` | Error: Unexpected end of input (stderr) | ✓ | 1 |
|
||||
| ` 3.14 * (2 + 1) `| 9.42 | 9.42 | 0 |
|
||||
| `1.5 + (2.5 * 2)` | 6.5 | 6.5 | 0 |
|
||||
|
||||
Adversary must re-run these and any additional break-it cases it chooses.
|
||||
|
||||
### D4 — Findings cleared
|
||||
|
||||
No findings yet. Adversary to file defects in REVIEW-review.md. Builder will address all findings.
|
||||
|
||||
---
|
||||
|
||||
## File locations
|
||||
|
||||
- `calc/lexer.py` — tokenizer
|
||||
- `calc/parser.py` — recursive-descent parser + AST nodes
|
||||
- `calc/evaluator.py` — AST evaluator + EvalError
|
||||
- `calc.py` — CLI entry point
|
||||
- `calc/test_lexer.py`, `calc/test_parser.py`, `calc/test_evaluator.py` — test suites
|
||||
Reference in New Issue
Block a user