artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs

This commit is contained in:
2026-06-16 15:39:42 +00:00
parent 64bc360fc0
commit bb85aa9f11
728 changed files with 34148 additions and 0 deletions

View File

@ -0,0 +1,16 @@
# git history (claim/review handshake), from the run's shared bare repo
931025b status(eval): DONE — all D1-D5 Adversary PASS @2026-06-15T02:05Z
7631a17 review(eval): PASS D1,D2,D3,D4,D5 — cold-verified all gates
d786616 status(eval): add commit sha to STATUS-eval.md
74dddbc claim(D1,D2,D3,D4,D5): implement evaluator, CLI, and tests for phase eval
69e3563 review(eval): init Adversary REVIEW file
1b7bb57 status(parse): DONE — all D1-D6 Adversary PASS @2026-06-15T02:00Z
6479762 review(parse): PASS D1,D2,D3,D4,D5,D6 — cold-verified all gates
0bf6616 claim(D1,D2,D3,D4,D5,D6): implement parser with all gates for phase parse
a819c33 review(parse): init Adversary REVIEW file
12505f4 status: mark phase lex DONE — all D1-D4 Adversary PASS
9b209c4 review(lex): PASS D1,D2,D3,D4 — cold-verified all gates
3440210 status: claim(D1,D2,D3,D4) all gates for lex phase — lexer+tests complete
bb84bf1 feat: implement lexer with tokenize() for phase lex (D1-D4)
b4c14b0 review(lex): init adversary REVIEW file
7bff854 chore: seed

View File

@ -0,0 +1 @@
# calc work repo

View File

@ -0,0 +1 @@
original path: /tmp/ao-campaign-Ofyz4E/builder-adversary-min/r1

View File

@ -0,0 +1,24 @@
"""calc.py — CLI entry point: python calc.py "<expression>" """
import sys
from calc.evaluator import EvalError, evaluate
from calc.lexer import LexError, tokenize
from calc.parser import ParseError, parse
def main():
if len(sys.argv) != 2:
print("Usage: calc.py <expression>", file=sys.stderr)
sys.exit(1)
expr = sys.argv[1]
try:
result = evaluate(parse(tokenize(expr)))
except (LexError, ParseError, EvalError) as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
print(result)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,43 @@
"""Evaluator for the calc AST.
Result type rule: if the result is a whole number, return int; otherwise return float.
Division is always true division. Division by zero raises EvalError.
"""
from calc.parser import Num, BinOp, Unary
class EvalError(Exception):
pass
def evaluate(node) -> int | float:
if isinstance(node, Num):
return node.value
if isinstance(node, Unary):
val = evaluate(node.operand)
if node.op == '-':
return _coerce(-val)
raise EvalError(f"Unknown unary op: {node.op!r}")
if isinstance(node, BinOp):
left = evaluate(node.left)
right = evaluate(node.right)
if node.op == '+':
return _coerce(left + right)
if node.op == '-':
return _coerce(left - right)
if node.op == '*':
return _coerce(left * right)
if node.op == '/':
if right == 0:
raise EvalError("Division by zero")
return _coerce(left / right)
raise EvalError(f"Unknown binary op: {node.op!r}")
raise EvalError(f"Unknown node type: {type(node)!r}")
def _coerce(val: int | float) -> int | float:
"""Return int if val is whole-valued, otherwise float."""
if isinstance(val, float) and val.is_integer():
return int(val)
return val

View File

@ -0,0 +1,62 @@
"""Lexer for arithmetic expressions."""
from dataclasses import dataclass
from typing import Union
class LexError(Exception):
pass
@dataclass
class Token:
kind: str
value: Union[int, float, None]
def __repr__(self):
return f"{self.kind}({self.value!r})"
def tokenize(src: str) -> list:
tokens = []
i = 0
while i < len(src):
ch = src[i]
if ch in ' \t':
i += 1
continue
if ch.isdigit() or (ch == '.' and i + 1 < len(src) and src[i + 1].isdigit()):
j = i
while j < len(src) and src[j].isdigit():
j += 1
if j < len(src) and src[j] == '.':
j += 1
while j < len(src) and src[j].isdigit():
j += 1
tokens.append(Token('NUMBER', float(src[i:j])))
else:
tokens.append(Token('NUMBER', int(src[i:j])))
i = j
continue
if ch == '+':
tokens.append(Token('PLUS', None))
elif ch == '-':
tokens.append(Token('MINUS', None))
elif ch == '*':
tokens.append(Token('STAR', None))
elif ch == '/':
tokens.append(Token('SLASH', None))
elif ch == '(':
tokens.append(Token('LPAREN', None))
elif ch == ')':
tokens.append(Token('RPAREN', None))
else:
raise LexError(f"Invalid character {ch!r} at position {i}")
i += 1
tokens.append(Token('EOF', None))
return tokens

View File

@ -0,0 +1,113 @@
"""Recursive-descent parser for arithmetic expressions.
AST node shapes:
Num(value) — numeric literal; value is int or float
BinOp(op, left, right) — binary op; op in {'+', '-', '*', '/'}
Unary(op, operand) — unary op; op is '-'
Grammar (lowest to highest precedence):
expr → term (('+' | '-') term)*
term → unary (('*' | '/') unary)*
unary → '-' unary | primary
primary → NUMBER | '(' expr ')'
"""
from dataclasses import dataclass
from typing import Union
class ParseError(Exception):
pass
@dataclass
class Num:
value: Union[int, float]
def __repr__(self):
return f"Num({self.value!r})"
@dataclass
class BinOp:
op: str
left: object
right: object
def __repr__(self):
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
@dataclass
class Unary:
op: str
operand: object
def __repr__(self):
return f"Unary({self.op!r}, {self.operand!r})"
Node = Union[Num, BinOp, Unary]
def parse(tokens: list) -> Node:
"""Parse a token list produced by tokenize() and return the AST root."""
if not tokens:
raise ParseError("Empty token list")
p = _Parser(tokens)
tree = p.expr()
if p.current().kind != 'EOF':
raise ParseError(f"Unexpected token {p.current()!r} after expression")
return tree
class _Parser:
def __init__(self, tokens):
self._tokens = tokens
self._pos = 0
def current(self):
return self._tokens[self._pos]
def consume(self, kind=None):
tok = self.current()
if kind is not None and tok.kind != kind:
raise ParseError(f"Expected {kind!r}, got {tok!r}")
self._pos += 1
return tok
def expr(self):
left = self.term()
while self.current().kind in ('PLUS', 'MINUS'):
tok = self.consume()
op = '+' if tok.kind == 'PLUS' else '-'
right = self.term()
left = BinOp(op, left, right)
return left
def term(self):
left = self.unary()
while self.current().kind in ('STAR', 'SLASH'):
tok = self.consume()
op = '*' if tok.kind == 'STAR' else '/'
right = self.unary()
left = BinOp(op, left, right)
return left
def unary(self):
if self.current().kind == 'MINUS':
self.consume()
return Unary('-', self.unary())
return self.primary()
def primary(self):
tok = self.current()
if tok.kind == 'NUMBER':
self.consume()
return Num(tok.value)
if tok.kind == 'LPAREN':
self.consume()
node = self.expr()
self.consume('RPAREN')
return node
raise ParseError(f"Unexpected token {tok!r}")

View File

@ -0,0 +1,98 @@
"""Tests for calc/evaluator.py covering D1-D4."""
import subprocess
import sys
import unittest
from calc.lexer import tokenize
from calc.parser import parse
from calc.evaluator import EvalError, evaluate
def calc(s):
return evaluate(parse(tokenize(s)))
class TestArithmetic(unittest.TestCase):
def test_precedence(self):
self.assertEqual(calc("2+3*4"), 14)
def test_parens(self):
self.assertEqual(calc("(2+3)*4"), 20)
def test_left_associative_sub(self):
self.assertEqual(calc("8-3-2"), 3)
def test_unary_minus(self):
self.assertEqual(calc("-2+5"), 3)
def test_unary_in_mul(self):
self.assertEqual(calc("2*-3"), -6)
class TestDivision(unittest.TestCase):
def test_true_division(self):
self.assertEqual(calc("7/2"), 3.5)
def test_div_by_zero(self):
with self.assertRaises(EvalError):
calc("1/0")
class TestResultType(unittest.TestCase):
def test_whole_division_returns_int(self):
result = calc("4/2")
self.assertEqual(result, 2)
self.assertIsInstance(result, int)
def test_non_whole_returns_float(self):
result = calc("7/2")
self.assertIsInstance(result, float)
def test_addition_int(self):
self.assertIsInstance(calc("1+2"), int)
class TestCLI(unittest.TestCase):
def _run(self, expr):
return subprocess.run(
[sys.executable, "calc.py", expr],
capture_output=True,
text=True,
)
def test_cli_basic(self):
r = self._run("2+3*4")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "14")
def test_cli_parens(self):
r = self._run("(2+3)*4")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "20")
def test_cli_float(self):
r = self._run("7/2")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "3.5")
def test_cli_whole_float(self):
r = self._run("4/2")
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "2")
def test_cli_div_zero_error(self):
r = self._run("1/0")
self.assertNotEqual(r.returncode, 0)
self.assertTrue(r.stderr.strip())
self.assertNotIn("Traceback", r.stderr)
def test_cli_invalid_expr_error(self):
r = self._run("1 +")
self.assertNotEqual(r.returncode, 0)
self.assertTrue(r.stderr.strip())
self.assertNotIn("Traceback", r.stderr)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,88 @@
import unittest
from calc.lexer import tokenize, Token, LexError
def kinds(src):
return [t.kind for t in tokenize(src)]
def tok(src):
return [(t.kind, t.value) for t in tokenize(src)]
class TestNumbers(unittest.TestCase):
def test_integer(self):
result = tokenize("42")
self.assertEqual(result[0], Token('NUMBER', 42))
self.assertEqual(result[1].kind, 'EOF')
self.assertIsInstance(result[0].value, int)
def test_float_standard(self):
result = tokenize("3.14")
self.assertAlmostEqual(result[0].value, 3.14)
self.assertEqual(result[0].kind, 'NUMBER')
def test_float_leading_dot(self):
result = tokenize(".5")
self.assertAlmostEqual(result[0].value, 0.5)
def test_float_trailing_dot(self):
result = tokenize("10.")
self.assertAlmostEqual(result[0].value, 10.0)
self.assertIsInstance(result[0].value, float)
class TestOperatorsAndParens(unittest.TestCase):
def test_operators(self):
self.assertEqual(kinds("1+2*3"), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
def test_minus_slash(self):
ks = kinds("4-2/1")
self.assertIn('MINUS', ks)
self.assertIn('SLASH', ks)
def test_parens(self):
ks = kinds("(1)")
self.assertIn('LPAREN', ks)
self.assertIn('RPAREN', ks)
def test_complex_expr(self):
result = tok("3.5*(1-2)")
expected_kinds = ['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF']
self.assertEqual([k for k, v in result], expected_kinds)
self.assertAlmostEqual(result[0][1], 3.5)
class TestWhitespaceAndErrors(unittest.TestCase):
def test_whitespace_skipped(self):
result = tok(" 12 + 3 ")
self.assertEqual([k for k, v in result], ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
self.assertEqual(result[0][1], 12)
self.assertEqual(result[2][1], 3)
def test_tab_whitespace(self):
result = kinds("\t1\t+\t2\t")
self.assertEqual(result, ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
def test_at_raises_lex_error(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
self.assertIn('@', str(ctx.exception))
def test_dollar_raises_lex_error(self):
with self.assertRaises(LexError):
tokenize("$10")
def test_letter_raises_lex_error(self):
with self.assertRaises(LexError):
tokenize("abc")
def test_error_reports_position(self):
with self.assertRaises(LexError) as ctx:
tokenize("1 @ 2")
msg = str(ctx.exception)
self.assertIn('2', msg)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,93 @@
import unittest
from calc.lexer import tokenize
from calc.parser import parse, ParseError, Num, BinOp, Unary
def p(src):
return parse(tokenize(src))
class TestPrecedence(unittest.TestCase):
"""D1 — * and / bind tighter than + and -."""
def test_mul_over_add(self):
self.assertEqual(p('1+2*3'), BinOp('+', Num(1), BinOp('*', Num(2), Num(3))))
def test_mul_over_sub(self):
self.assertEqual(p('1-2*3'), BinOp('-', Num(1), BinOp('*', Num(2), Num(3))))
def test_div_over_add(self):
self.assertEqual(p('4+6/2'), BinOp('+', Num(4), BinOp('/', Num(6), Num(2))))
class TestLeftAssociativity(unittest.TestCase):
"""D2 — same-precedence operators associate left."""
def test_sub_left(self):
self.assertEqual(p('8-3-2'), BinOp('-', BinOp('-', Num(8), Num(3)), Num(2)))
def test_div_left(self):
self.assertEqual(p('8/4/2'), BinOp('/', BinOp('/', Num(8), Num(4)), Num(2)))
def test_add_left(self):
self.assertEqual(p('1+2+3'), BinOp('+', BinOp('+', Num(1), Num(2)), Num(3)))
def test_mul_left(self):
self.assertEqual(p('2*3*4'), BinOp('*', BinOp('*', Num(2), Num(3)), Num(4)))
class TestParentheses(unittest.TestCase):
"""D3 — parens override precedence."""
def test_paren_overrides_precedence(self):
self.assertEqual(p('(1+2)*3'), BinOp('*', BinOp('+', Num(1), Num(2)), Num(3)))
def test_nested_parens(self):
self.assertEqual(p('((2+3))*4'), BinOp('*', BinOp('+', Num(2), Num(3)), Num(4)))
def test_paren_right_side(self):
self.assertEqual(p('3*(1+2)'), BinOp('*', Num(3), BinOp('+', Num(1), Num(2))))
class TestUnaryMinus(unittest.TestCase):
"""D4 — leading and nested unary minus."""
def test_unary_literal(self):
self.assertEqual(p('-5'), Unary('-', Num(5)))
def test_unary_paren(self):
self.assertEqual(p('-(1+2)'), Unary('-', BinOp('+', Num(1), Num(2))))
def test_unary_in_mul(self):
self.assertEqual(p('3 * -2'), BinOp('*', Num(3), Unary('-', Num(2))))
def test_double_unary(self):
self.assertEqual(p('--5'), Unary('-', Unary('-', Num(5))))
class TestErrors(unittest.TestCase):
"""D5 — malformed input raises ParseError."""
def test_trailing_op(self):
with self.assertRaises(ParseError):
p('1 +')
def test_unclosed_paren(self):
with self.assertRaises(ParseError):
p('(1')
def test_consecutive_numbers(self):
with self.assertRaises(ParseError):
p('1 2')
def test_close_before_open(self):
with self.assertRaises(ParseError):
p(')(')
def test_empty(self):
with self.assertRaises(ParseError):
p('')
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,3 @@
# BACKLOG-parse
(empty — all D1-D6 gates implemented and tested)

View File

@ -0,0 +1,9 @@
# JOURNAL — phase eval
## Implementation notes
- `evaluate()` walks the AST recursively using isinstance checks on Num/BinOp/Unary.
- `_coerce()` converts whole-valued floats to int (e.g. `4/2 → 2`).
- Division by zero raises `EvalError` (not the bare `ZeroDivisionError`).
- `calc.py` CLI catches `LexError`, `ParseError`, `EvalError` and prints to stderr with exit 1.
- Test suite has 49 total tests (lex + parse + eval); CLI tests use subprocess to exercise the full pipeline end-to-end.

View File

@ -0,0 +1,12 @@
# JOURNAL-lex
## Implementation notes
Built `calc/lexer.py` with:
- `Token` dataclass with `kind: str` and `value: Union[int, float, None]`
- `LexError(Exception)` for invalid characters
- `tokenize(src: str) -> list[Token]` scanning character by character
Number scanning handles all three forms: integer (`42`), standard float (`3.14`), leading-dot float (`.5`), and trailing-dot float (`10.`). The key invariant: when `ch` is `.` we only enter number scanning if the next char is also a digit (to avoid confusing `.` used as an operator in other contexts). Trailing dot (`10.`) is handled because after scanning digits we check if the next char is `.` and absorb it into a float.
14 tests written covering D1-D4 plus edge cases.

View File

@ -0,0 +1,14 @@
# JOURNAL-parse
## Implementation notes
Grammar chose iterative (not recursive) form for expr and term to ensure left-associativity without
risk of right-fold bugs. Unary uses right-recursive call to handle `--5` naturally.
Empty string: `tokenize("")` returns `[Token('EOF', None)]`. `primary()` sees EOF and raises
ParseError — no special-case needed.
`"1 2"` error: `parse()` checks that after `expr()` the current token is EOF; NUMBER is not EOF, so
ParseError raised cleanly.
`")("` error: `primary()` is called, sees RPAREN (not NUMBER or LPAREN), raises ParseError.

View File

@ -0,0 +1,57 @@
# Adversary REVIEW — phase eval
## Gates
- D1: PASS @2026-06-15T02:05Z
- D2: PASS @2026-06-15T02:05Z
- D3: PASS @2026-06-15T02:05Z
- D4: PASS @2026-06-15T02:05Z
- D5: PASS @2026-06-15T02:05Z
## Evidence
### D5 — full suite (49 tests, 0 failures)
```
Ran 49 tests in 0.218s
OK
```
### D1 — arithmetic / precedence / parens / unary minus
```
python calc.py "2+3*4" → 14 ✓
python calc.py "(2+3)*4" → 20 ✓
python calc.py "8-3-2" → 3 ✓
python calc.py "-2+5" → 3 ✓
python calc.py "2*-3" → -6 ✓
```
### D2 — true division + EvalError on zero
```
python calc.py "7/2" → 3.5 (exit 0) ✓
python calc.py "1/0" → Error: Division by zero (stderr, exit 1, no traceback) ✓
python calc.py "0/0" → Error: Division by zero (stderr, exit 1) ✓
```
No bare ZeroDivisionError escapes; EvalError wraps it correctly.
### D3 — result type
```
python calc.py "4/2" → 2 (int, no trailing .0) ✓
python calc.py "7/2" → 3.5 (float) ✓
python calc.py "100/10"→ 10 (whole-valued) ✓
python calc.py "1/3" → 0.3333333333333333 ✓
```
`_coerce()` correctly converts whole-valued floats to int.
### D4 — CLI
```
python calc.py "2+3*4" → stdout: 14, exit 0 ✓
python calc.py "1 +" → stderr: Error: Unexpected token EOF(None), exit 1, no traceback ✓
```
### Adversarial extras (all correct)
- `(-2)*(-3)` → 6 ✓
- `100/10` → 10 (no .0) ✓
- `1/3` → 0.333... ✓
- `0/0` → EvalError, exit 1 ✓
No regressions in lex or parse phases (49 tests = prior 39 + 10 new eval tests).

View File

@ -0,0 +1,34 @@
# REVIEW-lex
Adversary review log for phase `lex`.
<!-- verdicts appended below -->
## review(lex): PASS — 2026-06-15T00:00:00Z
**Commit verified:** bb84bf1
**Verified by:** Adversary (cold run, own clone)
### D1: PASS @2026-06-15T00:00:00Z
- `tokenize("42")``[NUMBER(42), EOF]`, value is `int`
- `tokenize("3.14")``NUMBER(3.14)` as float ✓
- `tokenize(".5")``NUMBER(0.5)` ✓ (leading-dot float branch correct)
- `tokenize("10.")``NUMBER(10.0)` as float ✓ (trailing-dot float branch correct)
### D2: PASS @2026-06-15T00:00:00Z
- `tokenize("1+2*3")``['NUMBER','PLUS','NUMBER','STAR','NUMBER','EOF']`
- All six operator/paren kinds recognized: `+ - * / ( )`
- `tokenize("3.5*(1-2)")``[('NUMBER',3.5),('STAR',None),('LPAREN',None),('NUMBER',1),('MINUS',None),('NUMBER',2),('RPAREN',None),('EOF',None)]`
### D3: PASS @2026-06-15T00:00:00Z
- `tokenize(" 12 + 3 ")``['NUMBER','PLUS','NUMBER','EOF']` ✓ (spaces/tabs skipped)
- `tokenize("1 @ 2")``LexError: Invalid character '@' at position 2`
- `tokenize("abc")``LexError`
- `tokenize("$10")``LexError`
- Error message includes offending char and position ✓
### D4: PASS @2026-06-15T00:00:00Z
- `python -m unittest -q` → 14 tests, 0 failures ✓
- Required cases covered: `" 12 + 3 "`, `"3.5*(1-2)"`, `"1 @ 2"` raises `LexError`
**All gates D1D4: PASS. No vetoes.**

View File

@ -0,0 +1,52 @@
# Adversary Review — phase `parse`
## Verdicts
| Gate | Result | Evidence |
|------|--------|----------|
| D1 | PASS | `parse(tokenize('1+2*3'))``BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))` |
| D2 | PASS | `8-3-2``BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))`; `8/4/2``BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))` |
| D3 | PASS | `(1+2)*3``BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))` |
| D4 | PASS | `-5``Unary('-', Num(5))`; `-(1+2)``Unary('-', BinOp('+', ...))`; `3 * -2``BinOp('*', Num(3), Unary('-', Num(2)))`; `--5``Unary('-', Unary('-', Num(5)))` |
| D5 | PASS | All 5 cases `'1 +'`, `'(1'`, `'1 2'`, `')('`, `''` raise `ParseError` (not any other exception) |
| D6 | PASS | `python -m unittest -q``Ran 33 tests in 0.001s OK` |
---
## Cold-run commands executed
```
python -m unittest -q
python -c "... parse(tokenize('1+2*3'))" # D1
python -c "... parse(tokenize('4+6/2'))" # D1
python -c "... parse(tokenize('8-3-2'))" # D2
python -c "... parse(tokenize('8/4/2'))" # D2
python -c "... parse(tokenize('(1+2)*3'))" # D3
python -c "... parse(tokenize('-5'))" # D4
python -c "... parse(tokenize('-(1+2)'))" # D4
python -c "... parse(tokenize('3 * -2'))" # D4
python -c "... parse(tokenize('--5'))" # D4 extra
python -c "... [all 5 error cases]" # D5
```
Extra edge cases (adversarial):
- `()` → ParseError ✓
- `1++2` → ParseError ✓ (no unary plus)
- `1 + + 2` → ParseError ✓
- `*3` → ParseError ✓
- `1*(2+3)*4``BinOp('*', BinOp('*', Num(1), BinOp('+', Num(2), Num(3))), Num(4))`
- `-1+2``BinOp('+', Unary('-', Num(1)), Num(2))`
- `1+2*3+4``BinOp('+', BinOp('+', Num(1), BinOp('*', Num(2), Num(3))), Num(4))`
---
## Notes
- The `if not tokens: raise ParseError("Empty token list")` guard in `parse()` is **dead code**`tokenize("")` always appends an EOF token so the list is never empty. The empty-string case still raises `ParseError` correctly via `primary()` seeing EOF. Not a bug; harmless dead code.
- Grammar structure (expr → term → unary → primary) correctly encodes precedence and left-associativity by construction.
---
## Summary
review(parse): PASS D1,D2,D3,D4,D5,D6 — cold-verified all gates @2026-06-15T02:00Z

View File

@ -0,0 +1,47 @@
# STATUS — phase eval
## WHAT is claimed
All gates D1D5 implemented and locally verified.
### Files added
- `calc/evaluator.py``EvalError`, `evaluate(node) -> int | float`
- `calc/test_evaluator.py` — unittest suite covering D1D4 (CLI via subprocess)
- `calc.py` — top-level CLI entry point
## Verify commands (exact) + expected results
```bash
# D5 — whole suite (lex + parse + eval), 0 failures
python -m unittest -q
# Expected: OK (49 tests)
# D1 — arithmetic / precedence / parens / unary
python calc.py "2+3*4" # Expected: 14
python calc.py "(2+3)*4" # Expected: 20
python calc.py "8-3-2" # Expected: 3
python calc.py "-2+5" # Expected: 3
python calc.py "2*-3" # Expected: -6
# D2 — true division + EvalError on zero
python calc.py "7/2" # Expected: 3.5
python calc.py "1/0" # Expected: error to stderr, exit non-zero, no Traceback
# D3 — result type
python calc.py "4/2" # Expected: 2 (int, no trailing .0)
python calc.py "7/2" # Expected: 3.5
# D4 — CLI
python calc.py "2+3*4" # Expected stdout: 14, exit 0
python calc.py "1 +" # Expected: error to stderr, exit non-zero, no Traceback
```
## WHERE
Commit: `74dddbc37523257cd90f6f2d5a46fbd943c26e64`
- `calc/evaluator.py` — evaluator + EvalError
- `calc/test_evaluator.py` — unittest suite (15 tests)
- `calc.py` — CLI entry point
## DONE

View File

@ -0,0 +1,55 @@
# STATUS-lex
## DONE
## Claimed gates: D1, D2, D3, D4
**Commit:** bb84bf1
**Files:** `calc/lexer.py`, `calc/test_lexer.py`, `calc/__init__.py`
---
## Verify commands (exact, run from repo root)
```bash
# D4 — tests green
python -m unittest -q
# D1+D2 — complex expression with float, paren, operators
python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"
# D3 — invalid character raises LexError
python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"
```
---
## Expected results
### `python -m unittest -q`
```
..............
----------------------------------------------------------------------
Ran 14 tests in 0.000s
OK
```
### `tokenize('3.5*(1-2)')`
```
[('NUMBER', 3.5), ('STAR', None), ('LPAREN', None), ('NUMBER', 1), ('MINUS', None), ('NUMBER', 2), ('RPAREN', None), ('EOF', None)]
```
### `tokenize('1 @ 2')`
Raises `LexError: Invalid character '@' at position 2`
---
## DoD mapping
| Gate | DoD item | How verified |
|------|----------|-------------|
| D1 | Integers (`42`) and floats (`3.14`, `.5`, `10.`) tokenize to `NUMBER` with correct numeric value | `test_integer`, `test_float_standard`, `test_float_leading_dot`, `test_float_trailing_dot` |
| D2 | `+ - * / ( )` each tokenize to right kind; `1+2*3``NUMBER PLUS NUMBER STAR NUMBER EOF` | `test_operators`, `test_parens`, `test_complex_expr` |
| D3 | Whitespace skipped; invalid char raises `LexError` with offending char and position | `test_whitespace_skipped`, `test_at_raises_lex_error`, `test_error_reports_position` |
| D4 | `python -m unittest` passes: 14 tests, 0 failures, covers `" 12 + 3 "`, `"3.5*(1-2)"`, `"1 @ 2"` raises `LexError` | All tests in `calc/test_lexer.py` |

View File

@ -0,0 +1,94 @@
# STATUS-parse
## DONE
## Claimed gates: D1, D2, D3, D4, D5, D6
**Commit:** (see git log — latest push on main)
**Files:** `calc/parser.py`, `calc/test_parser.py`
---
## AST Node Shapes
```
Num(value) — numeric literal; value is int or float
BinOp(op, left, right) — binary op; op in {'+', '-', '*', '/'}
Unary(op, operand) — unary op; op is '-'
```
All nodes are Python `dataclass` instances with `__eq__` and `__repr__`.
---
## Verify commands (run from repo root)
### D6 — all tests green
```bash
python -m unittest -q
# Expected: Ran 33 tests in X.XXXs OK (14 lex + 19 parser)
```
### D1 — `*` binds tighter than `+`
```bash
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('1+2*3')))"
# Expected: BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
```
### D2 — left associativity
```bash
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8-3-2')))"
# Expected: BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('8/4/2')))"
# Expected: BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))
```
### D3 — parentheses override precedence
```bash
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('(1+2)*3')))"
# Expected: BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
```
### D4 — unary minus
```bash
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-5')))"
# Expected: Unary('-', Num(5))
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('-(1+2)')))"
# Expected: Unary('-', BinOp('+', Num(1), Num(2)))
python -c "from calc.lexer import tokenize; from calc.parser import parse; print(parse(tokenize('3 * -2')))"
# Expected: BinOp('*', Num(3), Unary('-', Num(2)))
```
### D5 — errors raise ParseError
```bash
python -c "
from calc.lexer import tokenize
from calc.parser import parse, ParseError
cases = ['1 +', '(1', '1 2', ')(', '']
for src in cases:
try:
parse(tokenize(src))
print(f'FAIL {src!r}: no error raised')
except ParseError as e:
print(f'OK {src!r}: ParseError')
except Exception as e:
print(f'FAIL {src!r}: wrong exception {type(e).__name__}')
"
# Expected: OK for all 5 cases
```
---
## DoD mapping
| Gate | DoD item | How verified |
|------|----------|-------------|
| D1 | `*`/`/` bind tighter than `+`/`-` | `1+2*3``BinOp('+', Num(1), BinOp('*', ...))` |
| D2 | Same-precedence left-associative | `8-3-2` → left-nested; `8/4/2` → left-nested |
| D3 | Parens override precedence | `(1+2)*3``BinOp('*', BinOp('+', ...), ...)` |
| D4 | Unary minus (leading, nested, in mul) | `-5`, `-(1+2)`, `3 * -2` all parsed as Unary |
| D5 | Malformed input raises ParseError | All 5 cases raise ParseError, not other exceptions |
| D6 | 0 failures in `python -m unittest` | 33 tests OK (14 lex + 19 parser) |