artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
8
calculators/builder-solo/run-02/GIT-LOG.txt
Normal file
8
calculators/builder-solo/run-02/GIT-LOG.txt
Normal file
@ -0,0 +1,8 @@
|
||||
# git history (claim/review handshake), from the run's shared bare repo
|
||||
5ae4f50 status: record eval phase STATUS and JOURNAL with all DoD gates PASS
|
||||
f083f90 feat: implement evaluator, CLI, and evaluator tests (eval phase)
|
||||
cc1dfad status: record parse phase STATUS and JOURNAL with all DoD gates PASS
|
||||
14d6662 feat: implement recursive-descent parser with AST and ParseError
|
||||
a0eec13 status: record lex phase STATUS and JOURNAL with all DoD gates PASS
|
||||
7ac5cda feat: implement lexer with tokenize() for arithmetic expressions
|
||||
ab8a1b9 seed
|
||||
1
calculators/builder-solo/run-02/README.md
Normal file
1
calculators/builder-solo/run-02/README.md
Normal file
@ -0,0 +1 @@
|
||||
# calc
|
||||
1
calculators/builder-solo/run-02/SOURCE.txt
Normal file
1
calculators/builder-solo/run-02/SOURCE.txt
Normal file
@ -0,0 +1 @@
|
||||
original path: /tmp/ao-solo-ssWwR6/r2
|
||||
28
calculators/builder-solo/run-02/calc.py
Normal file
28
calculators/builder-solo/run-02/calc.py
Normal file
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
"""calc CLI — evaluate an arithmetic expression given as a single argument."""
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("usage: calc.py <expression>", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
expr = sys.argv[1]
|
||||
try:
|
||||
from calc.lexer import tokenize, LexError
|
||||
from calc.parser import parse, ParseError
|
||||
from calc.evaluator import evaluate, EvalError
|
||||
|
||||
tokens = tokenize(expr)
|
||||
ast = parse(tokens)
|
||||
result = evaluate(ast)
|
||||
print(result)
|
||||
except (LexError, ParseError, EvalError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
0
calculators/builder-solo/run-02/calc/__init__.py
Normal file
0
calculators/builder-solo/run-02/calc/__init__.py
Normal file
41
calculators/builder-solo/run-02/calc/evaluator.py
Normal file
41
calculators/builder-solo/run-02/calc/evaluator.py
Normal file
@ -0,0 +1,41 @@
|
||||
"""Evaluator for the arithmetic AST produced by calc.parser.
|
||||
|
||||
evaluate(node) -> int | float
|
||||
|
||||
Result-type rule: if the result is a whole number (no fractional part),
|
||||
return an int; otherwise return a float. This means 4/2 → 2 (int) and
|
||||
7/2 → 3.5 (float).
|
||||
"""
|
||||
|
||||
from calc.parser import Num, BinOp, Unary, Node
|
||||
|
||||
|
||||
class EvalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def evaluate(node: Node) -> "int | float":
|
||||
if isinstance(node, Num):
|
||||
return node.value
|
||||
if isinstance(node, Unary):
|
||||
return -evaluate(node.operand)
|
||||
if isinstance(node, BinOp):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
op = node.op
|
||||
if op == '+':
|
||||
result = left + right
|
||||
elif op == '-':
|
||||
result = left - right
|
||||
elif op == '*':
|
||||
result = left * right
|
||||
elif op == '/':
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
result = left / right
|
||||
else:
|
||||
raise EvalError(f"unknown operator: {op!r}")
|
||||
if isinstance(result, float) and result.is_integer():
|
||||
return int(result)
|
||||
return result
|
||||
raise EvalError(f"unknown node type: {type(node).__name__}")
|
||||
49
calculators/builder-solo/run-02/calc/lexer.py
Normal file
49
calculators/builder-solo/run-02/calc/lexer.py
Normal file
@ -0,0 +1,49 @@
|
||||
"""Lexer for arithmetic expressions."""
|
||||
|
||||
from typing import NamedTuple, Union
|
||||
|
||||
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Token(NamedTuple):
|
||||
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 == '.':
|
||||
j = i
|
||||
has_dot = False
|
||||
while j < len(src) and (src[j].isdigit() or (src[j] == '.' and not has_dot)):
|
||||
if src[j] == '.':
|
||||
has_dot = True
|
||||
j += 1
|
||||
raw = src[i:j]
|
||||
value = float(raw) if has_dot else int(raw)
|
||||
tokens.append(Token('NUMBER', value))
|
||||
i = j
|
||||
else:
|
||||
raise LexError(f"unexpected character {ch!r} at position {i}")
|
||||
tokens.append(Token('EOF', None))
|
||||
return tokens
|
||||
147
calculators/builder-solo/run-02/calc/parser.py
Normal file
147
calculators/builder-solo/run-02/calc/parser.py
Normal file
@ -0,0 +1,147 @@
|
||||
"""Recursive-descent parser for arithmetic expressions.
|
||||
|
||||
AST node shapes (stable contract for the eval phase):
|
||||
Num(value) — numeric literal; value is int or float
|
||||
BinOp(op, left, right) — binary operation; op in ('+', '-', '*', '/')
|
||||
Unary(op, operand) — unary operation; op == '-'
|
||||
|
||||
Grammar (encodes precedence and left-associativity):
|
||||
expr → term (('+' | '-') term)*
|
||||
term → unary (('*' | '/') unary)*
|
||||
unary → '-' unary | primary
|
||||
primary → NUMBER | '(' expr ')'
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import Union
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Num:
|
||||
__slots__ = ("value",)
|
||||
|
||||
def __init__(self, value: Union[int, float]) -> None:
|
||||
self.value = value
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Num({self.value!r})"
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
return isinstance(other, Num) and self.value == other.value
|
||||
|
||||
|
||||
class BinOp:
|
||||
__slots__ = ("op", "left", "right")
|
||||
|
||||
def __init__(self, op: str, left: "Node", right: "Node") -> None:
|
||||
self.op = op
|
||||
self.left = left
|
||||
self.right = right
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
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: "Node") -> None:
|
||||
self.op = op
|
||||
self.operand = operand
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Unary({self.op!r}, {self.operand!r})"
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
return (
|
||||
isinstance(other, Unary)
|
||||
and self.op == other.op
|
||||
and self.operand == other.operand
|
||||
)
|
||||
|
||||
|
||||
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}, got {tok.kind!r} ({tok.value!r})"
|
||||
)
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def parse(self) -> Node:
|
||||
if self._peek().kind == "EOF":
|
||||
raise ParseError("empty expression")
|
||||
node = self._expr()
|
||||
if self._peek().kind != "EOF":
|
||||
tok = self._peek()
|
||||
raise ParseError(
|
||||
f"unexpected token {tok.kind!r} ({tok.value!r}) after expression"
|
||||
)
|
||||
return node
|
||||
|
||||
def _expr(self) -> Node:
|
||||
node = self._term()
|
||||
while self._peek().kind in ("PLUS", "MINUS"):
|
||||
op = self._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("LPAREN")
|
||||
node = self._expr()
|
||||
if self._peek().kind != "RPAREN":
|
||||
raise ParseError("unclosed parenthesis — expected ')'")
|
||||
self._consume("RPAREN")
|
||||
return node
|
||||
if tok.kind == "EOF":
|
||||
raise ParseError("unexpected end of expression")
|
||||
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")
|
||||
|
||||
|
||||
def parse(tokens: list) -> Node:
|
||||
"""Parse a token list produced by calc.lexer.tokenize into an AST."""
|
||||
return _Parser(tokens).parse()
|
||||
99
calculators/builder-solo/run-02/calc/test_evaluator.py
Normal file
99
calculators/builder-solo/run-02/calc/test_evaluator.py
Normal file
@ -0,0 +1,99 @@
|
||||
"""Tests for calc.evaluator — covers D1, D2, D3, and a CLI smoke test (D4)."""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse
|
||||
from calc.evaluator import evaluate, EvalError
|
||||
|
||||
|
||||
def calc(expr):
|
||||
return evaluate(parse(tokenize(expr)))
|
||||
|
||||
|
||||
class TestArithmetic(unittest.TestCase):
|
||||
"""D1 — + - * /, precedence, parens, unary minus."""
|
||||
|
||||
def test_addition(self):
|
||||
self.assertEqual(calc("1+2"), 3)
|
||||
|
||||
def test_multiplication_precedence(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_leading(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_minus_in_expression(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
|
||||
class TestDivision(unittest.TestCase):
|
||||
"""D2 — true division and EvalError on div-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_not_bare_exception(self):
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError escaped — should have been EvalError")
|
||||
|
||||
|
||||
class TestResultType(unittest.TestCase):
|
||||
"""D3 — whole-valued floats return int, non-whole return float."""
|
||||
|
||||
def test_integer_division_returns_int(self):
|
||||
result = calc("4/2")
|
||||
self.assertEqual(result, 2)
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
def test_non_integer_division_returns_float(self):
|
||||
result = calc("7/2")
|
||||
self.assertEqual(result, 3.5)
|
||||
self.assertIsInstance(result, float)
|
||||
|
||||
def test_int_literal_stays_int(self):
|
||||
result = calc("6")
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
|
||||
class TestCLI(unittest.TestCase):
|
||||
"""D4 — CLI smoke tests."""
|
||||
|
||||
def _run(self, expr):
|
||||
return subprocess.run(
|
||||
[sys.executable, "calc.py", expr],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=__file__.rsplit("/calc/", 1)[0],
|
||||
)
|
||||
|
||||
def test_cli_valid_expression(self):
|
||||
r = self._run("2+3*4")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout.strip(), "14")
|
||||
|
||||
def test_cli_invalid_expression_stderr_nonzero(self):
|
||||
r = self._run("1 +")
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertGreater(len(r.stderr.strip()), 0)
|
||||
self.assertEqual(r.stdout.strip(), "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
89
calculators/builder-solo/run-02/calc/test_lexer.py
Normal file
89
calculators/builder-solo/run-02/calc/test_lexer.py
Normal file
@ -0,0 +1,89 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize, Token, LexError
|
||||
|
||||
|
||||
def kinds(tokens):
|
||||
return [t.kind for t in tokens]
|
||||
|
||||
|
||||
def vals(tokens):
|
||||
return [t.value for t in tokens]
|
||||
|
||||
|
||||
class TestNumbers(unittest.TestCase):
|
||||
def test_integer(self):
|
||||
toks = tokenize("42")
|
||||
self.assertEqual(kinds(toks), ['NUMBER', 'EOF'])
|
||||
self.assertEqual(toks[0].value, 42)
|
||||
self.assertIsInstance(toks[0].value, int)
|
||||
|
||||
def test_float(self):
|
||||
toks = tokenize("3.14")
|
||||
self.assertEqual(kinds(toks), ['NUMBER', 'EOF'])
|
||||
self.assertAlmostEqual(toks[0].value, 3.14)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
def test_float_leading_dot(self):
|
||||
toks = tokenize(".5")
|
||||
self.assertEqual(kinds(toks), ['NUMBER', 'EOF'])
|
||||
self.assertAlmostEqual(toks[0].value, 0.5)
|
||||
|
||||
def test_float_trailing_dot(self):
|
||||
toks = tokenize("10.")
|
||||
self.assertEqual(kinds(toks), ['NUMBER', 'EOF'])
|
||||
self.assertAlmostEqual(toks[0].value, 10.0)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_operators(self):
|
||||
toks = tokenize("1+2*3")
|
||||
self.assertEqual(kinds(toks), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_all_operators(self):
|
||||
toks = tokenize("+-*/")
|
||||
self.assertEqual(kinds(toks), ['PLUS', 'MINUS', 'STAR', 'SLASH', 'EOF'])
|
||||
|
||||
def test_parens(self):
|
||||
toks = tokenize("()")
|
||||
self.assertEqual(kinds(toks), ['LPAREN', 'RPAREN', 'EOF'])
|
||||
|
||||
def test_complex_expr(self):
|
||||
toks = tokenize("3.5*(1-2)")
|
||||
self.assertEqual(kinds(toks), ['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)
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def test_whitespace_skipped(self):
|
||||
toks = tokenize(" 12 + 3 ")
|
||||
self.assertEqual(kinds(toks), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
self.assertEqual(toks[0].value, 12)
|
||||
self.assertEqual(toks[2].value, 3)
|
||||
|
||||
def test_tab_skipped(self):
|
||||
toks = tokenize("1\t+\t2")
|
||||
self.assertEqual(kinds(toks), ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_invalid_at_raises(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('@', str(ctx.exception))
|
||||
|
||||
def test_invalid_dollar_raises(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$")
|
||||
|
||||
def test_invalid_letter_raises(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("x")
|
||||
|
||||
def test_invalid_position_in_message(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('2', str(ctx.exception)) # position 2
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
164
calculators/builder-solo/run-02/calc/test_parser.py
Normal file
164
calculators/builder-solo/run-02/calc/test_parser.py
Normal file
@ -0,0 +1,164 @@
|
||||
"""Tests for calc.parser — asserts on AST structure, not evaluation."""
|
||||
|
||||
import unittest
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError, Num, BinOp, Unary
|
||||
|
||||
|
||||
def p(src: str):
|
||||
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+1 → BinOp('+', BinOp('*', Num(2), Num(3)), Num(1))
|
||||
self.assertEqual(
|
||||
p("2*3+1"),
|
||||
BinOp("+", BinOp("*", Num(2), Num(3)), Num(1)),
|
||||
)
|
||||
|
||||
def test_sub_then_div(self):
|
||||
# 10-6/3 → BinOp('-', Num(10), BinOp('/', Num(6), Num(3)))
|
||||
self.assertEqual(
|
||||
p("10-6/3"),
|
||||
BinOp("-", Num(10), BinOp("/", Num(6), Num(3))),
|
||||
)
|
||||
|
||||
def test_mul_and_div_same_precedence_left(self):
|
||||
# 4*3/2 → BinOp('/', BinOp('*', Num(4), Num(3)), Num(2))
|
||||
self.assertEqual(
|
||||
p("4*3/2"),
|
||||
BinOp("/", BinOp("*", Num(4), Num(3)), Num(2)),
|
||||
)
|
||||
|
||||
|
||||
class TestAssociativity(unittest.TestCase):
|
||||
"""D2 — same-precedence operators associate left."""
|
||||
|
||||
def test_sub_left_assoc(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_left_assoc(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_left_assoc(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_left_assoc(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_force_add_under_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):
|
||||
# ((2+3)) → BinOp('+', Num(2), Num(3))
|
||||
self.assertEqual(p("((2+3))"), BinOp("+", Num(2), Num(3)))
|
||||
|
||||
def test_parens_right_side(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))),
|
||||
)
|
||||
|
||||
|
||||
class TestUnaryMinus(unittest.TestCase):
|
||||
"""D4 — leading and nested unary minus."""
|
||||
|
||||
def test_leading_unary(self):
|
||||
# -5 → Unary('-', Num(5))
|
||||
self.assertEqual(p("-5"), Unary("-", Num(5)))
|
||||
|
||||
def test_unary_in_parens(self):
|
||||
# -(1+2) → Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
self.assertEqual(
|
||||
p("-(1+2)"),
|
||||
Unary("-", BinOp("+", Num(1), Num(2))),
|
||||
)
|
||||
|
||||
def test_unary_right_operand(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_addition(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_operator(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("1 +")
|
||||
|
||||
def test_unclosed_paren(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("(1")
|
||||
|
||||
def test_two_numbers_no_op(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_mismatched_parens_extra_close(self):
|
||||
with self.assertRaises(ParseError):
|
||||
p("(1+2))")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
47
calculators/builder-solo/run-02/machine-docs/JOURNAL-eval.md
Normal file
47
calculators/builder-solo/run-02/machine-docs/JOURNAL-eval.md
Normal file
@ -0,0 +1,47 @@
|
||||
# JOURNAL — eval phase
|
||||
|
||||
## Build
|
||||
|
||||
1. Read `calc/parser.py` and `calc/lexer.py` to understand AST node contracts
|
||||
(`Num`, `BinOp`, `Unary`) and `Token`/`ParseError` types.
|
||||
|
||||
2. Wrote `calc/evaluator.py`:
|
||||
- `EvalError(Exception)` wraps all evaluation failures.
|
||||
- `evaluate(node)` walks the AST recursively.
|
||||
- Division by zero raises `EvalError("division by zero")`.
|
||||
- Result-type rule: `float.is_integer()` → cast to `int`; otherwise keep `float`.
|
||||
|
||||
3. Wrote `calc.py` (top-level CLI):
|
||||
- Accepts exactly one argument (the expression string).
|
||||
- Chains `tokenize → parse → evaluate`, prints result.
|
||||
- Catches `LexError | ParseError | EvalError`, prints `error: <msg>` to stderr, exits 1.
|
||||
- No traceback surfaces.
|
||||
|
||||
4. Wrote `calc/test_evaluator.py` (unittest):
|
||||
- `TestArithmetic` — D1: +, -, *, /, precedence, parens, unary minus.
|
||||
- `TestDivision` — D2: true division, `EvalError` on /0, confirms no bare `ZeroDivisionError`.
|
||||
- `TestResultType` — D3: `4/2 → int(2)`, `7/2 → float(3.5)`.
|
||||
- `TestCLI` — D4: subprocess smoke tests for valid and invalid CLI invocations.
|
||||
|
||||
## Verification
|
||||
|
||||
All plan Verify commands run from a clean working directory:
|
||||
|
||||
```
|
||||
python -m unittest -q → Ran 51 tests, OK
|
||||
python calc.py "2+3*4" → 14 (exit 0)
|
||||
python calc.py "(2+3)*4" → 20 (exit 0)
|
||||
python calc.py "7/2" → 3.5 (exit 0)
|
||||
python calc.py "4/2" → 2 (exit 0, no trailing .0)
|
||||
python calc.py "1/0" → error: division by zero (exit 1, stderr)
|
||||
python calc.py "1 +" → error: unexpected end of expression (exit 1, stderr)
|
||||
```
|
||||
|
||||
Additional D1 edge cases verified:
|
||||
```
|
||||
python calc.py "8-3-2" → 3
|
||||
python calc.py "-2+5" → 3
|
||||
python calc.py "2*-3" → -6
|
||||
```
|
||||
|
||||
All DoD gates confirmed PASS. Committed as f083f901.
|
||||
21
calculators/builder-solo/run-02/machine-docs/JOURNAL-lex.md
Normal file
21
calculators/builder-solo/run-02/machine-docs/JOURNAL-lex.md
Normal file
@ -0,0 +1,21 @@
|
||||
# JOURNAL-lex
|
||||
|
||||
## 2026-06-15
|
||||
|
||||
### Build
|
||||
- Created `calc/__init__.py` (empty package marker)
|
||||
- Created `calc/lexer.py`: `Token` (NamedTuple with `kind` and `value`), `LexError`, `tokenize(src)`
|
||||
- Handles integers (int), floats (float, including `.5` and `10.` edge cases)
|
||||
- Single-char operators: `+ - * / ( )`
|
||||
- Whitespace (space, tab) skipped
|
||||
- Invalid chars raise `LexError` with char repr and position
|
||||
- Appends `EOF` token at end
|
||||
- Created `calc/test_lexer.py`: 14 unittest cases covering D1–D3
|
||||
|
||||
### Verification
|
||||
- `python -m unittest -q` → 14 tests, 0 failures — PASS
|
||||
- `tokenize('3.5*(1-2)')` → correct 8-token sequence — PASS
|
||||
- `tokenize('1 @ 2')` → raises `LexError: unexpected character '@' at position 2` — PASS
|
||||
|
||||
### Commit
|
||||
`7ac5cdaded6af3b635d6d638f9c20082b5648393`
|
||||
@ -0,0 +1,28 @@
|
||||
# JOURNAL-parse
|
||||
|
||||
## Session 1
|
||||
|
||||
**Read plan** — phase `parse` requires `calc/parser.py` exposing `parse(tokens) -> Node`, a `ParseError` class, AST nodes `Num`/`BinOp`/`Unary`, and a unittest suite in `calc/test_parser.py`.
|
||||
|
||||
**Inspected lex phase** — `calc/lexer.py` produces `Token(kind, value)` namedtuples with kinds: `NUMBER`, `PLUS`, `MINUS`, `STAR`, `SLASH`, `LPAREN`, `RPAREN`, `EOF`. STATUS-lex confirms all lex gates PASS.
|
||||
|
||||
**Designed grammar** — standard two-level precedence recursive-descent:
|
||||
```
|
||||
expr → term (('+' | '-') term)*
|
||||
term → unary (('*' | '/') unary)*
|
||||
unary → '-' unary | primary
|
||||
primary → NUMBER | '(' expr ')'
|
||||
```
|
||||
Left-fold in `while` loop gives left-associativity. `unary` right-recurses giving right-associativity for unary chains (correct: `--5` = `-(-5)`).
|
||||
|
||||
**Implemented** `calc/parser.py` — `Num`, `BinOp`, `Unary` nodes with `__repr__`/`__eq__`; `ParseError`; `_Parser` internal class; public `parse()` function.
|
||||
|
||||
**Wrote tests** `calc/test_parser.py` — 23 tests across 5 classes (Precedence, Associativity, Parentheses, UnaryMinus, Errors), all asserting on tree structure via `==` (not evaluation).
|
||||
|
||||
**Ran full suite** — 37 tests (14 lex + 23 parser), 0 failures.
|
||||
|
||||
**Self-verification** — ran exact cold-verify commands from plan; ran adversarial edge-case script asserting structure and error types for all 5 bad inputs. All pass.
|
||||
|
||||
**Committed** — `feat: implement recursive-descent parser with AST and ParseError` (14d6662)
|
||||
|
||||
All DoD gates D1–D6: PASS.
|
||||
37
calculators/builder-solo/run-02/machine-docs/STATUS-eval.md
Normal file
37
calculators/builder-solo/run-02/machine-docs/STATUS-eval.md
Normal file
@ -0,0 +1,37 @@
|
||||
# STATUS — eval phase
|
||||
|
||||
Commit: f083f901cdfdf6ba6614a95171506efd917b31a4
|
||||
|
||||
## Gate Results
|
||||
|
||||
### D1 — arithmetic (precedence, parens, unary minus)
|
||||
- Command: `python calc.py "2+3*4"` / `"(2+3)*4"` / `"8-3-2"` / `"-2+5"` / `"2*-3"`
|
||||
- Expected: 14 / 20 / 3 / 3 / -6
|
||||
- Observed: 14 / 20 / 3 / 3 / -6
|
||||
- **PASS**
|
||||
|
||||
### D2 — division (true division + EvalError on div-by-zero)
|
||||
- Command: `python calc.py "7/2"` → 3.5; `python calc.py "1/0"` → stderr + exit 1
|
||||
- Expected: 3.5; error: division by zero, exit 1
|
||||
- Observed: 3.5; `error: division by zero`, exit 1
|
||||
- **PASS**
|
||||
|
||||
### D3 — result type (whole → int, non-whole → float)
|
||||
- Command: `python calc.py "4/2"` → `2`; `python calc.py "7/2"` → `3.5`
|
||||
- Expected: `2` (no `.0`); `3.5`
|
||||
- Observed: `2`; `3.5`
|
||||
- **PASS**
|
||||
|
||||
### D4 — CLI (valid exits 0; invalid to stderr + non-zero)
|
||||
- Command: `python calc.py "2+3*4"` → `14`, exit 0; `python calc.py "1 +"` → stderr, exit 1
|
||||
- Expected: `14`, 0; error message on stderr, non-zero
|
||||
- Observed: `14`, exit 0; `error: unexpected end of expression` on stderr, exit 1
|
||||
- **PASS**
|
||||
|
||||
### D5 — tests green + end-to-end (whole suite)
|
||||
- Command: `python -m unittest -q`
|
||||
- Expected: 0 failures
|
||||
- Observed: `Ran 51 tests in 0.065s` / `OK`
|
||||
- **PASS**
|
||||
|
||||
## DONE
|
||||
55
calculators/builder-solo/run-02/machine-docs/STATUS-lex.md
Normal file
55
calculators/builder-solo/run-02/machine-docs/STATUS-lex.md
Normal file
@ -0,0 +1,55 @@
|
||||
# STATUS-lex
|
||||
|
||||
Commit: 7ac5cdaded6af3b635d6d638f9c20082b5648393
|
||||
|
||||
## Gate Verification
|
||||
|
||||
### D1 — numbers
|
||||
**What:** Integers and floats tokenize to NUMBER with correct value type (int/float). EOF appended.
|
||||
**Command:** `python -m unittest calc.test_lexer.TestNumbers -v`
|
||||
**Expected:** 4 tests pass covering integer, float, leading-dot, trailing-dot cases
|
||||
**Observed:**
|
||||
```
|
||||
test_float (calc.test_lexer.TestNumbers.test_float) ... ok
|
||||
test_float_leading_dot (calc.test_lexer.TestNumbers.test_float_leading_dot) ... ok
|
||||
test_float_trailing_dot (calc.test_lexer.TestNumbers.test_float_trailing_dot) ... ok
|
||||
test_integer (calc.test_lexer.TestNumbers.test_integer) ... ok
|
||||
```
|
||||
Result: **PASS**
|
||||
|
||||
### D2 — operators & parens
|
||||
**What:** `+ - * / ( )` tokenize to PLUS MINUS STAR SLASH LPAREN RPAREN; `1+2*3` yields NUMBER PLUS NUMBER STAR NUMBER EOF.
|
||||
**Command:** `python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('3.5*(1-2)')])"`
|
||||
**Expected:** `[('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]`
|
||||
**Observed:**
|
||||
```
|
||||
[('NUMBER', 3.5), ('STAR', '*'), ('LPAREN', '('), ('NUMBER', 1), ('MINUS', '-'), ('NUMBER', 2), ('RPAREN', ')'), ('EOF', None)]
|
||||
```
|
||||
Result: **PASS**
|
||||
|
||||
### D3 — whitespace & errors
|
||||
**What:** Spaces/tabs between tokens are skipped; invalid chars raise LexError with char and position.
|
||||
**Command 1:** `python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"` → must raise LexError
|
||||
**Observed:**
|
||||
```
|
||||
calc.lexer.LexError: unexpected character '@' at position 2
|
||||
```
|
||||
Result: **PASS**
|
||||
|
||||
**Command 2:** `python -m unittest calc.test_lexer.TestWhitespaceAndErrors -v`
|
||||
**Observed:** 6 tests pass (whitespace_skipped, tab_skipped, invalid_at_raises, invalid_dollar_raises, invalid_letter_raises, invalid_position_in_message)
|
||||
Result: **PASS**
|
||||
|
||||
### D4 — tests green
|
||||
**What:** `python -m unittest -q` passes with 0 failures covering D1–D3 including `" 12 + 3 "`, `"3.5*(1-2)"`, `"1 @ 2"` raising LexError.
|
||||
**Command:** `python -m unittest -q`
|
||||
**Expected:** Ran N tests in X.XXXs / OK
|
||||
**Observed:**
|
||||
```
|
||||
Ran 14 tests in 0.000s
|
||||
|
||||
OK
|
||||
```
|
||||
Result: **PASS**
|
||||
|
||||
## DONE
|
||||
83
calculators/builder-solo/run-02/machine-docs/STATUS-parse.md
Normal file
83
calculators/builder-solo/run-02/machine-docs/STATUS-parse.md
Normal file
@ -0,0 +1,83 @@
|
||||
# STATUS-parse
|
||||
|
||||
Commit: 14d6662
|
||||
|
||||
## AST Shape (contract for eval phase)
|
||||
|
||||
```
|
||||
Num(value) — numeric literal; value is int or float
|
||||
BinOp(op, left, right) — binary operation; op in ('+', '-', '*', '/')
|
||||
Unary(op, operand) — unary minus; op == '-'
|
||||
```
|
||||
|
||||
All nodes support `__repr__` and `__eq__`. Import from `calc.parser`.
|
||||
|
||||
## Gate Verification
|
||||
|
||||
### D1 — precedence
|
||||
**What:** `*` and `/` bind tighter than `+` and `-`
|
||||
**Command:** `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)))`
|
||||
**Observed:**
|
||||
```
|
||||
BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
```
|
||||
Result: **PASS**
|
||||
|
||||
### D2 — left associativity
|
||||
**What:** Same-precedence operators fold left: `8-3-2` → `(8-3)-2`; `8/4/2` → `(8/4)/2`
|
||||
**Command:**
|
||||
```python
|
||||
str(parse(tokenize('8-3-2'))) == "BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))"
|
||||
str(parse(tokenize('8/4/2'))) == "BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))"
|
||||
```
|
||||
**Observed:** Both assertions pass (confirmed via edge-case script)
|
||||
Result: **PASS**
|
||||
|
||||
### D3 — parentheses
|
||||
**What:** `(1+2)*3` places `+` under `*`
|
||||
**Command:**
|
||||
```python
|
||||
str(parse(tokenize('(1+2)*3'))) == "BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))"
|
||||
```
|
||||
**Observed:** Assertion passes (confirmed via edge-case script)
|
||||
Result: **PASS**
|
||||
|
||||
### D4 — unary minus
|
||||
**What:** `-5`, `-(1+2)`, `3 * -2` all parse correctly
|
||||
**Commands:**
|
||||
```python
|
||||
str(parse(tokenize('-5'))) == "Unary('-', Num(5))"
|
||||
str(parse(tokenize('-(1+2)'))) == "Unary('-', BinOp('+', Num(1), Num(2)))"
|
||||
str(parse(tokenize('3 * -2'))) == "BinOp('*', Num(3), Unary('-', Num(2)))"
|
||||
```
|
||||
**Observed:** All three assertions pass (confirmed via edge-case script)
|
||||
Result: **PASS**
|
||||
|
||||
### D5 — errors
|
||||
**What:** `"1 +"`, `"(1"`, `"1 2"`, `")("`, `""` each raise `ParseError` (not any other exception)
|
||||
**Command:**
|
||||
```python
|
||||
for bad in ['1 +', '(1', '1 2', ')(', '']:
|
||||
try:
|
||||
parse(tokenize(bad)); raise AssertionError(...)
|
||||
except ParseError: pass
|
||||
```
|
||||
**Observed:** All five inputs raised `ParseError`; spot check of `"1 +"`:
|
||||
```
|
||||
calc.parser.ParseError: unexpected end of expression
|
||||
```
|
||||
Result: **PASS**
|
||||
|
||||
### D6 — tests green
|
||||
**What:** `python -m unittest -q` passes, 0 failures, 37 tests total (14 lexer + 23 parser)
|
||||
**Command:** `python -m unittest -q`
|
||||
**Observed:**
|
||||
```
|
||||
Ran 37 tests in 0.001s
|
||||
|
||||
OK
|
||||
```
|
||||
Result: **PASS**
|
||||
|
||||
## DONE
|
||||
Reference in New Issue
Block a user