calculator: replace M register with variable dropup
- Commit
d82a5ffe0ddb9e917e33738102c78f112368d323- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 13:51 UTC (21 hours ago)
- Parents
18988e3
The keypad carried a single M memory register (MC/MR/M+/M-) while the owner asked for a variable assigning system instead: type or pick a name such as x=, a= or z=, build the assignment with a literal equals sign, and submit it. What changed: - Port the multi-line variable engine that existed only on the agent-fix-654 branch (it was not on main): Expression gains named variables resolved at evaluation time, and CalculatorTab re-evaluates every history line in chronological order on each submit, so an assignment feeds later lines and editing an early line (long-press a history row) updates its dependents. Variables survive AC, as the old register did, and are shown above the input in both portrait and landscape readouts. - Remove the single memory register and its MC/MR/M+/M- keys, CalculatorActions memory methods, the uiState memory field and the M indicator. The variable row that replaces them holds a wide var key, the literal = key and the RAD/DEG key, so every keypad row still spans five columns. - Separate = from Enter, as the owner directed: the = key is a regular key in the top section and only appends the character (it never submits); the accent Enter key in the bottom-right position the old = key occupied submits the line. On submit, only a leading <name>=<expr> line assigns; a bare name reads its value and any other line evaluates as a plain expression. - The var key opens a dropup (the app's Button + DropdownMenu pattern, anchored to the key so it opens above the keypad) in the new CalculatorVariablePicker file (split out to keep CalculatorKeypad under the ui file-length lint). Rows list every assignable single letter, a-z except e (Euler's constant) -- the picker is not limited by the keypad's 2nd-layer letters, which still type a-k directly -- with current values, and insert just the name. Genuinely reserved names (e, multi-letter ans/pi/tau/phi/theta, functions, multi-letter unit tokens) can never be assigned. Single letters that also spell the graph free variable (x/t) or units (c/g/h/k/m/s) are assignable in the calculator tab: once assigned, the variable wins in variable position (assignment target, picker insertion, later references), while graph, widget and intent expressions -- which pass no known variables -- keep the original meaning. - Update screenshot preview fixtures and instrumented-test key constants for the Enter glyph, and document the system in calculator/AGENTS.md. Tests: test-first. New MultiLineVariablesTest and VariableExpressionTest pin x= and z= assignment plus readback via Enter, assignment via name + = + Enter, use in a later line, name + Enter reading a value, expression + Enter evaluating without assigning, reserved-name rejection, unit-spelling variables winning in variable position once assigned, the graph free variable unchanged without known variables, and re-evaluation of dependent lines; compose tests pin the separate = and Enter keys, the absence of MC/MR/M+/M-, and the dropup listing values and inserting a name. Existing memory tests were removed with the register. Verified in this worktree with JDK 21: ./gradlew :calculator:lint :calculator:lintVitalRelease :calculator:testDevUnitTest --max-workers=128 -- all green. ktlintCheck still fails only on domain/UnitRegistry.kt, which this change does not touch (pre-existing).
Diff
calculator/AGENTS.md
diff --git a/calculator/AGENTS.md b/calculator/AGENTS.mdindex fd1e44d284..1a1e4f222a 100644--- a/calculator/AGENTS.md+++ b/calculator/AGENTS.md@@ -13,14 +13,15 @@ _Install: ./install calculator (dev by default)._ ## Overview **Purpose:** Modern Material You calculator — scientific/basic modes, function graphing with analysis, and a multi-category unit converter with live currency rates. **Key features:**-- Scientific + basic keypad with expression history+- Scientific + basic keypad with multi-line expression history: lines stack above the input, tapping a line reuses its result, long-pressing loads its expression for in-place editing (submitting re-runs that line and every line after it in order), and assigned variables show above the input and survive AC+- Variables instead of an M register: the `var` key opens a dropup listing every assignable single letter (`a`–`z` except reserved `e`; the picker is not limited by the keypad's 2nd-layer letters, which still type `a`–`k` directly) with current values; selecting one inserts just its name. Single letters that also spell the graph free variable (`x`/`t`) or units (`c`/`g`/`h`/`k`/`m`/`s`) are assignable in the calculator tab: once assigned, the variable wins in variable position (assignment target, picker insertion, later references), while graph/widget/intent expressions keep the original meaning. Typing/picking a name, then the literal `=` key, a value and Enter assigns (`a=5`); a name alone plus Enter reads its value; any other line plus Enter evaluates as a plain expression. Only a leading `<name>=<expr>` line assigns on Enter, and genuinely reserved names (`e`, multi-letter `ans`/`pi`/`tau`/`phi`/`theta`, functions, multi-letter unit tokens) can never be assigned. The literal `=` key is a regular key in the top section and never submits; the accent Enter key (`⏎`, bottom-right) submits - Graph page: plots functions with root / intercept / min-max / intersection detection - Unit converter across many categories incl. live currency rates (`CurrencyApi` over `:library:network`) - Home-screen widgets for both calculator and unit converter (`:library:widgets` Glance)-**Architecture / data-flow:** Single-screen `MainActivity` hosting `ui/` pages (`CalculatorPage`, `GraphPage`, `UnitConverterPage`) over a `util/` ViewModel + pure expression/graph/units helpers; widget receivers in `widget/` share the same logic. Internet is used only for currency rates.-**Entry points + reading order:** `MainActivity.kt` → `ui/CalculatorPage.kt` → `util/CalculatorViewModel.kt` + `util/CalculatorUiContract.kt` → `util/Expression.kt` / `util/GraphAnalysis.kt` / `domain/UnitRegistry.kt` → `widget/CalculatorGlanceWidget.kt`.+**Architecture / data-flow:** Single-screen `MainActivity` hosting `ui/` pages (`CalculatorPage`, `GraphPage`, `UnitConverterPage`) over a `platform/` ViewModel + pure `domain/` expression/graph/units helpers; widget receivers in `widget/` share the same logic. Internet is used only for currency rates.+**Entry points + reading order:** `MainActivity.kt` → `ui/CalculatorPage.kt` → `platform/CalculatorViewModel.kt` + `platform/CalculatorUiContract.kt` → `domain/Expression.kt` / `domain/GraphAnalysis.kt` / `domain/UnitRegistry.kt` → `widget/CalculatorGlanceWidget.kt`. **Gotchas:**-- `util/` is NOT a closed package root — don't add more files there+- There is no M memory register and no MC/MR/M+/M- keys; state that must persist across AC lives in assigned variables (`CalculatorTab.variables`), re-derived by re-evaluating history lines in order on every Enter - Currency rates are the only network call — everything else must stay offline-safe ## Key files@@ -30,18 +31,19 @@ _Install: ./install calculator (dev by default)._ ### ui/ — keypad, graph, converter pages - com/vayunmathur/calculator/ui/CalculatorPage.kt - com/vayunmathur/calculator/ui/CalculatorKeypad.kt+- com/vayunmathur/calculator/ui/CalculatorVariablePicker.kt — the `var` key + variable dropup - com/vayunmathur/calculator/ui/CalculatorDialogs.kt (unit-picker sheet; its absolute-time date/time pickers stay local — see the DIALOG LOCAL EXCEPTION in the file) - com/vayunmathur/calculator/ui/GraphPage.kt - com/vayunmathur/calculator/ui/UnitConverterPage.kt-### util/ — ViewModel + pure engine-- com/vayunmathur/calculator/util/CalculatorViewModel.kt-- com/vayunmathur/calculator/util/CalculatorUiContract.kt-- com/vayunmathur/calculator/util/Expression.kt — expression parsing/eval-- com/vayunmathur/calculator/util/GraphAnalysis.kt — root/intercept/min-max/intersection+### platform/ — ViewModel + UI contract (domain/ — pure engine)+- com/vayunmathur/calculator/platform/CalculatorViewModel.kt+- com/vayunmathur/calculator/platform/CalculatorUiContract.kt — `CalculatorUiState.variables` (name → formatted value), `CalculatorActions.insertVariable`/`evaluate`+- com/vayunmathur/calculator/platform/CalculatorTab.kt — input/history/variables, multi-line re-evaluation, assignment on Enter+- com/vayunmathur/calculator/domain/Expression.kt — expression parsing/eval; named variables, `Expression.assignableVariableNames`, `Expression.isVariableNameAvailable`+- com/vayunmathur/calculator/domain/GraphAnalysis.kt — root/intercept/min-max/intersection - com/vayunmathur/calculator/domain/UnitRegistry.kt-- com/vayunmathur/calculator/domain/BasicUnitCategories.kt-- com/vayunmathur/calculator/util/CurrencyApi.kt — only network call-- com/vayunmathur/calculator/util/Formatting.kt+- com/vayunmathur/calculator/network/CurrencyApi.kt — only network call+- com/vayunmathur/calculator/domain/Formatting.kt ### intents/ — assistant IPC (validated contracts over the engines above) - com/vayunmathur/calculator/intents/CalculatorContract.kt — caps + validation (expression ≤200 ch, result ≤100 ch); evaluation reuses `domain/Expression`, conversion reuses `domain/UnitRegistry` + live currency category - com/vayunmathur/calculator/intents/EvaluateIntent.kt — `calculator_evaluate` (scalar result)@@ -58,6 +60,6 @@ _Install: ./install calculator (dev by default)._ ## Verify (this module only) ``` ./gradlew :calculator:compileDevKotlin-./gradlew :calculator:lint+./gradlew :calculator:lint :calculator:lintVitalRelease :calculator:testDevUnitTest ./gradlew :calculator:checkMetadata ```
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.ktindex c701251be7..80ef544adc 100644--- a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt@@ -97,7 +97,7 @@ class CalculatorEvaluateTest { private const val GATE_TIMEOUT_MS = 5_000L private const val SHORT_TIMEOUT_MS = 5_000L private const val BOTTOM_TAB_LABEL = "Calculator"- private const val EQUALS_KEY = "="+ private const val EQUALS_KEY = "⏎" private const val EXPECTED_RESULT = "14" private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.ktindex b08de0dd09..e49a9219d1 100644--- a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt@@ -78,7 +78,7 @@ class CalculatorGraphTest { private companion object { private const val CONTENT_TIMEOUT_MS = 15_000L private const val GATE_TIMEOUT_MS = 5_000L- private const val EQUALS_KEY = "="+ private const val EQUALS_KEY = "⏎" private const val GRAPH_TAB = "Graph" private const val ADD_FUNCTION = "Add function" private const val FUNCTION_PLACEHOLDER = "f(x)"
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.ktindex a8cebf7a58..42d6acce70 100644--- a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt@@ -96,7 +96,7 @@ class CalculatorUnitsTest { private const val CONTENT_TIMEOUT_MS = 15_000L private const val GATE_TIMEOUT_MS = 5_000L private const val SHORT_TIMEOUT_MS = 5_000L- private const val EQUALS_KEY = "="+ private const val EQUALS_KEY = "⏎" private const val UNITS_TAB = "Units" // Candidate categories observed on device; the converter opens on
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.ktindex 5230639f5f..edad747f16 100644--- a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.kt+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.kt@@ -100,7 +100,7 @@ class FullE2eTest { private const val GATE_TIMEOUT_MS = 5_000L private const val SHORT_TIMEOUT_MS = 5_000L private const val BOTTOM_TAB_LABEL = "Calculator"- private const val EQUALS_KEY = "="+ private const val EQUALS_KEY = "⏎" private const val PERMISSION_GATE_TITLE = "Grant Required Permissions" /**
calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt b/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.ktindex 948607ff54..dfdfd85b24 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt@@ -70,11 +70,12 @@ class ExpressionError( message: String, ) : Exception(message) -/** Values supplied at evaluation time: the free variable, angle mode, and last answer. */+/** Values supplied at evaluation time: the free variable, angle mode, last answer and named variables. */ class EvalContext( val variable: Double, val angle: AngleMode, val ans: Double,+ val variables: Map<String, Quantity> = emptyMap(), ) /**@@ -85,7 +86,8 @@ class EvalContext( * Supported: `+ - * / ^ %`, unary minus, postfix `!` (factorial, via the gamma * function), implicit multiplication (`2x`, `3(x+1)`, `2sin(x)`), `|x|` bars, * scientific notation (`1.5E3`), the constants `pi`/`π`/`e`/`tau`/`phi`, the free- * variable (`x`/`t`/`θ`/`theta`), `ans` (previous answer), a large unary-function+ * variable (`x`/`t`/`θ`/`theta`), `ans` (previous answer), named variables supplied+ * at parse/eval time (see [Expression.parse]), a large unary-function * library, and multi-argument functions: `log(b,x)`, `root(n,x)`, `nCr(n,r)`, * `nPr(n,r)`, `mod(a,b)`, `gcd(a,b)`, `lcm(a,b)`, `atan2(y,x)`, `max(…)`, `min(…)`. */@@ -102,18 +104,66 @@ class Expression private constructor( variable: Double = 0.0, angle: AngleMode = AngleMode.RADIANS, ans: Double = 0.0,- ): Double = evalQuantity(variable, angle, ans).baseValue+ variables: Map<String, Quantity> = emptyMap(),+ ): Double = evalQuantity(variable, angle, ans, variables).baseValue /** Evaluate to a full [Quantity], carrying units through the calculation. */ fun evalQuantity( variable: Double = 0.0, angle: AngleMode = AngleMode.RADIANS, ans: Double = 0.0,- ): Quantity = root.eval(EvalContext(variable, angle, ans))+ variables: Map<String, Quantity> = emptyMap(),+ ): Quantity = root.eval(EvalContext(variable, angle, ans, variables)) /** Parses expression text into an [Expression]. */ companion object {- fun parse(input: String): Expression = Expression(Parser(input).parse())+ /**+ * Parses [input]. Identifiers in [knownVariables] (matched case-insensitively)+ * become named-variable references resolved from the map passed at evaluation+ * time; any other unknown identifier still fails, so graph expressions and+ * other callers that pass no names keep their current error behaviour.+ */+ fun parse(+ input: String,+ knownVariables: Set<String> = emptySet(),+ ): Expression = Expression(Parser(input, knownVariables.map { it.lowercase() }.toSet()).parse())++ /**+ * The single-letter variables the variable dropup offers: every+ * letter `a`–`z` except `e` (Euler's constant). The picker is not+ * limited by the keypad's 2nd-layer letters. Single letters that+ * also spell something else — `x`/`t` (the graph free variable) or+ * unit spellings such as `c`/`g`/`h`/`k`/`m`/`s` — are included:+ * in the calculator tab a known variable wins in variable position+ * (a line-leading assignment target, a picker insertion, and later+ * references once assigned), while callers that pass no known+ * variables (graph, widget, intents) keep the original meaning.+ * Every entry passes [isVariableNameAvailable].+ */+ val assignableVariableNames: List<String> = ('a'..'z').map { it.toString() }.filter { it != "e" }++ /**+ * Whether [name] may be assigned as a calculator variable: a plain+ * identifier that is not genuinely reserved — `e`, the multi-letter+ * constants (`pi`/`tau`/`phi`/`theta`), `ans`, a function name, or a+ * multi-letter unit token. Any single letter other than `e` is+ * allowed, even one that spells a unit or the graph free variable:+ * assignment is scoped to the calculator tab (callers pass the+ * assigned names as known variables), so those meanings are+ * shadowed only there, only once assigned.+ */+ fun isVariableNameAvailable(name: String): Boolean {+ if (name.isEmpty() || !name.first().isLetter() && name.first() != '_') return false+ if (!name.all { it.isLetterOrDigit() || it == '_' }) return false+ val lower = name.lowercase()+ if (lower == "e") return false+ if (lower in setOf("theta", "ans", "pi", "tau", "phi")) return false+ if (lower in TRIG_FUNCTIONS || lower in HYPERBOLIC_FUNCTIONS) return false+ if (lower in SINGLE_ARG_FUNCTIONS || lower in PAIR_FUNCTIONS) return false+ if (lower in setOf("abs", "log", "max", "min")) return false+ if (name.length == 1) return true+ return name !in UnitRegistry.parseTokens+ } } // ---- AST ----@@ -136,6 +186,14 @@ class Expression private constructor( override fun eval(ctx: EvalContext) = Quantity.scalar(ctx.ans) } + /** A user-assigned variable (e.g. `a` from a `a = 5` line), resolved at evaluation time. */+ private class NamedVar(+ val name: String,+ ) : Node {+ override fun eval(ctx: EvalContext): Quantity =+ ctx.variables[name] ?: throw ExpressionError("Unknown symbol '$name'")+ }+ private class UnitNode( val unit: UnitDef, ) : Node {@@ -300,6 +358,7 @@ class Expression private constructor( */ private class Parser( input: String,+ private val knownVariables: Set<String> = emptySet(), ) { private val src = input private var pos = 0@@ -526,6 +585,15 @@ class Expression private constructor( while (pos < src.length && (src[pos].isLetterOrDigit() || src[pos] == '_')) pos++ val raw = src.substring(start, pos) val name = raw.lowercase()+ // A known variable wins over every other single-word meaning —+ // the free variable (`x`/`t`), and unit spellings (`g`, `h`, …) —+ // in variable position. Only the calculator tab ever passes+ // known variables, and only names it has actually assigned, so+ // graph/widget/intent parses (no known variables) are unchanged+ // and an unassigned letter keeps its unit/free-variable meaning.+ // Genuinely reserved words can never be known variables+ // (assignment rejects them), so no exception list is needed here.+ if (name in knownVariables && peek() != '(') return NamedVar(name) return when (name) { "x", "t", "theta" -> Var "ans" -> Ans@@ -533,7 +601,7 @@ class Expression private constructor( "tau" -> Num(TAU_FACTOR * PI) "e" -> Num(E) "phi" -> Num((1 + sqrt(PHI_RADICAND)) / 2)- else -> parseFunctionOrUnit(raw, name)+ else -> if (name in knownVariables && peek() != '(') NamedVar(name) else parseFunctionOrUnit(raw, name) } }
calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.kt b/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.ktindex a0ae8665c2..927f402d7c 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.kt@@ -104,8 +104,8 @@ class Quantity( * The magnitude in coherent base units, as a single number: for an absolute * temperature that is the absolute kelvin (`value + tempOffsetK`), and for * everything else (including temperature deltas) it is just [value]. This is- * the only scalar a caller may store as "the result" (e.g. as `ans` or in the- * memory register): [value] alone for `212degF` is 117.77… — the degree-size+ * the only scalar a caller may store as "the result" (e.g. as `ans` or in a+ * variable): [value] alone for `212degF` is 117.77… — the degree-size * scaled by 5/9 with the offset dropped — which is neither 212 °F nor the * 373.15 K the same quantity displays as. */
calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.ktindex ee9ba8fc1c..67ba289feb 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt@@ -3,6 +3,7 @@ package com.vayunmathur.calculator.platform import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableDoubleStateOf import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.vayunmathur.calculator.domain.AngleMode@@ -14,10 +15,9 @@ import com.vayunmathur.calculator.domain.UnitRegistry import com.vayunmathur.calculator.domain.formatInstant import com.vayunmathur.calculator.domain.formatQuantity import com.vayunmathur.calculator.domain.formatResult-import com.vayunmathur.calculator.domain.formatResultToken /**- * The keypad tab: input, live preview, history, memory and output-unit selection.+ * The keypad tab: input, live preview, multi-line history, variables and output-unit selection. * * Extracted from [CalculatorViewModel] so the ViewModel stays under detekt's function cap; * the ViewModel delegates [CalculatorActions] to this and exposes [uiState].@@ -37,10 +37,6 @@ class CalculatorTab { var lastAnswer by mutableDoubleStateOf(0.0) private set - /** The single memory register (M+ / M- / MR / MC). */- var memory by mutableDoubleStateOf(0.0)- private set- /** Units the current result can be shown in; empty when the result is dimensionless. */ var unitOptions by mutableStateOf<List<UnitDef>>(emptyList()) private set@@ -54,6 +50,12 @@ class CalculatorTab { val history = mutableStateListOf<HistoryEntry>() + /** Variables assigned by `name = expression` lines, by lowercase name. Kept across [clear]. */+ val variables = mutableStateMapOf<String, Quantity>()++ /** Newest-first history index loaded by [editHistory], replaced in place on [evaluate]. */+ private var editingIndex: Int? = null+ /** * Snapshot of everything the keypad screen draws. Read during composition, so the * underlying `mutableStateOf` reads are tracked normally.@@ -63,9 +65,20 @@ class CalculatorTab { CalculatorUiState( input = input, preview = preview,- memory = memory, angleMode = angleMode, history = history,+ variables =+ variables.entries.sortedBy { it.key }.associate { (name, value) ->+ name to+ formatQuantity(+ value,+ if (value.isDimensionless || value.instant) {+ null+ } else {+ UnitRegistry.defaultUnitFor(value.dimension)+ },+ )+ }, unitOptions = unitOptions, selectedUnit = selectedUnit, unitCategories = UnitRegistry.categories,@@ -84,40 +97,82 @@ class CalculatorTab { if (input.isNotEmpty()) updateInput(input.dropLast(1)) } - fun clear() = updateInput("")+ fun clear() {+ editingIndex = null+ updateInput("")+ } - /** Evaluate the current input, push it to history, store `ans`, show the result. */+ /**+ * Enter: submit the current input as one line of the multi-line history.+ * Only a leading `<name>=<expr>` line assigns (see [assignmentTarget]);+ * every other line — including a bare variable name, which reads its+ * value — is evaluated as a plain expression. A plain new line is+ * appended; a line loaded by [editHistory] is replaced in place. Either+ * way every line is then re-evaluated in chronological order, so an+ * assignment (`a=5`) feeds the lines after it and editing an early line+ * updates the lines that depend on it. The result seeds the input in its+ * re-parsable token form, as before.+ */ fun evaluate() { if (input.isBlank()) return- val quantity =- try {- Expression.parse(input).evalQuantity(angle = angleMode, ans = lastAnswer)- } catch (ignored: ExpressionError) {- return // leave input untouched; the preview already flagged the problem- }- // Non-finite results (NaN, 1/0 = ∞) have no re-parsable token form:- // recording one would replace the input with "∞"/"Undefined" and- // strand it there. Like NaN, they stay a live preview only.- if (!quantity.baseValue.isFinite()) return- val isInstant = quantity.instant- val unit =- if (quantity.isDimensionless || isInstant) {- null- } else {- selectedUnit ?: UnitRegistry.defaultUnitFor(quantity.dimension)- }- val display = formatQuantity(quantity, unit)+ val lines = history.reversed().map { it.expression }.toMutableList()+ val editPos = editingIndex?.let { history.size - 1 - it }?.takeIf { it in lines.indices }+ if (editPos != null) lines[editPos] = input else lines.add(input)+ val targetPos = editPos ?: lines.lastIndex++ val rebuiltVars = mutableMapOf<String, Quantity>()+ val entries = ArrayList<HistoryEntry>(lines.size)+ var ans = 0.0+ for ((index, line) in lines.withIndex()) {+ val (quantity, assignTo) =+ try {+ evalLine(line, rebuiltVars, ans)+ } catch (ignored: ExpressionError) {+ return // leave input and history untouched; the preview already flagged the problem+ }+ // Non-finite results (NaN, 1/0 = ∞) have no re-parsable token form:+ // recording one would replace the input with "∞"/"Undefined" and+ // strand it there. Like NaN, they stay a live preview only.+ if (!quantity.baseValue.isFinite()) return+ val unit =+ if (quantity.isDimensionless || quantity.instant) {+ null+ } else if (index == targetPos) {+ selectedUnit ?: UnitRegistry.defaultUnitFor(quantity.dimension)+ } else {+ UnitRegistry.defaultUnitFor(quantity.dimension)+ }+ if (index == targetPos && unit != null) selectedUnit = unit+ entries.add(+ HistoryEntry(line, formatQuantity(quantity, unit), formatQuantity(quantity, unit, useToken = true)),+ )+ assignTo?.let { rebuiltVars[it] = quantity }+ // baseValue, not value: for an absolute temperature value is only the+ // degree-size, so `ans` after `212degF` was 117.77… instead of 373.15.+ ans = quantity.baseValue+ }+ history.clear()+ history.addAll(entries.reversed())+ variables.clear()+ variables.putAll(rebuiltVars)+ lastAnswer = ans+ editingIndex = null // The token form re-parses, so the result can seed the next calculation.- val token = formatQuantity(quantity, unit, useToken = true)- history.add(0, HistoryEntry(input, display, token))- // baseValue, not value: for an absolute temperature value is only the- // degree-size, so `ans` after `212degF` was 117.77… instead of 373.15.- lastAnswer = quantity.baseValue- if (unit != null) selectedUnit = unit- updateInput(token)+ updateInput(entries[targetPos].resultToken) } - fun useHistory(entry: HistoryEntry) = updateInput(entry.resultToken)+ fun useHistory(entry: HistoryEntry) {+ editingIndex = null+ updateInput(entry.resultToken)+ }++ /** Load a history line's expression into the input; [evaluate] replaces that line in place. */+ fun editHistory(entry: HistoryEntry) {+ val index = history.indexOf(entry)+ if (index < 0) return+ editingIndex = index+ updateInput(entry.expression)+ } fun selectOutputUnit(token: String) { val unit = unitOptions.firstOrNull { it.token == token } ?: return@@ -125,34 +180,43 @@ class CalculatorTab { previewQuantity?.let { preview = formatQuantity(it, unit) } } - // Memory register operations. M+/M- fold the current preview (or input) into memory.- fun memoryClear() {- memory = 0.0+ /**+ * Insert just the variable [name] at the end of the input — the variable+ * dropup's only action, and the same text the digits' 2nd layer types.+ * Only the assignable single letters are accepted, so a reserved name+ * (`x`, `e`, `pi`, a function or a unit) can never be inserted this way.+ * Assignment itself is built with the literal `=` key and submitted with+ * Enter ([evaluate]); this method never assigns.+ */+ fun insertVariable(name: String) {+ val lower = name.lowercase()+ if (lower !in Expression.assignableVariableNames) return+ append(lower) } - fun memoryRecall() = append(formatResultToken(memory))+ /** Re-derive [preview], [unitOptions] and [selectedUnit] from the current [input]. */+ fun refresh() = recomputePreview() - fun memoryAdd() {- currentValue()?.let { memory += it }+ /** The lowercase variable a `name = …` line assigns to, or null for a plain expression line. */+ private fun assignmentTarget(text: String): String? {+ val match = ASSIGNMENT_REGEX.matchEntire(text.trim()) ?: return null+ val name = match.groupValues[1]+ if (!Expression.isVariableNameAvailable(name)) throw ExpressionError("Cannot assign to '$name'")+ return name.lowercase() } - fun memorySubtract() {- currentValue()?.let { memory -= it }+ /** Evaluate one history line, returning its value and the variable it assigns to, if any. */+ private fun evalLine(+ text: String,+ vars: Map<String, Quantity>,+ ans: Double,+ ): Pair<Quantity, String?> {+ val target = assignmentTarget(text)+ val body = if (target == null) text else ASSIGNMENT_REGEX.matchEntire(text.trim())!!.groupValues[2]+ val quantity = Expression.parse(body, vars.keys).evalQuantity(angle = angleMode, ans = ans, variables = vars)+ return quantity to target } - /** Re-derive [preview], [unitOptions] and [selectedUnit] from the current [input]. */- fun refresh() = recomputePreview()-- private fun currentValue(): Double? =- try {- Expression- .parse(input.ifBlank { "0" })- .eval(angle = angleMode, ans = lastAnswer)- .takeIf { !it.isNaN() }- } catch (ignored: ExpressionError) {- null- }- /** Re-derive [preview], [unitOptions] and [selectedUnit] from the current [input]. */ private fun recomputePreview() { val quantity =@@ -160,10 +224,7 @@ class CalculatorTab { if (input.isBlank()) { null } else {- Expression- .parse(input)- .evalQuantity(angle = angleMode, ans = lastAnswer)- .takeIf { !it.value.isNaN() }+ evalLine(input, variables, lastAnswer).first.takeIf { !it.value.isNaN() } } } catch (ignored: ExpressionError) { null@@ -187,6 +248,9 @@ class CalculatorTab { } } +/** A `name = expression` assignment line, the only use of `=` (expressions have no comparison). */+private val ASSIGNMENT_REGEX = Regex("""([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)""")+ /** Adapts [CalculatorTab] to the [CalculatorActions] interface for ViewModel delegation. */ internal fun calculatorActionAdapter(tab: CalculatorTab): CalculatorActions = object : CalculatorActions {@@ -200,15 +264,11 @@ internal fun calculatorActionAdapter(tab: CalculatorTab): CalculatorActions = override fun evaluate() = tab.evaluate() - override fun memoryClear() = tab.memoryClear()-- override fun memoryRecall() = tab.memoryRecall()-- override fun memoryAdd() = tab.memoryAdd()-- override fun memorySubtract() = tab.memorySubtract()+ override fun insertVariable(name: String) = tab.insertVariable(name) override fun useHistory(entry: HistoryEntry) = tab.useHistory(entry) + override fun editHistory(entry: HistoryEntry) = tab.editHistory(entry)+ override fun selectOutputUnit(token: String) = tab.selectOutputUnit(token) }
calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.kt b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.ktindex 1b3e8ed287..6dafe9a538 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.kt@@ -109,9 +109,10 @@ data class GraphViewport( data class CalculatorUiState( val input: String = "", val preview: String = "",- val memory: Double = 0.0, val angleMode: AngleMode = AngleMode.RADIANS, val history: List<HistoryEntry> = emptyList(),+ /** Variables assigned by `name = expression` lines, name to formatted value; empty when none. */+ val variables: Map<String, String> = emptyMap(), /** Units compatible with the current result's dimension; empty when it's dimensionless. */ val unitOptions: List<UnitDef> = emptyList(), /** The unit the result is currently shown in, chosen from [unitOptions]. */@@ -142,20 +143,28 @@ interface CalculatorActions { fun backspace() {} + /**+ * Enter: submit the current line. A leading `<name>=<expr>` line assigns+ * the variable (and dependent lines re-evaluate); any other line is+ * evaluated as a plain expression. The literal `=` key only appends `=`+ * (via [append]) — it never submits.+ */ fun evaluate() {} fun toggleAngleMode() {} - fun memoryClear() {}-- fun memoryRecall() {}-- fun memoryAdd() {}-- fun memorySubtract() {}+ /**+ * Insert just the variable [name] at the end of the input (the variable+ * dropup's only action): type/pick a name, then `=` + value + Enter to+ * assign it, or Enter alone to read its current value.+ */+ fun insertVariable(name: String) {} fun useHistory(entry: HistoryEntry) {} + /** Load a history line's expression for editing; evaluating replaces that line in place. */+ fun editHistory(entry: HistoryEntry) {}+ /** Show the result in the compatible unit identified by [token]. */ fun selectOutputUnit(token: String) {}
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.ktindex 5c95227535..ea08d12e50 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt@@ -1,6 +1,7 @@ package com.vayunmathur.calculator.ui -import androidx.compose.foundation.clickable+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column@@ -54,6 +55,8 @@ internal class Key( val weight: Float = 1f, val second: String? = null, val secondPress: ((CalculatorActions) -> Unit)? = null,+ /** True only for the `var` key: it opens the variable dropup instead of pressing. */+ val isVariablePicker: Boolean = false, val onPress: (CalculatorActions) -> Unit, ) @@ -63,7 +66,12 @@ internal fun RowScope.KeyButton( actions: CalculatorActions, second: Boolean, onToggleSecond: () -> Unit,+ variables: Map<String, String> = emptyMap(), ) {+ if (key.isVariablePicker) {+ VariablePickerButton(key, actions, variables, Modifier.weight(key.weight))+ return+ } val showSecond = second && key.second != null val label = if (showSecond) key.second else key.label val secondActive = key.emphasis == KeyEmphasis.Toggle && second@@ -103,6 +111,11 @@ internal fun RowScope.KeyButton( /** Builds the 8-row keypad for the given angle mode. */ internal fun buildCalculatorRows(angleMode: AngleMode): List<List<Key>> { fun ins(text: String): (CalculatorActions) -> Unit = { it.append(text) }+ // The digits' 2nd layer spells variable names (a-k, skipping e = Euler's+ // constant), so a line like `a=5` can be typed with the existing 2nd+ // modifier — no new mode. The literal `=` in the top section only builds+ // such a line; the accent Enter key (bottom-right, where `=` used to+ // sit) is the one that submits it. return listOf( listOf( Key("2nd", KeyEmphasis.Toggle) {},@@ -126,39 +139,37 @@ internal fun buildCalculatorRows(angleMode: AngleMode): List<List<Key>> { Key(",", KeyEmphasis.Function, second = "EE", onPress = ins(","), secondPress = ins("E")), ), listOf(- Key("MC", KeyEmphasis.Function) { it.memoryClear() },- Key("MR", KeyEmphasis.Function) { it.memoryRecall() },- Key("M+", KeyEmphasis.Function) { it.memoryAdd() },- Key("M-", KeyEmphasis.Function) { it.memorySubtract() },+ Key("var", KeyEmphasis.Function, weight = 3f, isVariablePicker = true) {},+ Key("=", KeyEmphasis.Function) { it.append("=") }, Key(if (angleMode == AngleMode.DEGREES) "DEG" else "RAD", KeyEmphasis.Function) { it.toggleAngleMode() }, ), listOf(- Key("7") { it.append("7") },- Key("8") { it.append("8") },- Key("9") { it.append("9") },+ Key("7", second = "a", secondPress = ins("a")) { it.append("7") },+ Key("8", second = "b", secondPress = ins("b")) { it.append("8") },+ Key("9", second = "c", secondPress = ins("c")) { it.append("9") }, Key("÷", KeyEmphasis.Operator) { it.append("/") }, Key("⌫", KeyEmphasis.Operator) { it.backspace() }, ), listOf(- Key("4") { it.append("4") },- Key("5") { it.append("5") },- Key("6") { it.append("6") },+ Key("4", second = "d", secondPress = ins("d")) { it.append("4") },+ Key("5", second = "f", secondPress = ins("f")) { it.append("5") },+ Key("6", second = "g", secondPress = ins("g")) { it.append("6") }, Key("×", KeyEmphasis.Operator) { it.append("*") }, Key("%", KeyEmphasis.Operator) { it.append("%") }, ), listOf(- Key("1") { it.append("1") },- Key("2") { it.append("2") },- Key("3") { it.append("3") },+ Key("1", second = "h", secondPress = ins("h")) { it.append("1") },+ Key("2", second = "i", secondPress = ins("i")) { it.append("2") },+ Key("3", second = "j", secondPress = ins("j")) { it.append("3") }, Key("−", KeyEmphasis.Operator) { it.append("-") }, Key("nCr", KeyEmphasis.Function, second = "nPr", onPress = ins("nCr("), secondPress = ins("nPr(")), ), listOf( Key("ans", KeyEmphasis.Function) { it.append("ans") },- Key("0") { it.append("0") },+ Key("0", second = "k", secondPress = ins("k")) { it.append("0") }, Key(".") { it.append(".") }, Key("+", KeyEmphasis.Operator) { it.append("+") },- Key("=", KeyEmphasis.Primary) { it.evaluate() },+ Key("⏎", KeyEmphasis.Primary) { it.evaluate() }, ), ) }@@ -180,8 +191,15 @@ internal fun DisplayColumn( verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.End, ) {- if (state.memory != 0.0) {- Text("M", color = MaterialTheme.colorScheme.primary, fontSize = 14.sp)+ if (state.variables.isNotEmpty()) {+ Text(+ state.variables.entries.joinToString(" ") { (name, value) -> "$name = $value" },+ color = MaterialTheme.colorScheme.primary,+ fontSize = 14.sp,+ maxLines = 2,+ softWrap = true,+ overflow = TextOverflow.Ellipsis,+ ) } if (state.history.isNotEmpty()) { // Stored newest-first; reversed iteration lands the newest entry@@ -228,7 +246,11 @@ internal fun DisplayColumn( } } -/** One past calculation in the inline history stack: tapping reuses its result. */+/**+ * One past calculation in the inline history stack: tapping reuses its result,+ * long-pressing loads its expression for editing (evaluating replaces the line).+ */+@OptIn(ExperimentalFoundationApi::class) @Composable private fun HistoryRow( entry: HistoryEntry,@@ -244,8 +266,11 @@ private fun HistoryRow( Column( modifier .fillMaxWidth()- .clickable(role = Role.Button, onClick = { actions.useHistory(entry) })- .semantics { contentDescription = historyDescription }+ .combinedClickable(+ role = Role.Button,+ onClick = { actions.useHistory(entry) },+ onLongClick = { actions.editHistory(entry) },+ ).semantics { contentDescription = historyDescription } .padding(vertical = 8.dp), horizontalAlignment = Alignment.End, ) {@@ -306,11 +331,12 @@ internal fun KeypadColumn( second: Boolean, onToggleSecond: () -> Unit, modifier: Modifier = Modifier,+ variables: Map<String, String> = emptyMap(), ) { Column(modifier.padding(4.dp)) { rows.forEach { row -> Row(Modifier.fillMaxWidth()) {- row.forEach { key -> KeyButton(key, actions, second) { onToggleSecond() } }+ row.forEach { key -> KeyButton(key, actions, second, { onToggleSecond() }, variables) } } } }
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.ktindex cbd155f584..de087797d1 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.kt@@ -42,6 +42,18 @@ internal fun LandscapeDisplay( .replace("/", "÷") .replace("-", "−") Column(modifier.padding(horizontal = 16.dp, vertical = 4.dp), horizontalAlignment = Alignment.End) {+ if (state.variables.isNotEmpty()) {+ Text(+ state.variables.entries.joinToString(" ") { (name, value) -> "$name = $value" },+ modifier = Modifier.fillMaxWidth(),+ textAlign = TextAlign.End,+ fontSize = 14.sp,+ maxLines = 1,+ softWrap = false,+ color = MaterialTheme.colorScheme.primary,+ overflow = TextOverflow.Ellipsis,+ )+ } Text( equation, modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),@@ -81,8 +93,9 @@ internal fun LandscapeKeypad( second: Boolean, onToggleSecond: () -> Unit, modifier: Modifier = Modifier,+ variables: Map<String, String> = emptyMap(), ) {- // Portrait order is [2nd/pi row, trig row, powers/parens row, memory row,+ // Portrait order is [2nd/pi row, trig row, powers/parens row, variable row, // 7-8-9 row, 4-5-6 row, 1-2-3 row, ans-0 row]. Re-flowed as scientific // (first four rows) | basic (last four rows). val scientific = rows.take(4)@@ -92,7 +105,7 @@ internal fun LandscapeKeypad( scientific.forEach { row -> Row(Modifier.fillMaxWidth().weight(1f)) { row.forEach { key ->- LandscapeKeyButton(key, actions, second) { onToggleSecond() }+ LandscapeKeyButton(key, actions, second, variables) { onToggleSecond() } } } }@@ -101,7 +114,7 @@ internal fun LandscapeKeypad( basic.forEach { row -> Row(Modifier.fillMaxWidth().weight(1f)) { row.forEach { key ->- LandscapeKeyButton(key, actions, second) { onToggleSecond() }+ LandscapeKeyButton(key, actions, second, variables) { onToggleSecond() } } } }@@ -114,8 +127,13 @@ private fun RowScope.LandscapeKeyButton( key: Key, actions: CalculatorActions, second: Boolean,+ variables: Map<String, String>, onToggleSecond: () -> Unit, ) {+ if (key.isVariablePicker) {+ VariablePickerButton(key, actions, variables, Modifier.weight(key.weight).fillMaxHeight(), fillHeight = true)+ return+ } val showSecond = second && key.second != null val label = if (showSecond) key.second else key.label val secondActive = key.emphasis == KeyEmphasis.Toggle && second
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.ktindex 932a3bf485..6b269fd343 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.kt@@ -77,6 +77,7 @@ fun CalculatorScreen( second, { second = !second }, Modifier.fillMaxWidth().weight(1f),+ state.variables, ) } }@@ -90,6 +91,7 @@ fun CalculatorScreen( second, { second = !second }, Modifier.weight(1f).widthIn(max = 560.dp).fillMaxSize(),+ state.variables, ) } }@@ -97,7 +99,7 @@ fun CalculatorScreen( Column(Modifier.fillMaxSize().padding(padding)) { DisplayColumn(state, actions, Modifier.fillMaxWidth().weight(1f)) HorizontalDivider()- KeypadColumn(rows, actions, second, { second = !second }, Modifier.fillMaxWidth())+ KeypadColumn(rows, actions, second, { second = !second }, Modifier.fillMaxWidth(), state.variables) } } }
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorVariablePicker.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorVariablePicker.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorVariablePicker.ktnew file mode 100644index 0000000000..ef690fd8ec--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorVariablePicker.kt@@ -0,0 +1,76 @@+package com.vayunmathur.calculator.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.calculator.domain.Expression+import com.vayunmathur.calculator.platform.CalculatorActions+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ButtonDefaults+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberHaptics++/**+ * The `var` key and its dropup: a menu anchored to the key (opening above it+ * when the keypad leaves no room below), following the app's+ * `Button` + `DropdownMenu` pattern from the unit converter. Each row shows+ * the variable's current value when one is assigned; selecting a row inserts+ * just the variable name (see [CalculatorActions.insertVariable]).+ */+@Composable+internal fun VariablePickerButton(+ key: Key,+ actions: CalculatorActions,+ variables: Map<String, String>,+ modifier: Modifier = Modifier,+ fillHeight: Boolean = false,+) {+ var expanded by remember { mutableStateOf(false) }+ val haptics = rememberHaptics()+ Box(modifier.padding(2.dp)) {+ Button(+ onClick = {+ haptics.keyPress()+ expanded = true+ },+ modifier =+ if (fillHeight) {+ Modifier.fillMaxWidth().fillMaxHeight()+ } else {+ Modifier.fillMaxWidth().heightIn(min = 50.dp)+ },+ shape = MaterialTheme.shapes.largeIncreased,+ colors = ButtonDefaults.textButtonColors(),+ contentPadding = PaddingValues(0.dp),+ ) {+ Text(key.label, fontSize = 18.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {+ Expression.assignableVariableNames.forEach { name ->+ val value = variables[name]+ DropdownMenuItem(+ text = { Text(if (value != null) "$name = $value" else name) },+ onClick = {+ actions.insertVariable(name)+ expanded = false+ },+ )+ }+ }+ }+}
calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.kt
diff --git a/calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.kt b/calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.ktindex c79db73570..f42ff52015 100644--- a/calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.kt+++ b/calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.kt@@ -136,7 +136,7 @@ private fun KeypadContent() { CalculatorUiState( input = "sin(45) + 2^10", preview = "1024.707",- memory = 12.5,+ variables = mapOf("a" to "12.5"), angleMode = AngleMode.DEGREES, ), actions = CalculatorActions.Noop,
calculator/src/test/java/com/vayunmathur/calculator/ui/CalculatorScreensComposeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/CalculatorScreensComposeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/CalculatorScreensComposeTest.ktindex 56b8af1f98..d07c1f10ad 100644--- a/calculator/src/test/java/com/vayunmathur/calculator/ui/CalculatorScreensComposeTest.kt+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/CalculatorScreensComposeTest.kt@@ -36,10 +36,19 @@ class CalculatorScreensComposeTest { @Test fun keypadRowsShapeAndAngleLabel() { val rad = buildCalculatorRows(AngleMode.RADIANS) assertEquals(8, rad.size)- assertTrue(rad.all { it.size == 5 })- assertEquals("RAD", rad[3][4].label)- assertEquals("DEG", buildCalculatorRows(AngleMode.DEGREES)[3][4].label)- assertEquals("=", rad[7][4].label)+ // Every row spans the same five columns; the variable row holds one+ // wide `var` key (weight 4) plus the angle key instead of five keys.+ assertTrue(rad.all { row -> row.sumOf { it.weight.toDouble() } == 5.0 })+ assertEquals("var", rad[3][0].label)+ assertTrue(rad[3][0].isVariablePicker)+ // The literal `=` key (builds `a=5`) is separate from Enter.+ assertEquals("=", rad[3][1].label)+ assertEquals("RAD", rad[3][2].label)+ assertEquals("DEG", buildCalculatorRows(AngleMode.DEGREES)[3][2].label)+ assertEquals("⏎", rad[7][4].label)+ // The M register keys are gone.+ val labels = rad.flatten().map { it.label }+ assertTrue(labels.none { it in listOf("MC", "MR", "M+", "M-") }, labels.toString()) } @Test fun keyPressesDispatchToActions() {@@ -62,9 +71,12 @@ class CalculatorScreensComposeTest { } val rows = buildCalculatorRows(AngleMode.RADIANS) rows[4][0].onPress(actions) // 7- rows[7][4].onPress(actions) // =+ rows[3][1].onPress(actions) // literal `=` — builds an assignment, never submits+ assertEquals(listOf("7", "="), appended)+ assertTrue(!evaluated)+ rows[7][4].onPress(actions) // Enter — evaluates/submits the line rows[0][4].onPress(actions) // AC- assertEquals(listOf("7"), appended)+ assertEquals(listOf("7", "="), appended) assertTrue(evaluated) assertTrue(cleared) // Second-function presses.@@ -110,7 +122,7 @@ class CalculatorScreensComposeTest { rule.onNodeWithText("7").assertIsDisplayed() rule.onNodeWithText("7").performClick() assertEquals(listOf("7"), actions.appended)- rule.onNodeWithText("=").performClick()+ rule.onNodeWithText("⏎").performClick() assertEquals(1, actions.evaluated) } @@ -125,7 +137,7 @@ class CalculatorScreensComposeTest { assertEquals(listOf("asin("), actions.appended) } - @Test fun calculatorScreenWithHistoryAndMemory() {+ @Test fun calculatorScreenWithHistoryAndVariables() { val actions = RecordingActions() rule.setContent { CalculatorScreen(@@ -133,13 +145,38 @@ class CalculatorScreensComposeTest { CalculatorUiState( input = "10", preview = "10",- memory = 5.0,+ variables = mapOf("a" to "5"), history = listOf(HistoryEntry("2+3", "5")), ), actions = actions, ) } rule.onAllNodesWithText("10")[0].assertIsDisplayed()+ rule.onNodeWithText("a = 5").assertIsDisplayed()+ }++ @Test fun variableDropupNameTapInsertsJustTheName() {+ var inserted: String? = null+ val actions =+ object : CalculatorActions {+ override fun insertVariable(name: String) {+ inserted = name+ }+ }+ rule.setContent {+ CalculatorScreen(+ state = CalculatorUiState(variables = mapOf("a" to "5")),+ actions = actions,+ )+ }+ rule.onNodeWithText("var").performClick()+ // Assigned variables show their current value in the dropup (a+ // second `a = 5` node beside the one in the display); the rest+ // show the bare name.+ assertTrue(rule.onAllNodesWithText("a = 5").fetchSemanticsNodes().isNotEmpty())+ rule.onNodeWithText("b").assertIsDisplayed()+ rule.onNodeWithText("b").performClick()+ assertEquals("b", inserted) } @Test fun calculatorScreenUnitPickerSeededOpen() {
calculator/src/test/java/com/vayunmathur/calculator/ui/KeypadDirectComposeTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/ui/KeypadDirectComposeTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/ui/KeypadDirectComposeTest.ktindex ad0f903b6f..bc30a24418 100644--- a/calculator/src/test/java/com/vayunmathur/calculator/ui/KeypadDirectComposeTest.kt+++ b/calculator/src/test/java/com/vayunmathur/calculator/ui/KeypadDirectComposeTest.kt@@ -40,7 +40,7 @@ class KeypadDirectComposeTest { CalculatorUiState( input = "2km", preview = "2000 m",- memory = 5.0,+ variables = mapOf("a" to "5"), history = listOf(HistoryEntry("2+3", "5")), unitOptions = lengthUnits, selectedUnit = lengthUnits.firstOrNull { it.token == "m" },@@ -50,6 +50,7 @@ class KeypadDirectComposeTest { } rule.onNodeWithText("2km").assertIsDisplayed() rule.onNodeWithText("2000 m").assertIsDisplayed()+ rule.onNodeWithText("a = 5").assertIsDisplayed() rule.onNodeWithContentDescription("2+3 equals 5").performClick() assertEquals(HistoryEntry("2+3", "5"), used) // Unit chips: centimetre chip selects cm.
calculator/src/test/java/com/vayunmathur/calculator/util/HistoryMemoryTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/HistoryMemoryTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/HistoryMemoryTest.ktindex 418edfc617..e66b1a97a6 100644--- a/calculator/src/test/java/com/vayunmathur/calculator/util/HistoryMemoryTest.kt+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/HistoryMemoryTest.kt@@ -89,18 +89,6 @@ class HistoryMemoryTest { } } - @Test- fun memoryAfterAnAbsoluteTemperatureIsItsKelvinValueWhateverUnitWasTyped() {- // Same stored-scalar bug through M+: the register folded the preview- // via eval(), so it too must see the kelvin magnitude.- for (src in listOf("100degC", "212degF", "373.15K")) {- val tab = CalculatorTab()- tab.updateInput(src)- tab.memoryAdd()- assertEquals(373.15, tab.memory, 1e-9, "memory after $src")- }- }- @Test fun fractionalPowerEvaluatesAndRecords() { val tab = CalculatorTab()@@ -111,30 +99,6 @@ class HistoryMemoryTest { assertEquals(HistoryEntry("4^0.5", "2"), tab.history[0]) } - @Test- fun memoryAddAndSubtractFoldPreview() {- val tab = CalculatorTab()- tab.updateInput("5")- tab.memoryAdd()- assertEquals(5.0, tab.memory)- tab.updateInput("2")- tab.memorySubtract()- assertEquals(3.0, tab.memory)- tab.memoryClear()- assertEquals(0.0, tab.memory)- }-- @Test- fun memoryIgnoresInvalidInput() {- val tab = CalculatorTab()- tab.updateInput("1+")- tab.memoryAdd()- assertEquals(0.0, tab.memory)- tab.clear()- tab.memorySubtract()- assertEquals(0.0, tab.memory)- }- @Test fun evaluatedScientificResultSeedsInputInReparsableForm() { val tab = CalculatorTab()@@ -153,27 +117,6 @@ class HistoryMemoryTest { assertEquals("1e-7", small.preview) } - @Test- fun memoryRecallOfScientificValueSeedsInputInReparsableForm() {- val tab = CalculatorTab()- tab.updateInput("10^12")- tab.memoryAdd()- tab.clear()- tab.memoryRecall()- assertEquals("1E+12", tab.input)- assertEquals("1e+12", tab.preview)- }-- @Test- fun memoryRecallInsertsFormattedValue() {- val tab = CalculatorTab()- tab.updateInput("8")- tab.memoryAdd()- tab.clear()- tab.memoryRecall()- assertEquals("8", tab.input)- }- @Test fun useHistorySeedsTokenFormNotPrettySymbols() { val tab = CalculatorTab()
calculator/src/test/java/com/vayunmathur/calculator/util/MultiLineVariablesTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/MultiLineVariablesTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/MultiLineVariablesTest.ktnew file mode 100644index 0000000000..98bc9e9e28--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/MultiLineVariablesTest.kt@@ -0,0 +1,243 @@+package com.vayunmathur.calculator.util++import com.vayunmathur.calculator.platform.CalculatorTab+import com.vayunmathur.calculator.platform.HistoryEntry+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class MultiLineVariablesTest {+ @Test+ fun assignmentStoresVariableForLaterLines() {+ val tab = CalculatorTab()+ tab.updateInput("a=5")+ assertEquals("5", tab.preview)+ tab.evaluate()+ assertEquals(5.0, tab.lastAnswer, 0.0)+ assertEquals(HistoryEntry("a=5", "5"), tab.history[0])+ assertEquals(mapOf("a" to "5"), tab.uiState.variables)++ tab.updateInput("a*2")+ assertEquals("10", tab.preview)+ tab.evaluate()+ assertEquals(10.0, tab.lastAnswer, 0.0)+ assertEquals(HistoryEntry("a*2", "10"), tab.history[0])+ }++ @Test+ fun assigningIsNameEqualsValueThenEnter() {+ val tab = CalculatorTab()+ // Dropup selection inserts just the name; the literal `=` key builds+ // the assignment; Enter (evaluate) performs it.+ tab.insertVariable("a")+ assertEquals("a", tab.input)+ tab.append("=")+ tab.append("5")+ assertEquals("a=5", tab.input)+ assertEquals("5", tab.preview)+ tab.evaluate()+ assertEquals(5.0, tab.lastAnswer, 0.0)+ assertEquals(mapOf("a" to "5"), tab.uiState.variables)++ // The assigned variable is usable in a later line.+ tab.updateInput("a*2")+ tab.evaluate()+ assertEquals(10.0, tab.lastAnswer, 0.0)+ }++ @Test+ fun dropupSelectionMidExpressionInsertsJustTheNameAsOperand() {+ val tab = CalculatorTab()+ tab.updateInput("a=3")+ tab.evaluate()+ tab.updateInput("2+")+ tab.insertVariable("a")+ assertEquals("2+a", tab.input)+ tab.evaluate()+ assertEquals(5.0, tab.lastAnswer, 0.0)+ }++ @Test+ fun nameThenEnterShowsTheVariablesValue() {+ val tab = CalculatorTab()+ tab.updateInput("a=5")+ tab.evaluate()+ // A bare name line is not an assignment: Enter just reads it.+ // (Clear first: evaluate seeds the input with the result token.)+ tab.clear()+ tab.insertVariable("a")+ assertEquals("a", tab.input)+ tab.evaluate()+ assertEquals(5.0, tab.lastAnswer, 0.0)+ assertEquals(HistoryEntry("a", "5"), tab.history[0])+ assertEquals(mapOf("a" to "5"), tab.uiState.variables)+ }++ @Test+ fun expressionThenEnterEvaluatesWithoutAssigning() {+ val tab = CalculatorTab()+ tab.updateInput("a=5")+ tab.evaluate()+ tab.updateInput("a+1")+ tab.evaluate()+ assertEquals(6.0, tab.lastAnswer, 0.0)+ assertEquals(HistoryEntry("a+1", "6"), tab.history[0])+ // Still 5: `a+1` + Enter evaluated, it did not assign.+ assertEquals(mapOf("a" to "5"), tab.uiState.variables)+ }++ @Test+ fun enterNeverAssignsUnlessLineIsLeadingNameEqualsExpression() {+ val tab = CalculatorTab()+ // `a=` with no value: pressing Enter assigns nothing.+ tab.updateInput("a=")+ tab.evaluate()+ assertTrue(tab.history.isEmpty())+ assertEquals("a=", tab.input)+ assertTrue(tab.uiState.variables.isEmpty())+ // A leading `=` is not an assignment either.+ tab.updateInput("=5")+ tab.evaluate()+ assertTrue(tab.history.isEmpty())+ assertTrue(tab.uiState.variables.isEmpty())+ }++ @Test+ fun dropupSelectionRejectsReservedAndNonAssignableNames() {+ for (name in listOf("e", "pi", "ans", "sin", "log", "radius", "")) {+ val tab = CalculatorTab()+ tab.insertVariable(name)+ assertEquals("", tab.input, name)+ assertTrue(tab.uiState.variables.isEmpty(), name)+ }+ }++ @Test+ fun xAndZAssignmentAndReadbackViaEnter() {+ // The owner's examples: `x=` and `z=` are real assignments, even+ // though `x` is the graph free variable outside the calculator tab.+ val tab = CalculatorTab()+ tab.insertVariable("x")+ tab.append("=")+ tab.append("5")+ tab.evaluate()+ assertEquals(mapOf("x" to "5"), tab.uiState.variables)+ tab.clear()+ tab.insertVariable("x")+ tab.evaluate()+ assertEquals(5.0, tab.lastAnswer, 0.0)+ assertEquals(HistoryEntry("x", "5"), tab.history[0])++ // Start clean: evaluate seeds the input with the result token.+ tab.clear()+ tab.insertVariable("z")+ tab.append("=")+ tab.append("7")+ tab.evaluate()+ assertEquals("7", tab.uiState.variables["z"])+ tab.updateInput("x+z")+ tab.evaluate()+ assertEquals(12.0, tab.lastAnswer, 0.0)+ }++ @Test+ fun unitSpellingVariableWinsInVariablePositionOnceAssigned() {+ val tab = CalculatorTab()+ // Before assignment `2h` is two hours; assigning `h` makes the+ // variable win in variable position (assignment target and later+ // references) in the calculator tab.+ tab.updateInput("h=5")+ tab.evaluate()+ assertEquals(mapOf("h" to "5"), tab.uiState.variables)+ tab.updateInput("2h")+ tab.evaluate()+ assertEquals(10.0, tab.lastAnswer, 0.0)+ }++ @Test+ fun implicitMultiplicationAndReassignment() {+ val tab = CalculatorTab()+ tab.updateInput("a=3")+ tab.evaluate()+ tab.updateInput("2a")+ tab.evaluate()+ assertEquals(6.0, tab.lastAnswer, 0.0)+ tab.updateInput("a=4")+ tab.evaluate()+ tab.updateInput("2a")+ tab.evaluate()+ assertEquals(8.0, tab.lastAnswer, 0.0)+ }++ @Test+ fun editingAnAssignmentLineRecomputesLaterLines() {+ val tab = CalculatorTab()+ tab.updateInput("a=5")+ tab.evaluate()+ tab.updateInput("a*2")+ tab.evaluate()+ assertEquals(2, tab.history.size)++ tab.editHistory(tab.history[1])+ assertEquals("a=5", tab.input)+ tab.updateInput("a=6")+ tab.evaluate()++ // The edited line is replaced, not appended, and the line that+ // depended on it is re-evaluated in order.+ assertEquals(2, tab.history.size)+ assertEquals(HistoryEntry("a*2", "12"), tab.history[0])+ assertEquals(HistoryEntry("a=6", "6"), tab.history[1])+ assertEquals(mapOf("a" to "6"), tab.uiState.variables)+ }++ @Test+ fun editingAPlainLineReplacesItInPlace() {+ val tab = CalculatorTab()+ tab.updateInput("2+3")+ tab.evaluate()+ tab.updateInput("10-4")+ tab.evaluate()+ tab.editHistory(tab.history[1])+ assertEquals("2+3", tab.input)+ tab.updateInput("2+4")+ tab.evaluate()+ assertEquals(2, tab.history.size)+ assertEquals(HistoryEntry("2+4", "6"), tab.history[1])+ assertEquals(HistoryEntry("10-4", "6"), tab.history[0])+ }++ @Test+ fun reservedOrUnknownNamesDoNotEvaluate() {+ for (src in listOf("e=5", "pi=3", "sin=1", "ans=1", "a+1")) {+ val tab = CalculatorTab()+ tab.updateInput(src)+ tab.evaluate()+ assertTrue(tab.history.isEmpty(), src)+ assertEquals(src, tab.input, src)+ }+ }++ @Test+ fun assignmentCanUsePreviousVariableAndAns() {+ val tab = CalculatorTab()+ tab.updateInput("a=2")+ tab.evaluate()+ tab.updateInput("b=a*3")+ tab.evaluate()+ assertEquals(6.0, tab.lastAnswer, 0.0)+ tab.updateInput("b+ans")+ tab.evaluate()+ assertEquals(12.0, tab.lastAnswer, 0.0)+ }++ @Test+ fun clearKeepsVariablesLikeMemory() {+ val tab = CalculatorTab()+ tab.updateInput("a=5")+ tab.evaluate()+ tab.clear()+ tab.updateInput("a+1")+ assertEquals("6", tab.preview)+ }+}
calculator/src/test/java/com/vayunmathur/calculator/util/TabsExtraTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/TabsExtraTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/TabsExtraTest.ktindex a2f11c8e16..a10dbc3ee5 100644--- a/calculator/src/test/java/com/vayunmathur/calculator/util/TabsExtraTest.kt+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/TabsExtraTest.kt@@ -15,7 +15,7 @@ import kotlin.test.assertNotEquals import kotlin.test.assertTrue class TabsExtraTest {- // ---- CalculatorTab: units, memory, instants ----+ // ---- CalculatorTab: units, variables, instants ---- @Test fun unitBearingPreviewOffersOutputUnits() { val tab = CalculatorTab()@@ -44,29 +44,6 @@ class TabsExtraTest { assertTrue(tab.history.size == 1) } - @Test fun memoryRegisterLifecycle() {- val tab = CalculatorTab()- tab.updateInput("5")- tab.memoryAdd()- assertEquals(5.0, tab.memory)- tab.memoryAdd()- assertEquals(10.0, tab.memory)- tab.memorySubtract()- assertEquals(5.0, tab.memory)- tab.clear()- tab.memoryRecall()- assertEquals("5", tab.input)- tab.memoryClear()- assertEquals(0.0, tab.memory)- }-- @Test fun memoryOpsOnInvalidInputAreNoOps() {- val tab = CalculatorTab()- tab.updateInput("1+")- tab.memoryAdd()- assertEquals(0.0, tab.memory)- }- @Test fun insertInstantAndUseHistory() { val tab = CalculatorTab() tab.insertInstant(1_700_000_000)@@ -96,7 +73,6 @@ class TabsExtraTest { assertEquals("", tab.input) actions.insertInstant(10) assertEquals("#10", tab.input)- actions.memoryClear() actions.useHistory(HistoryEntry("e", "9")) assertEquals("9", tab.input) }
calculator/src/test/java/com/vayunmathur/calculator/util/VariableExpressionTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/VariableExpressionTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/VariableExpressionTest.ktnew file mode 100644index 0000000000..0d17b5105e--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/VariableExpressionTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.calculator.util++import com.vayunmathur.calculator.domain.Expression+import com.vayunmathur.calculator.domain.ExpressionError+import com.vayunmathur.calculator.domain.Quantity+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class VariableExpressionTest {+ @Test+ fun namedVariableEvaluatesFromSuppliedValues() {+ val expr = Expression.parse("a*2+b", knownVariables = setOf("a", "b"))+ val vars = mapOf("a" to Quantity.scalar(3.0), "b" to Quantity.scalar(1.0))+ assertEquals(7.0, expr.eval(variables = vars))+ }++ @Test+ fun implicitMultiplicationByNamedVariable() {+ val expr = Expression.parse("2a", knownVariables = setOf("a"))+ assertEquals(6.0, expr.eval(variables = mapOf("a" to Quantity.scalar(3.0))))+ }++ @Test+ fun unknownBareSymbolStillFailsWithoutKnownVariables() {+ assertFailsWith<ExpressionError> { Expression.parse("y").eval() }+ assertFailsWith<ExpressionError> { Expression.parse("a+1").eval() }+ }++ @Test+ fun knownVariableMissingAtEvalTimeFailsAsExpressionError() {+ val expr = Expression.parse("a+1", knownVariables = setOf("a"))+ assertFailsWith<ExpressionError> { expr.eval() }+ }++ @Test+ fun variableNamesAreCaseInsensitive() {+ val expr = Expression.parse("A+1", knownVariables = setOf("a"))+ assertEquals(4.0, expr.eval(variables = mapOf("a" to Quantity.scalar(3.0))))+ }++ @Test+ fun reservedNamesCannotBeVariables() {+ // Only genuinely reserved names are excluded: `e` (Euler's constant)+ // and the multi-letter reserved words (constants, `ans`, functions,+ // multi-letter unit tokens).+ for (name in listOf("theta", "ans", "pi", "e", "tau", "phi", "sin", "log", "km")) {+ assertFalse(Expression.isVariableNameAvailable(name), name)+ }+ assertTrue(Expression.isVariableNameAvailable("a"))+ assertTrue(Expression.isVariableNameAvailable("radius"))+ assertFalse(Expression.isVariableNameAvailable("2a"))+ assertFalse(Expression.isVariableNameAvailable(""))+ }++ @Test+ fun singleLettersIncludingXAndUnitSpellingsCanBeVariables() {+ // The dropup offers a-z (minus `e`); single letters that are also+ // unit spellings or the graph free variable are assignable in the+ // calculator tab, where variable position wins.+ for (name in listOf("x", "z", "t", "c", "g", "h", "k", "m", "s")) {+ assertTrue(Expression.isVariableNameAvailable(name), name)+ }+ }++ @Test+ fun xIsAVariableOnlyWhenKnownOtherwiseTheFreeVariable() {+ // Calculator-tab scoping: with `x` among the known variables it is a+ // named variable; without them (the graph paths) it stays the free+ // variable, unchanged.+ val asVariable = Expression.parse("x*2", knownVariables = setOf("x"))+ assertEquals(6.0, asVariable.eval(variables = mapOf("x" to Quantity.scalar(3.0))))+ assertEquals(8.0, Expression.parse("x*2").eval(variable = 4.0))+ }++ @Test+ fun assignedVariableWinsOverUnitSpellingInVariablePosition() {+ // `g` is gram, but once the calculator tab knows it as a variable,+ // the variable wins; with no known variable it stays the unit.+ val asVariable = Expression.parse("2g", knownVariables = setOf("g"))+ assertEquals(10.0, asVariable.eval(variables = mapOf("g" to Quantity.scalar(5.0))))+ assertEquals(0.002, Expression.parse("2g").evalQuantity().baseValue, 1e-12)+ }++ @Test+ fun assignableNamesAreEverySingleLetterExceptE() {+ // The dropup is not limited by the keypad's 2nd-layer letters: it+ // offers a-z, with only `e` (Euler's constant) excluded.+ assertEquals(+ ('a'..'z').map { it.toString() }.filter { it != "e" },+ Expression.assignableVariableNames,+ )+ assertTrue(Expression.assignableVariableNames.all { Expression.isVariableNameAvailable(it) })+ }+}