artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
1
calculators/builder-solo/run-04/.gitignore
vendored
Normal file
1
calculators/builder-solo/run-04/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
__pycache__/
|
||||
6
calculators/builder-solo/run-04/GIT-LOG.txt
Normal file
6
calculators/builder-solo/run-04/GIT-LOG.txt
Normal file
@ -0,0 +1,6 @@
|
||||
# git history (claim/review handshake), from the run's shared bare repo
|
||||
daf298f feat: add evaluator, CLI, and test suite — all eval-phase gates pass (D1-D5)
|
||||
fb6d551 feat: add recursive-descent parser with AST nodes and unittest suite
|
||||
0065976 status: lex phase DONE — all D1-D4 gates pass
|
||||
c37b70f feat: add calc lexer with tokenize function and unittest suite
|
||||
b6a59dc seed
|
||||
1
calculators/builder-solo/run-04/README.md
Normal file
1
calculators/builder-solo/run-04/README.md
Normal file
@ -0,0 +1 @@
|
||||
# calc
|
||||
1
calculators/builder-solo/run-04/SOURCE.txt
Normal file
1
calculators/builder-solo/run-04/SOURCE.txt
Normal file
@ -0,0 +1 @@
|
||||
original path: /tmp/ao-solo-ssWwR6/r4
|
||||
26
calculators/builder-solo/run-04/calc.py
Normal file
26
calculators/builder-solo/run-04/calc.py
Normal file
@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""calc.py — command-line calculator: python calc.py "<expression>" """
|
||||
|
||||
import sys
|
||||
from calc.lexer import tokenize, LexError
|
||||
from calc.parser import parse, ParseError
|
||||
from calc.evaluator import evaluate, EvalError
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("usage: python calc.py \"<expression>\"", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
expr = sys.argv[1]
|
||||
try:
|
||||
result = evaluate(parse(tokenize(expr)))
|
||||
except (LexError, ParseError, EvalError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print(result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
0
calculators/builder-solo/run-04/calc/__init__.py
Normal file
0
calculators/builder-solo/run-04/calc/__init__.py
Normal file
40
calculators/builder-solo/run-04/calc/evaluator.py
Normal file
40
calculators/builder-solo/run-04/calc/evaluator.py
Normal file
@ -0,0 +1,40 @@
|
||||
"""AST evaluator for calc expressions.
|
||||
|
||||
evaluate(node) -> int | float
|
||||
|
||||
Result-type rule:
|
||||
- Whole-valued results (including float 2.0) are returned/displayed as int.
|
||||
- Non-whole results are returned as float.
|
||||
Division by zero raises EvalError, not a bare ZeroDivisionError.
|
||||
"""
|
||||
|
||||
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):
|
||||
if node.op == "-":
|
||||
return -evaluate(node.operand)
|
||||
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 left + right
|
||||
if node.op == "-":
|
||||
return left - right
|
||||
if node.op == "*":
|
||||
return left * right
|
||||
if node.op == "/":
|
||||
if right == 0:
|
||||
raise EvalError("division by zero")
|
||||
result = left / right
|
||||
return int(result) if result == int(result) else result
|
||||
raise EvalError(f"unknown binary op {node.op!r}")
|
||||
raise EvalError(f"unknown node type {type(node).__name__}")
|
||||
53
calculators/builder-solo/run-04/calc/lexer.py
Normal file
53
calculators/builder-solo/run-04/calc/lexer.py
Normal file
@ -0,0 +1,53 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
class LexError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Token:
|
||||
kind: str
|
||||
value: Union[int, float, str, None]
|
||||
|
||||
|
||||
def tokenize(src: str) -> list:
|
||||
tokens = []
|
||||
i = 0
|
||||
while i < len(src):
|
||||
ch = src[i]
|
||||
if ch in ' \t':
|
||||
i += 1
|
||||
continue
|
||||
if ch == '+':
|
||||
tokens.append(Token('PLUS', '+'))
|
||||
i += 1
|
||||
elif ch == '-':
|
||||
tokens.append(Token('MINUS', '-'))
|
||||
i += 1
|
||||
elif ch == '*':
|
||||
tokens.append(Token('STAR', '*'))
|
||||
i += 1
|
||||
elif ch == '/':
|
||||
tokens.append(Token('SLASH', '/'))
|
||||
i += 1
|
||||
elif ch == '(':
|
||||
tokens.append(Token('LPAREN', '('))
|
||||
i += 1
|
||||
elif ch == ')':
|
||||
tokens.append(Token('RPAREN', ')'))
|
||||
i += 1
|
||||
elif ch.isdigit() or ch == '.':
|
||||
start = i
|
||||
while i < len(src) and (src[i].isdigit() or src[i] == '.'):
|
||||
i += 1
|
||||
raw = src[start:i]
|
||||
if '.' in raw:
|
||||
tokens.append(Token('NUMBER', float(raw)))
|
||||
else:
|
||||
tokens.append(Token('NUMBER', int(raw)))
|
||||
else:
|
||||
raise LexError(f"unexpected character {ch!r} at position {i}")
|
||||
tokens.append(Token('EOF', None))
|
||||
return tokens
|
||||
116
calculators/builder-solo/run-04/calc/parser.py
Normal file
116
calculators/builder-solo/run-04/calc/parser.py
Normal file
@ -0,0 +1,116 @@
|
||||
"""Recursive-descent parser for calc expressions.
|
||||
|
||||
AST node shapes:
|
||||
Num(value) — numeric literal; value is int or float
|
||||
BinOp(op, left, right) — binary op; op is one of '+' '-' '*' '/'
|
||||
Unary(op, operand) — unary op; op is '-'
|
||||
|
||||
All nodes implement __repr__ for easy shape inspection.
|
||||
|
||||
Grammar (lowest → highest precedence):
|
||||
expr : term (('+' | '-') term)*
|
||||
term : unary (('*' | '/') unary)*
|
||||
unary : '-' unary | primary
|
||||
primary : NUMBER | '(' expr ')'
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Num:
|
||||
value: Union[int, float]
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Num({self.value!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
op: str
|
||||
left: "Node"
|
||||
right: "Node"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
op: str
|
||||
operand: "Node"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Unary({self.op!r}, {self.operand!r})"
|
||||
|
||||
|
||||
Node = Union[Num, BinOp, Unary]
|
||||
|
||||
|
||||
def parse(tokens: list) -> Node:
|
||||
"""Parse a token list into an AST. Raises ParseError on malformed input."""
|
||||
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: list) -> None:
|
||||
self._tokens = tokens
|
||||
self._pos = 0
|
||||
|
||||
def current(self):
|
||||
return self._tokens[self._pos]
|
||||
|
||||
def consume(self, kind: str = None):
|
||||
tok = self._tokens[self._pos]
|
||||
if kind is not None and tok.kind != kind:
|
||||
raise ParseError(
|
||||
f"expected {kind!r} but got {tok.kind!r} ({tok.value!r})"
|
||||
)
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def expr(self) -> Node:
|
||||
node = self.term()
|
||||
while self.current().kind in ("PLUS", "MINUS"):
|
||||
op = self.consume().value
|
||||
node = BinOp(op, node, self.term())
|
||||
return node
|
||||
|
||||
def term(self) -> Node:
|
||||
node = self.unary()
|
||||
while self.current().kind in ("STAR", "SLASH"):
|
||||
op = self.consume().value
|
||||
node = BinOp(op, node, self.unary())
|
||||
return node
|
||||
|
||||
def unary(self) -> Node:
|
||||
if self.current().kind == "MINUS":
|
||||
self.consume("MINUS")
|
||||
return Unary("-", self.unary())
|
||||
return self.primary()
|
||||
|
||||
def primary(self) -> Node:
|
||||
tok = self.current()
|
||||
if tok.kind == "NUMBER":
|
||||
self.consume("NUMBER")
|
||||
return Num(tok.value)
|
||||
if tok.kind == "LPAREN":
|
||||
self.consume("LPAREN")
|
||||
node = self.expr()
|
||||
if self.current().kind != "RPAREN":
|
||||
raise ParseError("unclosed '(' — expected ')'")
|
||||
self.consume("RPAREN")
|
||||
return node
|
||||
if tok.kind == "EOF":
|
||||
raise ParseError("unexpected end of input")
|
||||
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")
|
||||
100
calculators/builder-solo/run-04/calc/test_evaluator.py
Normal file
100
calculators/builder-solo/run-04/calc/test_evaluator.py
Normal file
@ -0,0 +1,100 @@
|
||||
"""Tests for calc/evaluator.py — covers D1, D2, D3 gates."""
|
||||
|
||||
import unittest
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse
|
||||
from calc.evaluator import evaluate, EvalError
|
||||
|
||||
|
||||
def calc(s):
|
||||
return evaluate(parse(tokenize(s)))
|
||||
|
||||
|
||||
class TestArithmetic(unittest.TestCase):
|
||||
"""D1 — arithmetic correctness."""
|
||||
|
||||
def test_addition_with_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_associative_subtraction(self):
|
||||
self.assertEqual(calc("8-3-2"), 3)
|
||||
|
||||
def test_unary_minus(self):
|
||||
self.assertEqual(calc("-2+5"), 3)
|
||||
|
||||
def test_unary_minus_before_mul(self):
|
||||
self.assertEqual(calc("2*-3"), -6)
|
||||
|
||||
|
||||
class TestDivision(unittest.TestCase):
|
||||
"""D2 — true division and EvalError on 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_no_bare_zero_division_error(self):
|
||||
try:
|
||||
calc("1/0")
|
||||
except EvalError:
|
||||
pass
|
||||
except ZeroDivisionError:
|
||||
self.fail("ZeroDivisionError escaped the API — must be EvalError")
|
||||
|
||||
|
||||
class TestResultType(unittest.TestCase):
|
||||
"""D3 — whole-valued results as int, non-whole as 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_stays_int(self):
|
||||
result = calc("2+3*4")
|
||||
self.assertIsInstance(result, int)
|
||||
|
||||
|
||||
class TestCLI(unittest.TestCase):
|
||||
"""D4 — CLI exit codes and output."""
|
||||
|
||||
def _run(self, expr):
|
||||
return subprocess.run(
|
||||
[sys.executable, "calc.py", expr],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd="/tmp/ao-solo-ssWwR6/r4/work",
|
||||
)
|
||||
|
||||
def test_valid_expression_exit_zero(self):
|
||||
proc = self._run("2+3*4")
|
||||
self.assertEqual(proc.returncode, 0)
|
||||
self.assertEqual(proc.stdout.strip(), "14")
|
||||
|
||||
def test_invalid_expression_exit_nonzero(self):
|
||||
proc = self._run("1 +")
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertEqual(proc.stdout, "")
|
||||
self.assertGreater(len(proc.stderr.strip()), 0)
|
||||
|
||||
def test_division_by_zero_exit_nonzero(self):
|
||||
proc = self._run("1/0")
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
93
calculators/builder-solo/run-04/calc/test_lexer.py
Normal file
93
calculators/builder-solo/run-04/calc/test_lexer.py
Normal file
@ -0,0 +1,93 @@
|
||||
import unittest
|
||||
from calc.lexer import tokenize, Token, LexError
|
||||
|
||||
|
||||
def kinds(src):
|
||||
return [t.kind for t in tokenize(src)]
|
||||
|
||||
|
||||
def values(src):
|
||||
return [(t.kind, t.value) for t in tokenize(src)]
|
||||
|
||||
|
||||
class TestNumbers(unittest.TestCase):
|
||||
def test_integer(self):
|
||||
toks = tokenize("42")
|
||||
self.assertEqual(len(toks), 2)
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertEqual(toks[0].value, 42)
|
||||
self.assertIsInstance(toks[0].value, int)
|
||||
self.assertEqual(toks[1].kind, 'EOF')
|
||||
|
||||
def test_float(self):
|
||||
toks = tokenize("3.14")
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(toks[0].value, 3.14)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
def test_float_leading_dot(self):
|
||||
toks = tokenize(".5")
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(toks[0].value, 0.5)
|
||||
|
||||
def test_float_trailing_dot(self):
|
||||
toks = tokenize("10.")
|
||||
self.assertEqual(toks[0].kind, 'NUMBER')
|
||||
self.assertAlmostEqual(toks[0].value, 10.0)
|
||||
self.assertIsInstance(toks[0].value, float)
|
||||
|
||||
|
||||
class TestOperatorsAndParens(unittest.TestCase):
|
||||
def test_simple_expression(self):
|
||||
self.assertEqual(kinds("1+2*3"), ['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_minus(self):
|
||||
self.assertIn('MINUS', kinds("1-2"))
|
||||
|
||||
def test_slash(self):
|
||||
self.assertIn('SLASH', kinds("4/2"))
|
||||
|
||||
def test_parens(self):
|
||||
k = kinds("(1)")
|
||||
self.assertEqual(k[0], 'LPAREN')
|
||||
self.assertEqual(k[-2], 'RPAREN')
|
||||
|
||||
def test_complex_expr(self):
|
||||
k = kinds("3.5*(1-2)")
|
||||
self.assertEqual(k, ['NUMBER', 'STAR', 'LPAREN', 'NUMBER', 'MINUS', 'NUMBER', 'RPAREN', 'EOF'])
|
||||
|
||||
|
||||
class TestWhitespaceAndErrors(unittest.TestCase):
|
||||
def test_whitespace_skipped(self):
|
||||
k = kinds(" 12 + 3 ")
|
||||
self.assertEqual(k, ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_tab_whitespace(self):
|
||||
k = kinds("1\t+\t2")
|
||||
self.assertEqual(k, ['NUMBER', 'PLUS', 'NUMBER', 'EOF'])
|
||||
|
||||
def test_lex_error_at_sign(self):
|
||||
with self.assertRaises(LexError) as ctx:
|
||||
tokenize("1 @ 2")
|
||||
self.assertIn('@', str(ctx.exception))
|
||||
|
||||
def test_lex_error_dollar(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("$100")
|
||||
|
||||
def test_lex_error_letter(self):
|
||||
with self.assertRaises(LexError):
|
||||
tokenize("abc")
|
||||
|
||||
def test_lex_error_position_in_message(self):
|
||||
try:
|
||||
tokenize("1 @ 2")
|
||||
self.fail("LexError not raised")
|
||||
except LexError as e:
|
||||
msg = str(e)
|
||||
self.assertIn('@', msg)
|
||||
self.assertIn('2', msg) # position 2
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
120
calculators/builder-solo/run-04/calc/test_parser.py
Normal file
120
calculators/builder-solo/run-04/calc/test_parser.py
Normal file
@ -0,0 +1,120 @@
|
||||
"""Tests for calc/parser.py covering DoD gates D1–D5."""
|
||||
import unittest
|
||||
|
||||
from calc.lexer import tokenize
|
||||
from calc.parser import parse, ParseError, Num, BinOp, Unary
|
||||
|
||||
|
||||
def p(src: str):
|
||||
"""Shorthand: tokenize then parse."""
|
||||
return parse(tokenize(src))
|
||||
|
||||
|
||||
class TestD1Precedence(unittest.TestCase):
|
||||
def test_mul_binds_tighter_than_add(self):
|
||||
# 1+2*3 => BinOp('+', Num(1), BinOp('*', Num(2), Num(3)))
|
||||
tree = p("1+2*3")
|
||||
self.assertEqual(tree, BinOp("+", Num(1), BinOp("*", Num(2), Num(3))))
|
||||
|
||||
def test_div_binds_tighter_than_sub(self):
|
||||
# 9-6/2 => BinOp('-', Num(9), BinOp('/', Num(6), Num(2)))
|
||||
tree = p("9-6/2")
|
||||
self.assertEqual(tree, BinOp("-", Num(9), BinOp("/", Num(6), Num(2))))
|
||||
|
||||
def test_add_before_mul_different_shape(self):
|
||||
# 1+2*3 must NOT parse as (1+2)*3
|
||||
tree = p("1+2*3")
|
||||
self.assertNotEqual(tree, BinOp("*", BinOp("+", Num(1), Num(2)), Num(3)))
|
||||
|
||||
|
||||
class TestD2LeftAssociativity(unittest.TestCase):
|
||||
def test_sub_left_assoc(self):
|
||||
# 8-3-2 => BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))
|
||||
tree = p("8-3-2")
|
||||
self.assertEqual(tree, 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))
|
||||
tree = p("8/4/2")
|
||||
self.assertEqual(tree, 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))
|
||||
tree = p("1+2+3")
|
||||
self.assertEqual(tree, 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))
|
||||
tree = p("2*3*4")
|
||||
self.assertEqual(tree, BinOp("*", BinOp("*", Num(2), Num(3)), Num(4)))
|
||||
|
||||
|
||||
class TestD3Parentheses(unittest.TestCase):
|
||||
def test_parens_override_precedence(self):
|
||||
# (1+2)*3 => BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))
|
||||
tree = p("(1+2)*3")
|
||||
self.assertEqual(tree, BinOp("*", BinOp("+", Num(1), Num(2)), Num(3)))
|
||||
|
||||
def test_nested_parens(self):
|
||||
# ((2+3)) => BinOp('+', Num(2), Num(3)) (extra parens transparent)
|
||||
tree = p("((2+3))")
|
||||
self.assertEqual(tree, BinOp("+", Num(2), Num(3)))
|
||||
|
||||
def test_parens_and_precedence_mixed(self):
|
||||
# 2*(3+4*5) => BinOp('*', Num(2), BinOp('+', Num(3), BinOp('*', Num(4), Num(5))))
|
||||
tree = p("2*(3+4*5)")
|
||||
self.assertEqual(
|
||||
tree,
|
||||
BinOp("*", Num(2), BinOp("+", Num(3), BinOp("*", Num(4), Num(5)))),
|
||||
)
|
||||
|
||||
|
||||
class TestD4UnaryMinus(unittest.TestCase):
|
||||
def test_leading_unary(self):
|
||||
# -5 => Unary('-', Num(5))
|
||||
tree = p("-5")
|
||||
self.assertEqual(tree, Unary("-", Num(5)))
|
||||
|
||||
def test_unary_in_parens(self):
|
||||
# -(1+2) => Unary('-', BinOp('+', Num(1), Num(2)))
|
||||
tree = p("-(1+2)")
|
||||
self.assertEqual(tree, Unary("-", BinOp("+", Num(1), Num(2))))
|
||||
|
||||
def test_unary_after_binop(self):
|
||||
# 3 * -2 => BinOp('*', Num(3), Unary('-', Num(2)))
|
||||
tree = p("3 * -2")
|
||||
self.assertEqual(tree, BinOp("*", Num(3), Unary("-", Num(2))))
|
||||
|
||||
def test_double_unary(self):
|
||||
# --5 => Unary('-', Unary('-', Num(5)))
|
||||
tree = p("--5")
|
||||
self.assertEqual(tree, Unary("-", Unary("-", Num(5))))
|
||||
|
||||
|
||||
class TestD5Errors(unittest.TestCase):
|
||||
def _raises(self, src: str):
|
||||
with self.assertRaises(ParseError, msg=f"expected ParseError for {src!r}"):
|
||||
p(src)
|
||||
|
||||
def test_trailing_operator(self):
|
||||
self._raises("1 +")
|
||||
|
||||
def test_unclosed_paren(self):
|
||||
self._raises("(1")
|
||||
|
||||
def test_two_numbers_no_op(self):
|
||||
self._raises("1 2")
|
||||
|
||||
def test_close_before_open(self):
|
||||
self._raises(")(")
|
||||
|
||||
def test_empty_string(self):
|
||||
self._raises("")
|
||||
|
||||
def test_open_close_no_expr(self):
|
||||
# "()" should fail — no expression inside
|
||||
self._raises("()")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
21
calculators/builder-solo/run-04/machine-docs/JOURNAL-eval.md
Normal file
21
calculators/builder-solo/run-04/machine-docs/JOURNAL-eval.md
Normal file
@ -0,0 +1,21 @@
|
||||
# JOURNAL — eval phase
|
||||
|
||||
## Build log
|
||||
|
||||
1. Read `calc/parser.py` to understand AST node types: `Num`, `BinOp`, `Unary`.
|
||||
2. Created `calc/evaluator.py`:
|
||||
- `EvalError` exception for API-safe error surface.
|
||||
- `evaluate(node)` walks AST recursively.
|
||||
- Division uses true division (`/`); div-by-zero raises `EvalError`.
|
||||
- Whole-valued float results are returned as `int` (D3 rule).
|
||||
3. Created `calc/test_evaluator.py`:
|
||||
- `TestArithmetic` covers all D1 expressions.
|
||||
- `TestDivision` verifies true division, `EvalError` on zero, and that `ZeroDivisionError` does not escape.
|
||||
- `TestResultType` checks int/float return types.
|
||||
- `TestCLI` uses subprocess to verify D4 (exit codes, stderr output).
|
||||
4. Created top-level `calc.py` CLI:
|
||||
- Accepts one argument, runs the full pipeline.
|
||||
- Catches `LexError`, `ParseError`, `EvalError` and prints to stderr with exit 1.
|
||||
- No traceback on error.
|
||||
5. Ran `python -m unittest -q` → 49 tests, 0 failures.
|
||||
6. Ran all 8 CLI checks from the plan — all match expected output.
|
||||
18
calculators/builder-solo/run-04/machine-docs/JOURNAL-lex.md
Normal file
18
calculators/builder-solo/run-04/machine-docs/JOURNAL-lex.md
Normal file
@ -0,0 +1,18 @@
|
||||
# JOURNAL-lex
|
||||
|
||||
## 2026-06-15
|
||||
|
||||
**Built:** `calc/__init__.py`, `calc/lexer.py`, `calc/test_lexer.py`, `.gitignore`
|
||||
|
||||
**Design decisions:**
|
||||
- `Token` is a `@dataclass` with `kind: str` and `value: Union[int, float, str, None]`
|
||||
- Operators/parens carry their char as value; EOF carries `None`
|
||||
- Number parsing: scans contiguous digits/dots; if `.` present → `float()`, else `int()`
|
||||
- `LexError` extends `Exception`; message includes repr of bad char and its index
|
||||
|
||||
**Verification (all 3 plan commands passed):**
|
||||
1. `python -m unittest -q` → 15 tests, 0 failures
|
||||
2. `tokenize('3.5*(1-2)')` → correct 8-token list
|
||||
3. `tokenize('1 @ 2')` → raises `LexError: unexpected character '@' at position 2`
|
||||
|
||||
**Commit:** c37b70f — pushed to origin/main
|
||||
@ -0,0 +1,16 @@
|
||||
# JOURNAL-parse
|
||||
|
||||
## Session 1
|
||||
|
||||
Built `calc/parser.py` — recursive-descent parser with grammar:
|
||||
- `expr → term (('+' | '-') term)*`
|
||||
- `term → unary (('*' | '/') unary)*`
|
||||
- `unary → '-' unary | primary`
|
||||
- `primary → NUMBER | '(' expr ')'`
|
||||
|
||||
Left associativity achieved via iterative loops (not recursion) in `expr` and `term`.
|
||||
Unary minus handled in its own `unary` rule, which recurses right.
|
||||
|
||||
Built `calc/test_parser.py` with 19 tests (35 total including lex tests) covering D1–D5.
|
||||
|
||||
All DoD gates passed on first run.
|
||||
62
calculators/builder-solo/run-04/machine-docs/STATUS-eval.md
Normal file
62
calculators/builder-solo/run-04/machine-docs/STATUS-eval.md
Normal file
@ -0,0 +1,62 @@
|
||||
# STATUS — eval phase
|
||||
|
||||
## Gate verification
|
||||
|
||||
### D1 — arithmetic
|
||||
|
||||
| Expression | Expected | Command | Observed |
|
||||
|------------|----------|---------|----------|
|
||||
| `2+3*4` | 14 | `python calc.py "2+3*4"` | `14` |
|
||||
| `(2+3)*4` | 20 | `python calc.py "(2+3)*4"` | `20` |
|
||||
| `8-3-2` | 3 | `python calc.py "8-3-2"` | `3` |
|
||||
| `-2+5` | 3 | `python calc.py "-2+5"` | `3` |
|
||||
| `2*-3` | -6 | `python calc.py "2*-3"` | `-6` |
|
||||
|
||||
**Result: PASS**
|
||||
|
||||
### D2 — division / EvalError
|
||||
|
||||
| Check | Command | Expected | Observed |
|
||||
|-------|---------|----------|----------|
|
||||
| True division | `python calc.py "7/2"` | `3.5` | `3.5` |
|
||||
| Div-by-zero stderr + exit 1 | `python calc.py "1/0"` | error to stderr, exit 1 | `error: division by zero`, exit 1 |
|
||||
| EvalError (not ZeroDivisionError) | unittest | EvalError raised | PASS (test_no_bare_zero_division_error) |
|
||||
|
||||
**Result: PASS**
|
||||
|
||||
### D3 — result type
|
||||
|
||||
| Check | Command | Expected | Observed |
|
||||
|-------|---------|----------|----------|
|
||||
| Whole result as int | `python calc.py "4/2"` | `2` (no `.0`) | `2` |
|
||||
| Non-whole as float | `python calc.py "7/2"` | `3.5` | `3.5` |
|
||||
|
||||
**Result: PASS**
|
||||
|
||||
### D4 — CLI
|
||||
|
||||
| Check | Command | Expected | Observed |
|
||||
|-------|---------|----------|----------|
|
||||
| Valid expression → stdout + exit 0 | `python calc.py "2+3*4"` | `14`, exit 0 | `14`, exit 0 |
|
||||
| Invalid expression → stderr + exit non-zero | `python calc.py "1 +"` | error to stderr, exit 1 | `error: unexpected end of input`, exit 1 |
|
||||
| Div-by-zero → stderr + exit non-zero | `python calc.py "1/0"` | error to stderr, exit 1 | `error: division by zero`, exit 1 |
|
||||
|
||||
**Result: PASS**
|
||||
|
||||
### D5 — tests green + no regression
|
||||
|
||||
Command: `python -m unittest -q`
|
||||
|
||||
Expected: 0 failures, covers D1–D3 + prior suite (lex + parse)
|
||||
|
||||
Observed:
|
||||
```
|
||||
----------------------------------------------------------------------
|
||||
Ran 49 tests in 0.105s
|
||||
|
||||
OK
|
||||
```
|
||||
|
||||
**Result: PASS**
|
||||
|
||||
## DONE
|
||||
64
calculators/builder-solo/run-04/machine-docs/STATUS-lex.md
Normal file
64
calculators/builder-solo/run-04/machine-docs/STATUS-lex.md
Normal file
@ -0,0 +1,64 @@
|
||||
# STATUS-lex
|
||||
|
||||
Phase: `lex`
|
||||
Commit: c37b70f
|
||||
|
||||
## Gate Results
|
||||
|
||||
### D1 — numbers
|
||||
**What:** Integers and floats tokenize to NUMBER tokens with correct Python values (int or float).
|
||||
**Command:** `python -c "from calc.lexer import tokenize; print([(t.kind,t.value) for t in tokenize('42')])"`
|
||||
**Expected:** `[('NUMBER', 42), ('EOF', None)]`
|
||||
**Observed:** `[('NUMBER', 42), ('EOF', None)]`
|
||||
**Result:** PASS
|
||||
|
||||
Float test: `tokenize("3.14")` → `[('NUMBER', 3.14), ('EOF', None)]` ✓
|
||||
Leading dot: `tokenize(".5")` → `[('NUMBER', 0.5), ('EOF', None)]` ✓
|
||||
Trailing dot: `tokenize("10.")` → `[('NUMBER', 10.0), ('EOF', None)]` ✓
|
||||
|
||||
### D2 — operators & parens
|
||||
**What:** `+ - * / ( )` tokenize to correct kinds; `"1+2*3"` yields NUMBER PLUS NUMBER STAR NUMBER EOF.
|
||||
**Command:** `python -c "from calc.lexer import tokenize; print([t.kind for t in tokenize('1+2*3')])"`
|
||||
**Expected:** `['NUMBER', 'PLUS', 'NUMBER', 'STAR', 'NUMBER', 'EOF']`
|
||||
**Observed:** Confirmed via test suite (15/15 tests pass)
|
||||
**Result:** PASS
|
||||
|
||||
### D3 — whitespace & errors
|
||||
**What:** Spaces/tabs skipped; invalid chars raise LexError with char and position.
|
||||
**Command (whitespace):** `python -c "from calc.lexer import tokenize; print([t.kind for t in tokenize(' 12 + 3 ')])"`
|
||||
**Observed:** `['NUMBER', 'PLUS', 'NUMBER', 'EOF']` ✓
|
||||
|
||||
**Command (error):** `python -c "from calc.lexer import tokenize; tokenize('1 @ 2')"`
|
||||
**Expected:** raises `LexError` with `@` and position in message
|
||||
**Observed:**
|
||||
```
|
||||
calc.lexer.LexError: unexpected character '@' at position 2
|
||||
```
|
||||
**Result:** PASS
|
||||
|
||||
### D4 — tests green
|
||||
**Command:** `python -m unittest -q`
|
||||
**Expected:** 0 failures
|
||||
**Observed:**
|
||||
```
|
||||
----------------------------------------------------------------------
|
||||
Ran 15 tests in 0.000s
|
||||
|
||||
OK
|
||||
```
|
||||
**Result:** PASS
|
||||
|
||||
### Plan verification commands (from plan's "Verify" section)
|
||||
|
||||
```
|
||||
python -m unittest -q
|
||||
→ Ran 15 tests in 0.000s / 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')"
|
||||
→ calc.lexer.LexError: unexpected character '@' at position 2
|
||||
```
|
||||
|
||||
## DONE
|
||||
56
calculators/builder-solo/run-04/machine-docs/STATUS-parse.md
Normal file
56
calculators/builder-solo/run-04/machine-docs/STATUS-parse.md
Normal file
@ -0,0 +1,56 @@
|
||||
# STATUS-parse
|
||||
|
||||
Phase: `parse`
|
||||
Files: `calc/parser.py`, `calc/test_parser.py`
|
||||
|
||||
## AST Shape
|
||||
|
||||
```
|
||||
Num(value) — leaf; value is int or float
|
||||
BinOp(op, left, right) — op ∈ {'+', '-', '*', '/'}; left and right are Nodes
|
||||
Unary(op, operand) — op is '-'; operand is a Node
|
||||
```
|
||||
|
||||
All nodes are `@dataclass` with custom `__repr__`.
|
||||
`parse(tokens) -> Node` accepts the list returned by `calc.lexer.tokenize`.
|
||||
`ParseError(Exception)` is raised for all malformed input.
|
||||
|
||||
## Gate Verification
|
||||
|
||||
### D1 — Precedence
|
||||
**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)))` ✓ **PASS**
|
||||
|
||||
### D2 — Left Associativity
|
||||
**Command:** parse `8-3-2` and `8/4/2`
|
||||
**Expected:** `BinOp('-', BinOp('-', Num(8), Num(3)), Num(2))` and `BinOp('/', BinOp('/', Num(8), Num(4)), Num(2))`
|
||||
**Observed:** Both matched exactly ✓ **PASS**
|
||||
|
||||
### D3 — Parentheses
|
||||
**Command:** parse `(1+2)*3`
|
||||
**Expected:** `BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))`
|
||||
**Observed:** `BinOp('*', BinOp('+', Num(1), Num(2)), Num(3))` ✓ **PASS**
|
||||
|
||||
### D4 — Unary Minus
|
||||
**Commands:** parse `-5`, `-(1+2)`, `3 * -2`
|
||||
**Expected:** `Unary('-', Num(5))`, `Unary('-', BinOp('+', Num(1), Num(2)))`, `BinOp('*', Num(3), Unary('-', Num(2)))`
|
||||
**Observed:** All three matched exactly ✓ **PASS**
|
||||
|
||||
### D5 — Errors
|
||||
**Inputs tested:** `"1 +"`, `"(1"`, `"1 2"`, `")("`, `""`
|
||||
**Expected:** Each raises `ParseError`
|
||||
**Observed:**
|
||||
- `"1 +"` → `ParseError: unexpected end of input` ✓
|
||||
- `"(1"` → `ParseError: unclosed '(' — expected ')'` ✓
|
||||
- `"1 2"` → `ParseError: unexpected token Token(kind='NUMBER', value=2) after expression` ✓
|
||||
- `")("` → `ParseError: unexpected token 'RPAREN' (')')` ✓
|
||||
- `""` → `ParseError: unexpected end of input` ✓
|
||||
**PASS**
|
||||
|
||||
### D6 — Tests Green
|
||||
**Command:** `python -m unittest -q`
|
||||
**Expected:** 0 failures
|
||||
**Observed:** `Ran 35 tests in 0.001s — OK` ✓ **PASS**
|
||||
|
||||
## DONE
|
||||
Reference in New Issue
Block a user