From 9fb8dcb2d90dc062042584cc3f89031b6674bb23 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 04:57:40 +0000 Subject: [PATCH 1/2] docs: RPN/programmable mode architecture and UX plan Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016hSe4b1KT9ibb3CNa7Ja8W --- DECISIONS.md | 12 +++++ docs/CHANGELOG.md | 4 ++ docs/ROADMAP.md | 8 ++- docs/RPN_PLAN.md | 135 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 158 insertions(+), 1 deletion(-) create mode 100644 docs/RPN_PLAN.md diff --git a/DECISIONS.md b/DECISIONS.md index 728b0b0..3b46793 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -699,3 +699,15 @@ number within the filtered subset, so --log-pin, --log-tag and --log-note addressing is the same from any view. The filtered export is chronological, like the lab record, because an exported record is read forwards in time. + +## 2026-11-07 — RPN / programmable mode (Free42 + Plus42 functionality) +SEAN asked for the functionality of Free42 and Plus42 and said +"proceed as you suggest". Chosen scope: (b) an HP-42S-compatible +RPN/programmable mode inside CalcDex first, then the Plus42 +extras (equations, units, TVM, directories, plotting). Clean-room +implementation (Free42/Plus42 are GPLv2; CalcDex stays MIT): no +upstream source read or copied. Engine lives in a new `src/rpn/` +beside the registry, because the registry signature is stateless, +f64-only and scalar. Numbers: f64 first, 34-digit decimal in P2. +Own versioned state format; program listings import/export. No UI +code until the wireframe is approved. Plan: docs/RPN_PLAN.md. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a448876..b5ad4b9 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Planned +- RPN / programmable mode (HP-42S-compatible, then Plus42-style + extras): plan in [RPN_PLAN.md](RPN_PLAN.md). No code yet. + ### Fixed - Legacy storage migration stages and flushes the complete data set before publication, preserving legacy storage on failure and existing foreign entries. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 68f63de..f92ac1f 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1,4 +1,10 @@ -# Roadmap — what v0.1.1 does NOT do yet (honest list) +# Roadmap — what CalcDex does NOT do yet (honest list) + +The RPN / programmable mode (Free42 + Plus42 functionality) is +planned in [RPN_PLAN.md](RPN_PLAN.md). The lists below date from +v0.1.1 and have not all been re-checked against v0.9.0; items +shipped since then (dates, log, engineering, units in expressions) +may still appear. Done since v0.1 (removed from the gap list): merged MM/DD/YYYY date fields with Today? buttons and end-date wording, CLI one-argument diff --git a/docs/RPN_PLAN.md b/docs/RPN_PLAN.md new file mode 100644 index 0000000..fcad03c --- /dev/null +++ b/docs/RPN_PLAN.md @@ -0,0 +1,135 @@ +# RPN / Programmable Mode — Architecture & UX Plan + +Status: PLAN (no code yet). Progress 0%. No ETA until P1 lands. +Decision: scope (b) — an HP-42S-compatible RPN/programmable mode +inside CalcDex, then the Plus42-style extras. Recorded in DECISIONS.md. + +## Goal +Offer the functionality of Free42 (HP-42S simulator) and Plus42 +(Free42 + algebraic equations, units, directories, TVM, plotting) +as a new **RPN** mode of CalcDex, alongside the 316 registry +calculators. Targets: HP-42S program compatibility and Plus42 +feature coverage, claimed only as far as tests prove. + +## Clean-room rule +Free42/Plus42 are GPLv2. CalcDex is MIT. No Free42/Plus42 source is +read, copied or translated. Behaviour comes from the published +HP-42S Owner's Manual, HP-42S Programming Examples, the Free42 / +Plus42 public documentation pages, and black-box comparison of +program results. Test programs must be public-domain or written +here. Any contributor who has read Free42 source is asked to say so +in the PR. + +## Why a new engine +The registry signature `Fn(&[f64]) -> Result` is +stateless, scalar and f64-only. The RPN machine is stateful (stack, +registers, programs, flags) and typed (real, complex, string, +matrix, list, later unit/equation). It lives beside the registry: + +``` +src/rpn/ + mod.rs public API: Session, Key/Op dispatch, text front end + num.rs Num (real) — f64-backed first, 34-digit decimal later + value.rs enum Value { Real, Complex, Str, Matrix, List, ... } + stack.rs 4-level stack + LASTX, optional growing "big stack" + ops/ one file per family: arith, trig, stats, base, time, + matrix, complex, string, list, flags, control + display.rs FIX/SCI/ENG/ALL, RDX./RDX, separators, base views + prog.rs program memory, labels, listing parse/print + run.rs interpreter: GTO/XEQ/RTN, flags, local vars, SST/BST + solve.rs SOLVE, integrator (programmable + equation based) + state.rs versioned state file, atomic save, import/export + eqn.rs (Plus42 phase) equation parser/evaluator + units.rs (Plus42 phase) attached units +``` + +`src/main.rs` stays shell-only. The registry is untouched except for +one new text entry point, `run_rpn(session, line)`, so the window +and CLI share one dispatch (AGENTS.md invariant). + +## Invariants (inherit AGENTS.md) +- No `unwrap()`/`expect()` on user input or file content; every + error is a plain-words message with a stable code. +- State, programs and settings live under `data/`, versioned + (`schema_version`), written atomically, with a migration fixture + for every bump. Unparseable state is quarantined, never reset. +- Interpreter is bounded: step/time limit with a cancel check + (abort < 50 ms), recursion depth cap, memory cap. +- Offline, zero telemetry, idle RAM < 40 MB, UI thread < 16 ms + (long programs run on a worker thread). +- Every capability reachable from the CLI. + +## CLI surface +``` +CalcDex rpn "2 3 + 4 *" one-shot, prints X (and stack with --stack) +CalcDex rpn --state NAME ... use/save a named state +CalcDex rpn --run prog.txt load a listing and XEQ it +CalcDex rpn --listing prog.txt print/validate a listing +CalcDex rpn --json ... machine-readable result +``` +Input tokens: numbers (incl. `1.5e-3`), HP-42S mnemonics (`ENTER`, +`STO 01`, `RCL "A"`, `XEQ "NAME"`), and `PRGM` lines. + +## Numbers +- Phase 1: `Num` wraps f64 (Free42 "Binary" equivalent). Documented + difference: 0.1 inexact. +- Phase 2: `Num` becomes a 34-digit decimal (IEEE 754-2008 + decimal128 semantics: 34 digits, exponent ±6144), pure Rust, + no C dependency. Transcendentals are implemented with guard + digits and verified against high-precision reference vectors. + A runtime/setting switch keeps both modes, as Free42 does. +- Risk: correct rounding of sin/exp/ln at 34 digits is the hardest + single item; if it slips, decimal mode ships with arithmetic, + sqrt and powers exact and transcendentals documented as + ≤ 1 ulp-ish with measured error, never claimed correctly rounded. + +## Phases (each = one PR, full gate green before merge) +| # | Scope | Done when | +|---|---|---| +| P1 | RPN core: stack, LASTX, entry, arithmetic and scientific functions, STO/RCL + named variables, FIX/SCI/ENG/ALL, `rpn` CLI | HP-42S manual chapter 2–3 examples pass | +| P2 | 34-digit decimal `Num`, Binary/Decimal switch | reference-vector suite; 0.1+0.2 exact | +| P3 | Complex (rect/polar), strings/ALPHA, lists | manual complex examples pass | +| P4 | Matrices: edit, inverse, det, transpose, row ops, linear solve, complex matrices | known-answer matrix suite | +| P5 | Programming: memory, labels, GTO/XEQ/RTN, tests, flags, loops (ISG/DSE), local vars (LSTO), SST/BST, listing import/export + clipboard | public-domain 42S programs run to expected output | +| P6 | Numerical SOLVE and integrator (programmable) | manual solver/integrator examples | +| P7 | Statistics (Σ+, regressions, forecasts), BASE (word size, bit ops), time/date functions | known-answer suites; dates 1582-10-15..4320-09-10 | +| P8 | State files, states manager, full copy/paste formats (scalars, matrices tab-delimited, programs) | round-trip + migration fixtures | +| P9 | GUI: keypad + display + program view + variables, as a mode on the mode rail | wireframe approved (below); screenshots from real run | +| P10 | Plus42: EQN parser/evaluator, direct+numeric solver, equation integration | equation suite | +| P11 | Plus42: attached units + catalog, TVM/amortization, directories | unit and TVM known answers | +| P12 | Plus42: XY plotting + plot viewer, big display options | plot export + visual check on Windows | +| P13 | Compatibility pass: corpus of 42S programs, verification matrix, docs | claims in README match tests | + +Out of scope unless asked: HP-82240 printer emulation, skin files, +accelerometer/GPS/compass, Android/iOS builds (CalcDex is +windows-x64). + +## UX +- New **RPN** mode on the mode rail (same Terminal theme, radius 0, + Cascadia Mono). Centre: display (stack levels, X highlighted, + annunciators: RAD/DEG, FIX/SCI, shift, PRGM, flags), keypad, + menu row (soft keys), optional program/variables panes. History + rail shows the tape. +- Keyboard first: physical keys map to RPN keys; Enter = ENTER; + Esc = cancel/abort program; Tab order logical; every key has a + tooltip (action + side effects). +- Window geometry and splitters persist (already supported). +- Accessibility: focus visuals, accessible names on every key, + contrast measured to WCAG AA, no colour-only annunciators. +- Wireframe sign-off is required before P9 (AGENTS.md gate); P1–P8 + have no UI work. + +## Testing / verification +- Known-answer vectors per op; property tests for stack invariants. +- Program corpus with expected outputs (written here or + public-domain). +- Failure drills: bad state file, truncated listing, runaway loop, + deep recursion, huge matrix, cancel mid-run. +- Evidence labels (Verified / Partially verified / Unverified) in + QUALITY.md; on-Windows GUI checks stay Unverified until run. + +## Open questions +1. Wireframe approval (P9). +2. Decimal precision fallback acceptable per the risk note above? +3. Keep Free42-compatible `.f42` state files? Default: no — own + versioned format, with listing import/export for programs. From ad08f4993d9af0cddeb0cc1e19ec8e148f8ff35d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 05:08:10 +0000 Subject: [PATCH 2/2] feat(rpn): P1 stack machine, display formats, state file, rpn CLI Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016hSe4b1KT9ibb3CNa7Ja8W --- QUALITY.md | 5 + README.md | 13 + docs/CHANGELOG.md | 16 +- docs/CREDITS.md | 8 + docs/PARITY.md | 6 + docs/RPN_PLAN.md | 15 +- src/lib.rs | 1 + src/main.rs | 71 +++++- src/paths.rs | 18 +- src/rpn/display.rs | 121 +++++++++ src/rpn/mod.rs | 598 +++++++++++++++++++++++++++++++++++++++++++++ src/rpn/state.rs | 190 ++++++++++++++ tests/rpn_p1.rs | 267 ++++++++++++++++++++ 13 files changed, 1322 insertions(+), 7 deletions(-) create mode 100644 src/rpn/display.rs create mode 100644 src/rpn/mod.rs create mode 100644 src/rpn/state.rs create mode 100644 tests/rpn_p1.rs diff --git a/QUALITY.md b/QUALITY.md index 4fa5799..852ca8b 100644 --- a/QUALITY.md +++ b/QUALITY.md @@ -126,3 +126,8 @@ at release (2026-10-25, this machine). - Windows cross-builds — x86_64-pc-windows-gnu (GCC 13): PE32+ GUI x86-64, `.rsrc` 14,792 B, exe 5,790,208 B, SHA-256 3764e29f92d1f6f3675a2f919abfbd9f631045385c237e32e0bdb6eda61e40d0; i686-pc-windows-gnu (GCC 13): PE32 GUI Intel 80386, `.rsrc` 14,792 B, exe 5,867,008 B, SHA-256 3d5f43b49f98654985f1323e717ca728b6240dad848b851439f2529840e2c9c5; aarch64-pc-windows-gnullvm (llvm-mingw clang): PE32+ GUI Aarch64, `.rsrc` 14,792 B, exe 5,194,240 B, SHA-256 757d6acf426033ff4375fcf3e952882d3a33057346ee054092376248eaeac259. Feature strings verified in all three binaries ("FOR ENGINEERS"). Toolchain notes: the VM had again lost the apt packages — gcc-mingw-w64-i686, gcc-mingw-w64-x86-64, nsis, msitools, llvm-18 and p7zip-full were reinstalled. The ARM64 build first linked without `.rsrc`: build.rs calls a bare `windres` for non-x86_64 targets, served by the per-arch shim in ~/calcdex-shims (i686 → GNU windres; aarch64 → llvm-mingw's wrapper), and the wrapper's llvm-windres needs clang on PATH for preprocessing — the first ARM64 build ran without llvm-mingw/bin on PATH, so build.rs quietly skipped the icon; adding ~/llvm-mingw/bin after the shim directory and touching build.rs fixed it (verified: .rsrc present at the same 14,792 B as the other targets). - Assets (exact-name 7-asset set, in dist/ and copied to dist-archive/v0.8.0/): CalcDex-Setup-x86.exe 2,514,196 B 9d711860b2f4949ec22bac7ec7021457534fa4765950fb4096ef311bfb6c3e04; CalcDex-Setup-x64.exe 2,321,248 B 5ae67623b2b3ef600d8cf220541c5cce5b872c33005aa269e5e04cd636b7e0b2; CalcDex-Setup-ARM64.exe 2,115,849 B dc30e40f6d7c31aa39ce8c5356a8729f102ffba0cc316265579a416ed3f207ba; CalcDex-Setup-x86_64.msi 2,926,592 B e62818b2e4835735d862c924e93badc59feb022bcc633cffed0eb8c4657f3d27; CalcDex-Portable-x86.zip 2,976,329 B 8a440e012345dd39d664394c8763e538d680a61b2abe93909f81c11ba0658af3; CalcDex-Portable-x64.zip 2,781,315 B 24809750dc097e8b6857f598d67440e2cd5f0e7a1b6c74e9e1bf1520f1645af5; CalcDex-Portable-ARM64.zip 2,635,949 B 3883582295c225c179755397a1c397dfe07bb9c15c409a8429cfd2911a923b99. Every payload verified by extraction: all three NSIS installers and the MSI contain their architecture's exe (SHA-256 identical to the cross-builds above; MSI payload = x64), and each portable zip holds CalcDex.exe + LICENSE + PORTABLE.txt with the exe hash matching its cross-build and the PE machine correct (80386 / x86-64 / Aarch64). NSIS stubs are 32-bit launchers by design. - On-Windows behaviour of the v0.8.0 GUI additions (MATERIALS view + USE E IN BEAM, the log view's search/filter/pin/export controls, the resistor colour text field): **Unverified** — a field run is the verdict. + +## RPN P1 gate transcript (2026-11-07, Linux sandbox) +- `cargo fmt --check` clean. `cargo clippy --all-targets --locked -D warnings`: clean for the new code; one existing lint (`manual_range_contains`, src/lib.rs:390, Rust 1.97) is not from this change and was not touched. +- `cargo test --locked --no-fail-fast`: every test binary passes, including 13 new in tests/rpn_p1.rs, except `v090::first_run_copies_legacy_files_into_data_beside_the_exe`, which also fails on the unmodified base here (Windows-only migration path) — Partially verified until run on Windows. +- Behaviour matches the repo's own known answers only; not compared with a real HP-42S or Free42 (see RPN_PLAN.md limitations). On-Windows run of `CalcDex rpn` is Unverified. diff --git a/README.md b/README.md index 04ace12..59788a8 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,19 @@ CalcDex --restore-log CalcDex --check-update ``` +RPN mode (v0.9.x, command line only for now; window comes later): + +``` +CalcDex rpn "2 3 + 4 *" prints 20.0000 +CalcDex rpn "1 3 / ALL" prints 0.333333333333 +CalcDex rpn "5 ENTER 3 -" --stack shows T/Z/Y/X +CalcDex rpn "12 STO A" --state work keep variables between runs +``` + +Tokens are separated by spaces: numbers (`1.5e-3`), operators, +and HP-42S names (ENTER, SIN, STO, RCL, FIX 4, ...). Errors name a +stable code such as `[RPN-103]`. See `docs/RPN_PLAN.md`. + Numbers go in the same order as the labelled boxes in the window. For unit converters the two extra numbers pick the units from the numbered list shown in that calculator's description. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index b5ad4b9..a6e3b15 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,9 +2,19 @@ ## Unreleased -### Planned -- RPN / programmable mode (HP-42S-compatible, then Plus42-style - extras): plan in [RPN_PLAN.md](RPN_PLAN.md). No code yet. +### Added +- **RPN mode, phase P1 (command line).** `CalcDex rpn "2 3 + 4 *"` + runs HP-42S-style tokens on a 4-level stack with LASTX, stack + lift/ENTER, arithmetic, powers, roots, logs, trig (DEG/RAD/GRAD, + exact at quarter turns), hyperbolics, FACT/COMB/PERM, %, %CH, + MOD, named variables (STO/RCL and STO+ - * /, RCL+ - * /, CLV) + and FIX/SCI/ENG/ALL display. `--stack` shows T/Z/Y/X, `--json` + prints one JSON object, `--state NAME` keeps the stack and + variables between runs in `data/rpn-NAME.txt` (versioned, + atomic; a corrupt file is kept as `.bad`, a newer-version file + is never overwritten). `--clean`/`--uninstall` remove these + files. Numbers are f64 for now; 34-digit decimal is phase P2. + No window yet (phase P9). Plan: [RPN_PLAN.md](RPN_PLAN.md). ### Fixed - Legacy storage migration stages and flushes the complete data set before diff --git a/docs/CREDITS.md b/docs/CREDITS.md index aa9dc9a..69521a7 100644 --- a/docs/CREDITS.md +++ b/docs/CREDITS.md @@ -15,3 +15,11 @@ problem-set tooling, the installers and these documents — is part of this repository, MIT-licensed (see [../LICENSE](../LICENSE)). Reference values in the constants table are the CODATA 2018 recommended values. + +## RPN mode + +The RPN mode follows the behaviour of the HP-42S calculator as +described in HP's published owner's manual and in the public +documentation of Free42 / Plus42 by Thomas Okken (GPLv2). No code +from those projects is used (clean-room); the names and +conventions are theirs and HP's. diff --git a/docs/PARITY.md b/docs/PARITY.md index 934ace8..02ade2a 100644 --- a/docs/PARITY.md +++ b/docs/PARITY.md @@ -102,3 +102,9 @@ result in outputs; full precision; scientific-notation inputs; constants named; estimates labelled. Implemented in the registry output text and README — Verified by CLI output; GUI presentation of the v0.4.0, v0.5.0, v0.6.0 and v0.7.0 panels is Unverified until a fresh field run. + +## RPN mode (P1) + +| Capability | Window | Command line | +|---|---|---| +| RPN stack machine (P1) | Not yet (phase P9) | `CalcDex rpn ""` — Verified by tests/rpn_p1.rs | diff --git a/docs/RPN_PLAN.md b/docs/RPN_PLAN.md index fcad03c..d34b1fa 100644 --- a/docs/RPN_PLAN.md +++ b/docs/RPN_PLAN.md @@ -1,6 +1,8 @@ # RPN / Programmable Mode — Architecture & UX Plan -Status: PLAN (no code yet). Progress 0%. No ETA until P1 lands. +Status: P1 done (RPN core + `rpn` CLI, f64 numbers). P2–P13 not +started. Progress: 1 of 13 phases (~8%, rough, phases differ a lot +in size). No ETA: P4–P6 and P10–P12 are the big ones. Decision: scope (b) — an HP-42S-compatible RPN/programmable mode inside CalcDex, then the Plus42-style extras. Recorded in DECISIONS.md. @@ -133,3 +135,14 @@ windows-x64). 2. Decimal precision fallback acceptable per the risk note above? 3. Keep Free42-compatible `.f42` state files? Default: no — own versioned format, with listing import/export for programs. + +## Known limitations after P1 (Unverified against real HP-42S) +- SQRT of a negative real, LN of 0 or less, etc. give Invalid Data; + real hardware/Free42 may return complex results. Revisit in P3. +- `0 0 Y^X` returns 1 (IEEE); hardware behaviour not checked. +- `MOD` with divisor 0 is an error here; hardware not checked. +- ENG n shows n+1 significant digits and no trailing point + (`12E-3`); the HP-42S look may differ. +- No registers 00-99 limit, no SIZE, no complex/strings/matrices yet. +- Behaviour checked only by this repo's tests, not by running an + HP-42S or Free42. diff --git a/src/lib.rs b/src/lib.rs index 5f132e9..143a498 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,6 +23,7 @@ pub mod features; pub mod meta; pub mod paths; pub mod rigour; +pub mod rpn; pub mod settings; pub mod students; pub mod teachers; diff --git a/src/main.rs b/src/main.rs index 825dc02..f0ea9ec 100644 --- a/src/main.rs +++ b/src/main.rs @@ -461,6 +461,9 @@ fn cli(args: &[String]) -> i32 { } return 0; } + if args[0] == "rpn" { + return cli_rpn(&args[1..], json); + } if args[0] == "--clean" || args[0] == "--uninstall" { return cli_clean(args[0] == "--uninstall", dry_run, silent, json); } @@ -1242,7 +1245,7 @@ set open list a set file's problems (never answers) --formula-sheet write a printable formula sheet (formula + symbol meanings per calculator) --save-example \"\" [--note \"<note>\"] with a run: save it as a named class example in the examples library --examples list the saved class examples ---open-example \"<title>\" print a saved example's problem + worked solution\n--favourite <id> add a calculator to the favourites in the settings file\n--unfavourite <id> remove it again\n--batch <id> <in.csv> <out.csv> run one calculator over a CSV file (header row names the fields; see README). An existing output file needs --force (backed up to .bak first)\n--force allow --batch to overwrite its output file (with backup)\n--sig-figs <n> also show the headline rounded to n significant figures (display only; may appear anywhere)\n--decimals <n> also show the headline to n decimal places (display only)\n--format <mode[:n]> the unified display format: off, sig-figs:3, decimals:2, engineering, auto (auto = precision inferred from your inputs), exact (fractions labelled exact, pi geometry also shows its exact form like 25*pi, rational expressions worked out exactly)\n--steps <standard|deeper> deeper steps: the formula, the formula with your values in it, the working, and the result, in labelled stages\n--rounding <mode> half-up, bankers or truncate — applies to the display formats above\n--as <format> print a run's result as plain, latex, scientific or csv\n--spec <min> <max> after a run, print PASS/FAIL for each result line against these limits (limits included)\n<calculator-id> <numbers...> run one calculator; numbers in the order of its labelled inputs\n<calculator-id> --example run the calculator's built-in teaching example\n<calculator-id> --vary <field> <start> <end> <step> <other numbers...>\n sweep one input (field numbered from 0, as in --describe);\n the other numbers are the remaining inputs in order\nexpr \"<expression>\" evaluate a free expression, e.g. CalcDex expr \"sqrt(2)/2\" (--degrees/--radians choose the trig mode; degrees is the default)\n<calculator-id> <numbers> --check <answer>\n check your own answer against the run (a number, or a fraction like 3/4 for the fraction calculators)\n<calculator-id> <numbers> --export <path>\n save the worked solution (name, formula, inputs, steps, result) as a plain-text file\n<calculator-id> --practice --seed <n> [--answer <x>]\n print a practice problem made from the seed; with --answer, check your answer and show the worked solution\nexpr \"<expression in x>\" --plot <from> <to>\n print the plot as CSV x,y sample points (the command-line form of the plot; a blank y means the function is not defined there)\n\nDates: a date is entered as ONE argument in MM/DD/YYYY form \u{2014} for example\n CalcDex age 04/23/1988 10/25/2026\nThe older three-number form still works: CalcDex age 1988 4 23 2026 10 25\n\nNumbers may use scientific notation (e.g. 6.022e23, 1.5e-3), and many fields accept typed quantities in quotes (e.g. CalcDex bmi \"154 lb\" \"5 ft 9 in\") — they are converted into the field's unit. Results show the formula, substituted values, and full precision.\n\nExpressions may use the CODATA constants by name (CalcDex expr \"h*c/500e-9\"), your own --define constants, and measurements with uncertainties (CalcDex expr \"10 \u{b1} 0.2 + 5 \u{b1} 0.1\" — also written 10 +/- 0.2): the uncertainty is carried through every operation and the propagation steps are shown. List calculators accept values separated by commas, spaces, tabs, semicolons or new lines — a pasted column in quotes works as one argument.\n\nExample: CalcDex compound-interest 1000 5 10"); +--open-example \"<title>\" print a saved example's problem + worked solution\n--favourite <id> add a calculator to the favourites in the settings file\n--unfavourite <id> remove it again\n--batch <id> <in.csv> <out.csv> run one calculator over a CSV file (header row names the fields; see README). An existing output file needs --force (backed up to .bak first)\n--force allow --batch to overwrite its output file (with backup)\n--sig-figs <n> also show the headline rounded to n significant figures (display only; may appear anywhere)\n--decimals <n> also show the headline to n decimal places (display only)\n--format <mode[:n]> the unified display format: off, sig-figs:3, decimals:2, engineering, auto (auto = precision inferred from your inputs), exact (fractions labelled exact, pi geometry also shows its exact form like 25*pi, rational expressions worked out exactly)\n--steps <standard|deeper> deeper steps: the formula, the formula with your values in it, the working, and the result, in labelled stages\n--rounding <mode> half-up, bankers or truncate — applies to the display formats above\n--as <format> print a run's result as plain, latex, scientific or csv\n--spec <min> <max> after a run, print PASS/FAIL for each result line against these limits (limits included)\n<calculator-id> <numbers...> run one calculator; numbers in the order of its labelled inputs\n<calculator-id> --example run the calculator's built-in teaching example\n<calculator-id> --vary <field> <start> <end> <step> <other numbers...>\n sweep one input (field numbered from 0, as in --describe);\n the other numbers are the remaining inputs in order\nexpr \"<expression>\" evaluate a free expression, e.g. CalcDex expr \"sqrt(2)/2\" (--degrees/--radians choose the trig mode; degrees is the default)\nrpn \"<tokens>\" [--stack] [--state <name>]\n run HP-42S-style RPN tokens, e.g. CalcDex rpn \"2 3 + 4 *\" prints 20.0000; --stack shows T/Z/Y/X; --state keeps the stack and variables between runs (saved in the data folder)\n<calculator-id> <numbers> --check <answer>\n check your own answer against the run (a number, or a fraction like 3/4 for the fraction calculators)\n<calculator-id> <numbers> --export <path>\n save the worked solution (name, formula, inputs, steps, result) as a plain-text file\n<calculator-id> --practice --seed <n> [--answer <x>]\n print a practice problem made from the seed; with --answer, check your answer and show the worked solution\nexpr \"<expression in x>\" --plot <from> <to>\n print the plot as CSV x,y sample points (the command-line form of the plot; a blank y means the function is not defined there)\n\nDates: a date is entered as ONE argument in MM/DD/YYYY form \u{2014} for example\n CalcDex age 04/23/1988 10/25/2026\nThe older three-number form still works: CalcDex age 1988 4 23 2026 10 25\n\nNumbers may use scientific notation (e.g. 6.022e23, 1.5e-3), and many fields accept typed quantities in quotes (e.g. CalcDex bmi \"154 lb\" \"5 ft 9 in\") — they are converted into the field's unit. Results show the formula, substituted values, and full precision.\n\nExpressions may use the CODATA constants by name (CalcDex expr \"h*c/500e-9\"), your own --define constants, and measurements with uncertainties (CalcDex expr \"10 \u{b1} 0.2 + 5 \u{b1} 0.1\" — also written 10 +/- 0.2): the uncertainty is carried through every operation and the propagation steps are shown. List calculators accept values separated by commas, spaces, tabs, semicolons or new lines — a pasted column in quotes works as one argument.\n\nExample: CalcDex compound-interest 1000 5 10"); return 0; } // expr "<expression>" (item #5): free-expression shortcut alias. @@ -1602,6 +1605,72 @@ fn json_escape(s: &str) -> String { /// stderr, so `--json` output on stdout stays parseable). Exit /// codes match the rest of the CLI: 0 = done / nothing to do / /// the user said no, 1 = refused or a removal failed. +/// `CalcDex rpn "<tokens>"` — the RPN stack machine (P1). +fn cli_rpn(args: &[String], json: bool) -> i32 { + use calcdex::rpn::{state, Session}; + let mut show_stack = false; + let mut state_name: Option<String> = None; + let mut parts: Vec<&str> = Vec::new(); + let mut i = 0; + while i < args.len() { + match args[i].as_str() { + "--stack" => show_stack = true, + "--state" => { + i += 1; + match args.get(i) { + Some(n) => state_name = Some(n.clone()), + None => { + eprintln!("--state needs a name, e.g. --state work."); + return 2; + } + } + } + other => parts.push(other), + } + i += 1; + } + let fail = |code: &str, msg: &str| -> i32 { + if json { + let esc = msg.replace('\\', "\\\\").replace('"', "\\\""); + println!("{{\"ok\":false,\"code\":\"{code}\",\"error\":\"{esc}\"}}"); + } else { + eprintln!("{msg}"); + } + 1 + }; + let (mut session, read_only) = match &state_name { + Some(n) => match state::load(n) { + Ok(l) => { + if let Some(note) = &l.note { + eprintln!("{note}"); + } + (l.session, l.read_only) + } + Err(e) => return fail(e.code, &e.to_string()), + }, + None => (Session::new(), false), + }; + let line = parts.join(" "); + let result = session.exec_line(&line); + // Save even after an error: tokens before the failing one stay applied. + if let (Some(n), false) = (&state_name, read_only) { + if let Err(e) = state::save(n, &session) { + return fail(e.code, &e.to_string()); + } + } + if let Err(e) = result { + return fail(e.code, &e.to_string()); + } + if json { + println!("{}", session.to_json()); + } else if show_stack { + println!("{}", session.stack_text()); + } else { + println!("{}", session.display_x()); + } + 0 +} + fn cli_clean(uninstall: bool, dry_run: bool, silent: bool, json: bool) -> i32 { let action = if uninstall { "uninstall" } else { "clean" }; let note = "Program files are not removed: use the installer's uninstaller, or delete the portable folder."; diff --git a/src/paths.rs b/src/paths.rs index 36651c3..3b211d7 100644 --- a/src/paths.rs +++ b/src/paths.rs @@ -376,11 +376,25 @@ pub fn atomic_write(path: &Path, contents: &[u8]) -> std::io::Result<()> { /// `dir`: exactly the app's known files that exist there. Pure — /// touches nothing. pub fn purge_candidates(dir: &Path) -> Vec<PathBuf> { - KNOWN_FILES + let mut out: Vec<PathBuf> = KNOWN_FILES .iter() .map(|name| dir.join(name)) .filter(|p| p.exists()) - .collect() + .collect(); + // RPN states (`rpn-<name>.txt`) and quarantined copies (`.txt.bad`). + if let Ok(rd) = std::fs::read_dir(dir) { + let mut extra: Vec<PathBuf> = rd + .flatten() + .filter(|e| { + let n = e.file_name().to_string_lossy().to_string(); + n.starts_with("rpn-") && (n.ends_with(".txt") || n.ends_with(".txt.bad")) + }) + .map(|e| e.path()) + .collect(); + extra.sort(); + out.extend(extra); + } + out } #[cfg(all(test, windows))] diff --git a/src/rpn/display.rs b/src/rpn/display.rs new file mode 100644 index 0000000..287cfb9 --- /dev/null +++ b/src/rpn/display.rs @@ -0,0 +1,121 @@ +//! Display formats: FIX / SCI / ENG / ALL (HP-42S style). +//! Pure functions; never panic on any f64. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Disp { + Fix(u8), + Sci(u8), + Eng(u8), + All, +} + +impl Disp { + pub fn label(self) -> String { + match self { + Disp::Fix(n) => format!("FIX {n}"), + Disp::Sci(n) => format!("SCI {n}"), + Disp::Eng(n) => format!("ENG {n}"), + Disp::All => "ALL".to_string(), + } + } + pub fn to_file(self) -> String { + match self { + Disp::Fix(n) => format!("FIX:{n}"), + Disp::Sci(n) => format!("SCI:{n}"), + Disp::Eng(n) => format!("ENG:{n}"), + Disp::All => "ALL".to_string(), + } + } + pub fn from_file(s: &str) -> Option<Disp> { + if s == "ALL" { + return Some(Disp::All); + } + let (k, n) = s.split_once(':')?; + let n: u8 = n.parse().ok().filter(|n| *n <= 11)?; + match k { + "FIX" => Some(Disp::Fix(n)), + "SCI" => Some(Disp::Sci(n)), + "ENG" => Some(Disp::Eng(n)), + _ => None, + } + } +} + +/// Split `{:.*e}` output into (negative, digit string, exponent). +fn sci_parts(x: f64, decimals: usize) -> (bool, String, i32) { + let s = format!("{:.*e}", decimals, x.abs()); + let (m, e) = s.split_once('e').unwrap_or((&s, "0")); + let digits: String = m.chars().filter(|c| c.is_ascii_digit()).collect(); + ( + x.is_sign_negative() && x != 0.0, + digits, + e.parse().unwrap_or(0), + ) +} + +/// Place the decimal point: digits d0 d1 ... with value d0.d1... * 10^e. +/// `int_digits` is how many digits sit left of the point. +fn place_point(digits: &str, int_digits: i32) -> String { + if int_digits <= 0 { + let zeros = "0".repeat((-int_digits) as usize); + return format!("0.{zeros}{digits}"); + } + let k = int_digits as usize; + if digits.len() <= k { + let pad = "0".repeat(k - digits.len()); + format!("{digits}{pad}") + } else { + format!("{}.{}", &digits[..k], &digits[k..]) + } +} + +fn fix(x: f64, n: u8) -> String { + if x != 0.0 && x.abs() >= 1e12 { + return sci(x, n.min(11)); + } + let s = format!("{:.*}", n as usize, x); + if s.starts_with('-') && s.chars().all(|c| !c.is_ascii_digit() || c == '0') { + return s[1..].to_string(); + } + s +} + +fn sci(x: f64, n: u8) -> String { + let (neg, digits, e) = sci_parts(x, n as usize); + let m = place_point(&digits, 1); + format!("{}{}E{}", if neg { "-" } else { "" }, m, e) +} + +fn eng(x: f64, n: u8) -> String { + let (neg, digits, e) = sci_parts(x, n as usize); + let e3 = e - e.rem_euclid(3); + let m = place_point(&digits, 1 + e - e3); + format!("{}{}E{}", if neg { "-" } else { "" }, m, e3) +} + +fn all(x: f64) -> String { + let (neg, digits, e) = sci_parts(x, 11); + let trimmed = digits.trim_end_matches('0'); + let digits = if trimmed.is_empty() { "0" } else { trimmed }; + let sign = if neg { "-" } else { "" }; + if x == 0.0 { + return "0".to_string(); + } + if (-5..=11).contains(&e) { + format!("{sign}{}", place_point(digits, e + 1)) + } else { + format!("{sign}{}E{}", place_point(digits, 1), e) + } +} + +pub fn format_num(x: f64, d: Disp) -> String { + if !x.is_finite() { + return "Out of Range".to_string(); + } + match d { + Disp::Fix(n) => fix(x, n), + Disp::Sci(n) => sci(x, n), + Disp::Eng(n) => eng(x, n), + Disp::All => all(x), + } +} diff --git a/src/rpn/mod.rs b/src/rpn/mod.rs new file mode 100644 index 0000000..97b657c --- /dev/null +++ b/src/rpn/mod.rs @@ -0,0 +1,598 @@ +//! RPN / programmable mode — P1: the HP-42S-style stack machine. +//! +//! Clean-room (see docs/RPN_PLAN.md): behaviour comes from the +//! published HP-42S manual and public Free42 docs, not upstream +//! source. Numbers are f64 for now (Free42 "Binary" equivalent); +//! P2 swaps in 34-digit decimal. +//! +//! Errors never panic: every failure is an `RpnError` with a stable +//! code and plain-words message, and a failing operation leaves the +//! stack untouched. + +pub mod display; +pub mod state; + +use display::{format_num, Disp}; +use std::collections::BTreeMap; +use std::f64::consts::{PI, TAU}; +use std::fmt; + +/// Upper bounds (memory / runtime caps, AGENTS.md). +pub const MAX_VARS: usize = 1000; +pub const MAX_TOKENS: usize = 100_000; +pub const MAX_NAME_LEN: usize = 32; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Angle { + Deg, + Rad, + Grad, +} + +impl Angle { + pub fn label(self) -> &'static str { + match self { + Angle::Deg => "DEG", + Angle::Rad => "RAD", + Angle::Grad => "GRAD", + } + } + pub fn from_label(s: &str) -> Option<Angle> { + match s { + "DEG" => Some(Angle::Deg), + "RAD" => Some(Angle::Rad), + "GRAD" => Some(Angle::Grad), + _ => None, + } + } + /// Units in a full circle. + fn full(self) -> f64 { + match self { + Angle::Deg => 360.0, + Angle::Rad => TAU, + Angle::Grad => 400.0, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RpnError { + pub code: &'static str, + pub msg: String, +} + +impl RpnError { + pub fn new(code: &'static str, msg: impl Into<String>) -> Self { + RpnError { + code, + msg: msg.into(), + } + } +} + +impl fmt::Display for RpnError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} [{}]", self.msg, self.code) + } +} + +fn invalid() -> RpnError { + RpnError::new( + "RPN-102", + "Invalid Data: the function is not defined for this value.", + ) +} +fn div0() -> RpnError { + RpnError::new("RPN-103", "Divide by 0.") +} +fn range() -> RpnError { + RpnError::new( + "RPN-104", + "Out of Range: the result is too large to represent.", + ) +} + +pub fn valid_var_name(name: &str) -> bool { + !name.is_empty() + && name.chars().count() <= MAX_NAME_LEN + && !name.chars().any(|c| c == '|' || c.is_control()) +} + +fn finite(x: f64) -> Result<f64, RpnError> { + if x.is_finite() { + Ok(x) + } else { + Err(range()) + } +} + +#[derive(Clone, Debug)] +pub struct Session { + /// stack[0] = X, 1 = Y, 2 = Z, 3 = T. + pub stack: [f64; 4], + pub lastx: f64, + /// Stack lift enabled (a number entry lifts the stack). + pub lift: bool, + pub angle: Angle, + pub disp: Disp, + pub vars: BTreeMap<String, f64>, +} + +impl Default for Session { + fn default() -> Self { + Self::new() + } +} + +struct Tok { + text: String, + quoted: bool, +} + +fn tokenize(line: &str) -> Result<Vec<Tok>, RpnError> { + let mut out = Vec::new(); + let mut chars = line.chars().peekable(); + while let Some(&c) = chars.peek() { + if c.is_whitespace() { + chars.next(); + } else if c == '"' { + chars.next(); + let mut s = String::new(); + let mut closed = false; + for ch in chars.by_ref() { + if ch == '"' { + closed = true; + break; + } + s.push(ch); + } + if !closed { + return Err(RpnError::new( + "RPN-108", + "A quoted name is missing its closing quote.", + )); + } + out.push(Tok { + text: s, + quoted: true, + }); + } else { + let mut s = String::new(); + while let Some(&ch) = chars.peek() { + if ch.is_whitespace() { + break; + } + s.push(ch); + chars.next(); + } + out.push(Tok { + text: s, + quoted: false, + }); + } + if out.len() > MAX_TOKENS { + return Err(RpnError::new("RPN-109", "Too many tokens in one line.")); + } + } + Ok(out) +} + +/// A number token: digits with optional sign, point and exponent. +/// Rejects words like "inf" / "nan" that Rust's parser would accept. +fn parse_number(t: &str) -> Option<f64> { + let b = t.as_bytes(); + let first = *b.first()?; + let starts_ok = first.is_ascii_digit() + || first == b'.' + || ((first == b'-' || first == b'+') + && b.get(1).is_some_and(|c| c.is_ascii_digit() || *c == b'.')); + if !starts_ok + || !t + .bytes() + .all(|c| c.is_ascii_digit() || b".+-eE".contains(&c)) + { + return None; + } + t.parse::<f64>().ok().filter(|v| v.is_finite()) +} + +fn to_angle_units(rad: f64, a: Angle) -> f64 { + rad * a.full() / TAU +} + +/// Exact results at quarter-turn multiples (sin 180° = 0, not 1.2e-16). +fn quarter(x: f64, a: Angle) -> Option<i64> { + let q = x / a.full() * 4.0; + if q.fract() == 0.0 && q.abs() < 1e15 { + Some((q as i64).rem_euclid(4)) + } else { + None + } +} + +fn sin_a(x: f64, a: Angle) -> f64 { + match quarter(x, a) { + Some(k) => [0.0, 1.0, 0.0, -1.0][k as usize], + None => (x * TAU / a.full()).sin(), + } +} +fn cos_a(x: f64, a: Angle) -> f64 { + match quarter(x, a) { + Some(k) => [1.0, 0.0, -1.0, 0.0][k as usize], + None => (x * TAU / a.full()).cos(), + } +} +fn tan_a(x: f64, a: Angle) -> Result<f64, RpnError> { + match quarter(x, a) { + Some(k) if k % 2 == 0 => Ok(0.0), + Some(_) => Err(invalid()), + None => Ok((x * TAU / a.full()).tan()), + } +} + +fn is_int(x: f64) -> bool { + x.fract() == 0.0 +} + +fn fact(x: f64) -> Result<f64, RpnError> { + if !is_int(x) || x < 0.0 { + return Err(invalid()); + } + if x > 170.0 { + return Err(range()); + } + let mut r = 1.0f64; + let mut i = 2.0; + while i <= x { + r *= i; + i += 1.0; + } + Ok(r) +} + +fn comb_perm(n: f64, k: f64, perm: bool) -> Result<f64, RpnError> { + if !is_int(n) || !is_int(k) || n < 0.0 || k < 0.0 || k > n { + return Err(invalid()); + } + let steps = if perm { k } else { k.min(n - k) }; + if steps > 1.0e6 { + return Err(range()); + } + let mut r = 1.0f64; + let mut i = 0.0; + while i < steps { + r = if perm { + r * (n - i) + } else { + r * (n - i) / (i + 1.0) + }; + i += 1.0; + } + finite(if perm { r } else { r.round() }) +} + +impl Session { + pub fn new() -> Self { + Session { + stack: [0.0; 4], + lastx: 0.0, + lift: true, + angle: Angle::Deg, + disp: Disp::Fix(4), + vars: BTreeMap::new(), + } + } + + pub fn x(&self) -> f64 { + self.stack[0] + } + + pub fn display_x(&self) -> String { + format_num(self.stack[0], self.disp) + } + + /// Four lines, T first, X last. + pub fn stack_text(&self) -> String { + ["T", "Z", "Y", "X"] + .iter() + .zip([3usize, 2, 1, 0]) + .map(|(n, i)| format!("{n}: {}", format_num(self.stack[i], self.disp))) + .collect::<Vec<_>>() + .join("\n") + } + + pub fn to_json(&self) -> String { + let f = |i: usize| format!("\"{}\"", format_num(self.stack[i], self.disp)); + format!( + "{{\"ok\":true,\"x\":{},\"y\":{},\"z\":{},\"t\":{},\"lastx\":\"{}\",\"angle\":\"{}\",\"disp\":\"{}\"}}", + f(0), + f(1), + f(2), + f(3), + format_num(self.lastx, self.disp), + self.angle.label(), + self.disp.label() + ) + } + + fn push_value(&mut self, x: f64) { + if self.lift { + self.stack[3] = self.stack[2]; + self.stack[2] = self.stack[1]; + self.stack[1] = self.stack[0]; + } + self.stack[0] = x; + self.lift = true; + } + + fn unary( + &mut self, + f: impl FnOnce(f64, Angle) -> Result<f64, RpnError>, + ) -> Result<(), RpnError> { + let x = self.stack[0]; + let r = finite(f(x, self.angle)?)?; + self.lastx = x; + self.stack[0] = r; + self.lift = true; + Ok(()) + } + + fn binary( + &mut self, + f: impl FnOnce(f64, f64) -> Result<f64, RpnError>, + ) -> Result<(), RpnError> { + let (y, x) = (self.stack[1], self.stack[0]); + let r = finite(f(y, x)?)?; + self.lastx = x; + self.stack[0] = r; + self.stack[1] = self.stack[2]; + self.stack[2] = self.stack[3]; + self.lift = true; + Ok(()) + } + + fn name_arg(toks: &[Tok], i: &mut usize, cmd: &str) -> Result<String, RpnError> { + let t = toks.get(*i).ok_or_else(|| { + RpnError::new( + "RPN-101", + format!("{cmd} needs a name or register number after it."), + ) + })?; + *i += 1; + if !valid_var_name(&t.text) { + return Err(RpnError::new( + "RPN-101", + format!( + "'{}' is not a valid name (1-{MAX_NAME_LEN} characters, no '|').", + t.text + ), + )); + } + Ok(t.text.clone()) + } + + fn digits_arg(toks: &[Tok], i: &mut usize, cmd: &str) -> Result<u8, RpnError> { + let t = toks.get(*i).ok_or_else(|| { + RpnError::new( + "RPN-101", + format!("{cmd} needs a digit count 0-11 after it."), + ) + })?; + *i += 1; + match t.text.parse::<u8>() { + Ok(n) if n <= 11 => Ok(n), + _ => Err(RpnError::new( + "RPN-102", + format!("{cmd} takes a whole number from 0 to 11, not '{}'.", t.text), + )), + } + } + + fn store(&mut self, name: String, v: f64) -> Result<(), RpnError> { + if !self.vars.contains_key(&name) && self.vars.len() >= MAX_VARS { + return Err(RpnError::new("RPN-110", "Too many variables.")); + } + self.vars.insert(name, finite(v)?); + Ok(()) + } + + fn var(&self, name: &str) -> Result<f64, RpnError> { + self.vars.get(name).copied().ok_or_else(|| { + RpnError::new( + "RPN-105", + format!("Nonexistent: no variable named '{name}'."), + ) + }) + } + + fn arith(op: char, a: f64, b: f64) -> Result<f64, RpnError> { + match op { + '+' => Ok(a + b), + '-' => Ok(a - b), + '*' => Ok(a * b), + _ => { + if b == 0.0 { + Err(div0()) + } else { + Ok(a / b) + } + } + } + } + + /// Run one line of tokens. On error the failing operation has + /// changed nothing; earlier tokens in the line stay applied. + pub fn exec_line(&mut self, line: &str) -> Result<(), RpnError> { + let toks = tokenize(line)?; + let mut i = 0; + while i < toks.len() { + let t = &toks[i]; + i += 1; + if !t.quoted { + if let Some(n) = parse_number(&t.text) { + self.push_value(n); + continue; + } + } else { + return Err(RpnError::new( + "RPN-100", + format!( + "Unexpected name \"{}\": names follow STO, RCL, CLV and friends.", + t.text + ), + )); + } + let w = t.text.to_uppercase(); + match w.as_str() { + "+" => self.binary(|y, x| finite(y + x))?, + "-" => self.binary(|y, x| Ok(y - x))?, + "*" | "×" => self.binary(|y, x| Ok(y * x))?, + "/" | "÷" => self.binary(|y, x| if x == 0.0 { Err(div0()) } else { Ok(y / x) })?, + "Y^X" => self.binary(|y, x| { + if y == 0.0 && x < 0.0 { + Err(div0()) + } else if y < 0.0 && !is_int(x) { + Err(invalid()) + } else { + Ok(y.powf(x)) + } + })?, + "MOD" => self.binary(|y, x| if x == 0.0 { Err(div0()) } else { Ok(y - x * (y / x).floor()) })?, + "COMB" => self.binary(|y, x| comb_perm(y, x, false))?, + "PERM" => self.binary(|y, x| comb_perm(y, x, true))?, + "%" => { + let (y, x) = (self.stack[1], self.stack[0]); + let r = finite(y * x / 100.0)?; + self.lastx = x; + self.stack[0] = r; + self.lift = true; + } + "%CH" => { + let (y, x) = (self.stack[1], self.stack[0]); + if y == 0.0 { + return Err(div0()); + } + let r = finite((x - y) / y * 100.0)?; + self.lastx = x; + self.stack[0] = r; + self.lift = true; + } + "1/X" => self.unary(|x, _| if x == 0.0 { Err(div0()) } else { Ok(1.0 / x) })?, + "X^2" => self.unary(|x, _| Ok(x * x))?, + "SQRT" | "√X" => self.unary(|x, _| if x < 0.0 { Err(invalid()) } else { Ok(x.sqrt()) })?, + "E^X" => self.unary(|x, _| Ok(x.exp()))?, + "10^X" => self.unary(|x, _| Ok(10f64.powf(x)))?, + "E^X-1" => self.unary(|x, _| Ok(x.exp_m1()))?, + "LN" => self.unary(|x, _| if x <= 0.0 { Err(invalid()) } else { Ok(x.ln()) })?, + "LOG" => self.unary(|x, _| if x <= 0.0 { Err(invalid()) } else { Ok(x.log10()) })?, + "LN1+X" => self.unary(|x, _| if x <= -1.0 { Err(invalid()) } else { Ok(x.ln_1p()) })?, + "ABS" => self.unary(|x, _| Ok(x.abs()))?, + "CHS" | "+/-" => self.unary(|x, _| Ok(-x))?, + "IP" => self.unary(|x, _| Ok(x.trunc()))?, + "FP" => self.unary(|x, _| Ok(x.fract()))?, + "FACT" => self.unary(|x, _| fact(x))?, + "SIN" => self.unary(|x, a| Ok(sin_a(x, a)))?, + "COS" => self.unary(|x, a| Ok(cos_a(x, a)))?, + "TAN" => self.unary(tan_a)?, + "ASIN" => self.unary(|x, a| { + if x.abs() > 1.0 { + Err(invalid()) + } else { + Ok(to_angle_units(x.asin(), a)) + } + })?, + "ACOS" => self.unary(|x, a| { + if x.abs() > 1.0 { + Err(invalid()) + } else { + Ok(to_angle_units(x.acos(), a)) + } + })?, + "ATAN" => self.unary(|x, a| Ok(to_angle_units(x.atan(), a)))?, + "SINH" => self.unary(|x, _| Ok(x.sinh()))?, + "COSH" => self.unary(|x, _| Ok(x.cosh()))?, + "TANH" => self.unary(|x, _| Ok(x.tanh()))?, + "ASINH" => self.unary(|x, _| Ok(x.asinh()))?, + "ACOSH" => self.unary(|x, _| if x < 1.0 { Err(invalid()) } else { Ok(x.acosh()) })?, + "ATANH" => self.unary(|x, _| if x.abs() >= 1.0 { Err(invalid()) } else { Ok(x.atanh()) })?, + "D-R" | "→RAD" => self.unary(|x, _| Ok(x.to_radians()))?, + "R-D" | "→DEG" => self.unary(|x, _| Ok(x.to_degrees()))?, + "PI" | "π" => self.push_value(PI), + "LASTX" => { + let l = self.lastx; + self.push_value(l); + } + "ENTER" | "ENTER^" | "↑" => { + self.stack[3] = self.stack[2]; + self.stack[2] = self.stack[1]; + self.stack[1] = self.stack[0]; + self.lift = false; + } + "CLX" => { + self.stack[0] = 0.0; + self.lift = false; + } + "CLST" => { + self.stack = [0.0; 4]; + self.lift = false; + } + "X<>Y" | "SWAP" => { + self.stack.swap(0, 1); + self.lift = true; + } + "RDN" | "R↓" => { + self.stack.rotate_left(1); + self.lift = true; + } + "RUP" | "R↑" => { + self.stack.rotate_right(1); + self.lift = true; + } + "DEG" => self.angle = Angle::Deg, + "RAD" => self.angle = Angle::Rad, + "GRAD" => self.angle = Angle::Grad, + "ALL" => self.disp = Disp::All, + "FIX" => self.disp = Disp::Fix(Self::digits_arg(&toks, &mut i, "FIX")?), + "SCI" => self.disp = Disp::Sci(Self::digits_arg(&toks, &mut i, "SCI")?), + "ENG" => self.disp = Disp::Eng(Self::digits_arg(&toks, &mut i, "ENG")?), + "STO" => { + let n = Self::name_arg(&toks, &mut i, "STO")?; + self.store(n, self.stack[0])?; + } + "RCL" => { + let n = Self::name_arg(&toks, &mut i, "RCL")?; + let v = self.var(&n)?; + self.push_value(v); + } + "CLV" => { + let n = Self::name_arg(&toks, &mut i, "CLV")?; + self.var(&n)?; + self.vars.remove(&n); + } + "STO+" | "STO-" | "STO*" | "STO/" => { + let op = w.chars().nth(3).unwrap_or('+'); + let n = Self::name_arg(&toks, &mut i, &w)?; + let v = Self::arith(op, self.var(&n)?, self.stack[0])?; + self.store(n, v)?; + } + "RCL+" | "RCL-" | "RCL*" | "RCL/" => { + let op = w.chars().nth(3).unwrap_or('+'); + let n = Self::name_arg(&toks, &mut i, &w)?; + let v = self.var(&n)?; + let x = self.stack[0]; + let r = finite(Self::arith(op, x, v)?)?; + self.lastx = x; + self.stack[0] = r; + self.lift = true; + } + _ => { + return Err(RpnError::new( + "RPN-100", + format!("Unknown token '{}'. Numbers, operators and HP-42S names such as ENTER, SIN, STO are accepted.", t.text), + )) + } + } + } + Ok(()) + } +} diff --git a/src/rpn/state.rs b/src/rpn/state.rs new file mode 100644 index 0000000..122bd4e --- /dev/null +++ b/src/rpn/state.rs @@ -0,0 +1,190 @@ +//! Versioned, atomic state file for the RPN session. +//! Format (text, `schema_version=1`): angle, disp, lift, stack, lastx, var lines. + +use super::display::Disp; +use super::{Angle, RpnError, Session, MAX_VARS}; +use crate::paths::{atomic_write, data_file}; + +pub const STATE_SCHEMA_VERSION: u32 = 1; + +pub fn valid_state_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 32 + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +pub fn state_file_name(name: &str) -> String { + format!("rpn-{name}.txt") +} + +pub fn serialize(s: &Session) -> String { + let mut out = format!("schema_version={STATE_SCHEMA_VERSION}\n"); + out.push_str(&format!("angle={}\n", s.angle.label())); + out.push_str(&format!("disp={}\n", s.disp.to_file())); + out.push_str(&format!("lift={}\n", u8::from(s.lift))); + out.push_str(&format!( + "stack={:e}|{:e}|{:e}|{:e}\n", + s.stack[0], s.stack[1], s.stack[2], s.stack[3] + )); + out.push_str(&format!("lastx={:e}\n", s.lastx)); + for (k, v) in &s.vars { + out.push_str(&format!("var={k}|{v:e}\n")); + } + out +} + +pub enum ParseOutcome { + Ok(Box<Session>), + /// Written by a newer CalcDex: must not be overwritten. + Newer(u32), + Bad(String), +} + +fn num(s: &str) -> Option<f64> { + s.parse::<f64>().ok().filter(|v| v.is_finite()) +} + +pub fn parse(text: &str) -> ParseOutcome { + let mut s = Session::new(); + let mut version: Option<u32> = None; + let mut seen_stack = false; + for (i, line) in text.lines().enumerate() { + let line = line.trim_end_matches('\r'); + if line.is_empty() { + continue; + } + let Some((k, v)) = line.split_once('=') else { + return ParseOutcome::Bad(format!("line {} has no '='", i + 1)); + }; + match k { + "schema_version" => match v.parse::<u32>() { + Ok(n) => version = Some(n), + Err(_) => return ParseOutcome::Bad("bad schema_version".into()), + }, + "angle" => match Angle::from_label(v) { + Some(a) => s.angle = a, + None => return ParseOutcome::Bad(format!("bad angle '{v}'")), + }, + "disp" => match Disp::from_file(v) { + Some(d) => s.disp = d, + None => return ParseOutcome::Bad(format!("bad disp '{v}'")), + }, + "lift" => s.lift = v == "1", + "stack" => { + let parts: Vec<&str> = v.split('|').collect(); + if parts.len() != 4 { + return ParseOutcome::Bad("stack needs 4 values".into()); + } + for (j, p) in parts.iter().enumerate() { + match num(p) { + Some(x) => s.stack[j] = x, + None => return ParseOutcome::Bad(format!("bad stack value '{p}'")), + } + } + seen_stack = true; + } + "lastx" => match num(v) { + Some(x) => s.lastx = x, + None => return ParseOutcome::Bad("bad lastx".into()), + }, + "var" => { + let Some((name, val)) = v.rsplit_once('|') else { + return ParseOutcome::Bad("var line needs name|value".into()); + }; + let Some(x) = num(val) else { + return ParseOutcome::Bad(format!("bad value for variable '{name}'")); + }; + if !super::valid_var_name(name) || s.vars.len() >= MAX_VARS { + return ParseOutcome::Bad(format!("bad variable '{name}'")); + } + s.vars.insert(name.to_string(), x); + } + _ => {} // unknown keys from a same-version writer are ignored + } + } + match version { + Some(n) if n > STATE_SCHEMA_VERSION => ParseOutcome::Newer(n), + Some(_) if seen_stack => ParseOutcome::Ok(Box::new(s)), + Some(_) => ParseOutcome::Bad("no stack line".into()), + None => ParseOutcome::Bad("no schema_version line".into()), + } +} + +pub struct Loaded { + pub session: Session, + pub note: Option<String>, + /// True when the file must not be written back (newer version). + pub read_only: bool, +} + +/// Load named state from the data folder. Missing file = fresh +/// session. Unparseable file is quarantined (renamed `.bad`), never +/// silently reset. +pub fn load(name: &str) -> Result<Loaded, RpnError> { + if !valid_state_name(name) { + return Err(RpnError::new( + "RPN-106", + "State names use letters, digits, '_' and '-' (max 32).", + )); + } + let path = data_file(&state_file_name(name)); + let text = match std::fs::read_to_string(&path) { + Ok(t) => t, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Ok(Loaded { + session: Session::new(), + note: None, + read_only: false, + }) + } + Err(e) => { + return Err(RpnError::new( + "RPN-107", + format!("Cannot read state '{name}': {e}"), + )) + } + }; + match parse(&text) { + ParseOutcome::Ok(s) => Ok(Loaded { + session: *s, + note: None, + read_only: false, + }), + ParseOutcome::Newer(n) => Ok(Loaded { + session: Session::new(), + note: Some(format!( + "State '{name}' was written by a newer CalcDex (schema {n}); using defaults and not overwriting it." + )), + read_only: true, + }), + ParseOutcome::Bad(why) => { + let bad = path.with_extension("txt.bad"); + let moved = std::fs::rename(&path, &bad).is_ok(); + Ok(Loaded { + session: Session::new(), + note: Some(format!( + "State '{name}' could not be read ({why}); {} Starting fresh.", + if moved { + "the file was kept as a .bad copy." + } else { + "it could not be moved aside." + } + )), + read_only: false, + }) + } + } +} + +pub fn save(name: &str, s: &Session) -> Result<(), RpnError> { + if !valid_state_name(name) { + return Err(RpnError::new( + "RPN-106", + "State names use letters, digits, '_' and '-' (max 32).", + )); + } + atomic_write(&data_file(&state_file_name(name)), serialize(s).as_bytes()) + .map_err(|e| RpnError::new("RPN-107", format!("Cannot save state '{name}': {e}"))) +} diff --git a/tests/rpn_p1.rs b/tests/rpn_p1.rs new file mode 100644 index 0000000..365c374 --- /dev/null +++ b/tests/rpn_p1.rs @@ -0,0 +1,267 @@ +//! RPN P1: stack machine, display formats, errors, state file. + +use calcdex::rpn::display::{format_num, Disp}; +use calcdex::rpn::state::{self, ParseOutcome}; +use calcdex::rpn::{Angle, Session}; + +fn run(line: &str) -> Session { + let mut s = Session::new(); + s.exec_line(line).unwrap_or_else(|e| panic!("{line}: {e}")); + s +} + +fn x(line: &str) -> f64 { + run(line).x() +} + +fn err(line: &str) -> String { + let mut s = Session::new(); + s.exec_line(line).unwrap_err().code.to_string() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() <= 1e-12 * b.abs().max(1.0) +} + +#[test] +fn basic_arithmetic_and_order() { + assert_eq!(x("2 3 + 4 *"), 20.0); + assert_eq!(x("10 4 -"), 6.0); // Y - X + assert_eq!(x("20 4 /"), 5.0); + assert_eq!(x("2 10 Y^X"), 1024.0); + assert_eq!(x("1.5e-3 2 *"), 3e-3); + assert_eq!(x("-3 ABS"), 3.0); + assert_eq!(x("5 CHS"), -5.0); + assert_eq!(x("7 3 MOD"), 1.0); + assert_eq!(x("-7 3 MOD"), 2.0); // sign of divisor +} + +#[test] +fn stack_lift_enter_and_drop() { + let s = run("1 2 3 4"); + assert_eq!(s.stack, [4.0, 3.0, 2.0, 1.0]); + // fifth entry pushes 1 off the top + assert_eq!(run("1 2 3 4 5").stack, [5.0, 4.0, 3.0, 2.0]); + // ENTER disables lift: next number replaces X + let s = run("5 ENTER 3"); + assert_eq!(s.stack[..2], [3.0, 5.0]); + // binary op drops the stack, T duplicates + let s = run("1 2 3 4 + "); + assert_eq!(s.stack, [7.0, 2.0, 1.0, 1.0]); + assert_eq!(run("1 2 3 4 RDN").stack, [3.0, 2.0, 1.0, 4.0]); + assert_eq!(run("1 2 3 4 RDN RUP").stack, [4.0, 3.0, 2.0, 1.0]); + assert_eq!(run("1 2 X<>Y").stack[..2], [1.0, 2.0]); + assert_eq!(run("1 2 3 CLX").stack[0], 0.0); + assert_eq!(run("1 2 3 CLST").stack, [0.0; 4]); +} + +#[test] +fn lastx_and_percent() { + assert_eq!(x("6 3 / LASTX"), 3.0); + let s = run("200 15 %"); + assert_eq!(s.stack[..2], [30.0, 200.0]); // Y kept + assert!(close(x("50 60 %CH"), 20.0)); + assert!(close(x("3 4 SQRT LASTX +"), 6.0)); // 3, sqrt(4)=2, lastx 4 -> 2+4 +} + +#[test] +fn scientific_functions() { + assert!(close(x("2 SQRT"), 2f64.sqrt())); + assert_eq!(x("4 X^2"), 16.0); + assert_eq!(x("4 1/X"), 0.25); + assert!(close(x("1 E^X"), std::f64::consts::E)); + assert_eq!(x("3 10^X"), 1000.0); + assert!(close(x("100 LOG"), 2.0)); + assert!(close(x("1 E^X LN"), 1.0)); + assert!(close(x("PI"), std::f64::consts::PI)); + assert_eq!(x("5 FACT"), 120.0); + assert_eq!(x("0 FACT"), 1.0); + assert_eq!(x("5 2 COMB"), 10.0); + assert_eq!(x("5 2 PERM"), 20.0); + assert_eq!(x("-3.7 IP"), -3.0); + assert!(close(x("3.75 FP"), 0.75)); + assert!(close(x("0 COSH"), 1.0)); + assert!(close(x("1 TANH ATANH"), 1.0)); +} + +#[test] +fn angle_modes_and_exact_quarters() { + assert_eq!(x("180 SIN"), 0.0); + assert_eq!(x("90 SIN"), 1.0); + assert_eq!(x("90 COS"), 0.0); + assert_eq!(x("270 SIN"), -1.0); + assert_eq!(x("-90 SIN"), -1.0); + assert!(close(x("45 TAN"), 1.0)); + assert!(close(x("1 ASIN"), 90.0)); + assert!(close(x("RAD 1 ASIN"), std::f64::consts::FRAC_PI_2)); + assert_eq!(x("GRAD 100 SIN"), 1.0); + assert!(close(x("GRAD 1 ASIN"), 100.0)); + assert_eq!(run("RAD").angle, Angle::Rad); + assert!(close(x("180 D-R"), std::f64::consts::PI)); + assert!(close(x("PI R-D"), 180.0)); +} + +#[test] +fn errors_have_codes_and_change_nothing() { + assert_eq!(err("1 0 /"), "RPN-103"); + assert_eq!(err("0 1/X"), "RPN-103"); + assert_eq!(err("-1 SQRT"), "RPN-102"); + assert_eq!(err("0 LN"), "RPN-102"); + assert_eq!(err("2 ASIN"), "RPN-102"); + assert_eq!(err("90 TAN"), "RPN-102"); + assert_eq!(err("1.5 FACT"), "RPN-102"); + assert_eq!(err("171 FACT"), "RPN-104"); + assert_eq!(err("1e308 10 *"), "RPN-104"); + assert_eq!(err("FOO"), "RPN-100"); + assert_eq!(err("inf"), "RPN-100"); + assert_eq!(err("nan"), "RPN-100"); + assert_eq!(err("STO"), "RPN-101"); + assert_eq!(err("RCL \"nothing\""), "RPN-105"); + assert_eq!(err("FIX 12"), "RPN-102"); + assert_eq!(err("RCL \"unterminated"), "RPN-108"); + // failing op leaves the stack as it was + let mut s = Session::new(); + s.exec_line("4 0").unwrap(); + assert!(s.exec_line("/").is_err()); + assert_eq!(s.stack[..2], [0.0, 4.0]); +} + +#[test] +fn variables_and_storage_arithmetic() { + let s = run("12 STO \"A\" 3 STO 01 RCL \"A\" RCL 01 +"); + assert_eq!(s.x(), 15.0); + assert_eq!(run("10 STO A 4 STO+ A RCL A").x(), 14.0); + assert_eq!(run("10 STO A 4 STO- A RCL A").x(), 6.0); + assert_eq!(run("10 STO A 4 STO* A RCL A").x(), 40.0); + assert_eq!(run("8 STO A 4 STO/ A RCL A").x(), 2.0); + assert_eq!(run("3 STO A 10 RCL+ A").x(), 13.0); + assert_eq!(run("3 STO A 10 RCL- A").x(), 7.0); + assert_eq!(run("3 STO A 10 RCL* A").x(), 30.0); + assert_eq!(run("2 STO A 10 RCL/ A").x(), 5.0); + assert_eq!(err("1 STO A 0 STO/ A"), "RPN-103"); + let s = run("1 STO A CLV A"); + assert!(s.vars.is_empty()); + assert_eq!(err("CLV A"), "RPN-105"); + assert_eq!(err("1 STO \"a|b\""), "RPN-101"); +} + +#[test] +fn display_formats() { + assert_eq!(format_num(7.12345678, Disp::Fix(4)), "7.1235"); + assert_eq!(format_num(-0.00001, Disp::Fix(4)), "0.0000"); + assert_eq!(format_num(12.0, Disp::Fix(0)), "12"); + assert_eq!(format_num(1234.5678, Disp::Sci(3)), "1.235E3"); + assert_eq!(format_num(0.00012345, Disp::Sci(2)), "1.23E-4"); + assert_eq!(format_num(0.0, Disp::Sci(2)), "0.00E0"); + assert_eq!(format_num(12345.678, Disp::Eng(2)), "12.3E3"); + assert_eq!(format_num(123.0, Disp::Eng(2)), "123E0"); + assert_eq!(format_num(0.0123, Disp::Eng(1)), "12E-3"); + assert_eq!(format_num(1.0 / 3.0, Disp::All), "0.333333333333"); + assert_eq!(format_num(2.0, Disp::All), "2"); + assert_eq!(format_num(-1234.5, Disp::All), "-1234.5"); + assert_eq!(format_num(1.5e-9, Disp::All), "1.5E-9"); + assert_eq!(format_num(1e20, Disp::All), "1E20"); + assert_eq!(format_num(1e15, Disp::Fix(2)), "1.00E15"); + assert_eq!(format_num(f64::NAN, Disp::All), "Out of Range"); +} + +#[test] +fn display_mode_tokens() { + assert_eq!(run("2 SQRT SCI 3").display_x(), "1.414E0"); + assert_eq!(run("2 SQRT FIX 2").display_x(), "1.41"); + assert_eq!(run("1234.5 ENG 2").display_x(), "1.23E3"); + assert_eq!(run("0.5 ALL").display_x(), "0.5"); +} + +#[test] +fn state_round_trip_exact() { + let mut s = run("1 3 / 2 SQRT STO \"A\" 1e-300 RAD SCI 5"); + s.exec_line("7 ENTER").unwrap(); + let text = state::serialize(&s); + assert!(text.starts_with("schema_version=1\n")); + match state::parse(&text) { + ParseOutcome::Ok(t) => { + assert_eq!(t.stack, s.stack); + assert_eq!(t.lastx, s.lastx); + assert_eq!(t.lift, s.lift); + assert_eq!(t.angle, s.angle); + assert_eq!(t.disp, s.disp); + assert_eq!(t.vars, s.vars); + } + _ => panic!("round trip failed"), + } +} + +#[test] +fn state_parse_rejects_bad_files() { + for bad in [ + "", + "stack=1|2|3|4\n", + "schema_version=1\n", + "schema_version=1\nstack=1|2|3\n", + "schema_version=1\nstack=1|2|3|nan\n", + "schema_version=1\nstack=0|0|0|0\nangle=TURN\n", + "schema_version=1\nstack=0|0|0|0\ndisp=FIX:99\n", + "schema_version=1\nstack=0|0|0|0\nvar=noval\n", + "schema_version=1\nstack=0|0|0|0\nvar=A|inf\n", + "garbage line\n", + ] { + assert!(matches!(state::parse(bad), ParseOutcome::Bad(_)), "{bad:?}"); + } + assert!(matches!( + state::parse("schema_version=2\nstack=0|0|0|0\n"), + ParseOutcome::Newer(2) + )); +} + +#[test] +fn state_file_load_save_quarantine_and_newer() { + let dir = std::env::temp_dir().join(format!("calcdex-rpn-p1-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::env::set_var("CALCDEX_DATA_DIR", &dir); + + assert!(state::load("a b").is_err()); // bad name + let l = state::load("t1").unwrap(); // missing = fresh + assert!(l.note.is_none() && !l.read_only); + + let mut s = l.session; + s.exec_line("42 STO \"V\" 9").unwrap(); + state::save("t1", &s).unwrap(); + let l = state::load("t1").unwrap(); + assert_eq!(l.session.x(), 9.0); + assert_eq!(l.session.vars.get("V"), Some(&42.0)); + + // corrupt file is moved aside, not lost + let p = dir.join("rpn-t2.txt"); + std::fs::write(&p, "not a state file").unwrap(); + let l = state::load("t2").unwrap(); + assert!(l.note.is_some() && !l.read_only); + assert!(!p.exists()); + assert!(dir.join("rpn-t2.txt.bad").exists()); + + // newer schema: defaults, read-only, file untouched + let p = dir.join("rpn-t3.txt"); + std::fs::write(&p, "schema_version=9\nstack=1|2|3|4\n").unwrap(); + let l = state::load("t3").unwrap(); + assert!(l.read_only && l.note.is_some()); + assert_eq!( + std::fs::read_to_string(&p).unwrap(), + "schema_version=9\nstack=1|2|3|4\n" + ); + + // --clean sees rpn files + let found = calcdex::paths::purge_candidates(&dir); + assert!(found.iter().any(|f| f.ends_with("rpn-t1.txt"))); + assert!(found.iter().any(|f| f.ends_with("rpn-t2.txt.bad"))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn runaway_input_is_bounded() { + let mut s = Session::new(); + let big = "1 ".repeat(100_001); + assert_eq!(s.exec_line(&big).unwrap_err().code, "RPN-109"); + let many: String = (0..1001).map(|i| format!("1 STO v{i} ")).collect(); + assert_eq!(s.exec_line(&many).unwrap_err().code, "RPN-110"); +}