calculator: prohibit reserved letters as variables
- Commit
fafe8ce470e331e9b970dcc9cdaa959a2a6bc39b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-06 03:33 UTC (17 minutes ago)
- Parents
5210bff
The variable system let any single letter except e be assigned, so m=5, g=5 or x=5 silently shadowed metres, grams and the graph free variable. The engine already reserves those meanings, so derive the prohibited set from it instead of inventing a list: Expression.prohibitedSingleLetterVariableNames is e/x/t from the parser (Euler constant, free variable) plus every single-letter token or alias in UnitRegistry.parseTokens (a/A ampere, b/B byte, c/C coulomb and Celsius alias, f/F farad, g gram, h hour, j/J joule, k/K kelvin, l/L litre, m metre, n/N newton, s second, v/V volt, w/W watt) — 17 letters, leaving d/i/o/p/q/r/u/y/z assignable. assignableVariableNames now excludes that set, so the var dropup no longer offers them; isVariableNameAvailable rejects them (case- insensitively), so a submitted m=5 line is rejected exactly like e=5 (preview blank, Enter leaves input/history untouched); and Expression.parse filters them out of knownVariables, so they keep their unit/free-variable meaning even if a caller passes them. Existing stored assignments under a newly prohibited letter are ignored on re-evaluation: the history line still evaluates to its value but the variable is dropped from the rebuilt map and from the readout, rather than crashing or blocking later lines. Tests move the variable fixtures from a/b (now ampere/byte) to the allowed d/p/z and add coverage that the prohibited set matches the engine tables, that assignment and dropup insertion are rejected for every prohibited letter, that allowed letters still assign and read back, and that a pre-existing m=5 assignment is dropped on re-evaluation. Verified: :calculator:testDevUnitTest (238 tests), :calculator:lint and :calculator:lintVitalRelease green.
Diff
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 dfdfd85b24..7510924236 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt@@ -126,37 +126,58 @@ class Expression private constructor( fun parse( input: String, knownVariables: Set<String> = emptySet(),- ): Expression = Expression(Parser(input, knownVariables.map { it.lowercase() }.toSet()).parse())+ ): Expression =+ Expression(+ Parser(+ input,+ knownVariables.map { it.lowercase() }.filter { isVariableNameAvailable(it) }.toSet(),+ ).parse(),+ )++ /**+ * Single letters that can never be calculator variables, derived+ * from the engine's own reserved meanings — not an invented list:+ * `e` (Euler's constant in [Parser.parseIdentifier]), `x`/`t` (the+ * free variable, also `theta`), plus every single-letter token or+ * alias in [UnitRegistry.parseTokens] (the parser's unit table,+ * matched case-insensitively because variable lookup lowercases+ * names: `A`/`a` ampere, `B`/`b` byte, `C`/`c` coulomb and the+ * Celsius alias, `F`/`f` farad, `g` gram, `h` hour, `J`/`j` joule,+ * `K`/`k` kelvin, `L`/`l` litre, `m` metre, `N`/`n` newton, `s`+ * second, `V`/`v` volt, `W`/`w` watt). A prohibited letter keeps+ * its original meaning everywhere; it is never shadowed by a+ * variable, in the calculator tab or anywhere else.+ */+ val prohibitedSingleLetterVariableNames: Set<String> =+ buildSet {+ add("e")+ add("t")+ add("x")+ for (key in UnitRegistry.parseTokens.keys) {+ if (key.length == 1) add(key.lowercase())+ }+ } /** * 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.+ * letter `a`–`z` except [prohibitedSingleLetterVariableNames]. * Every entry passes [isVariableNameAvailable]. */- val assignableVariableNames: List<String> = ('a'..'z').map { it.toString() }.filter { it != "e" }+ val assignableVariableNames: List<String> =+ ('a'..'z').map { it.toString() }.filter { it !in prohibitedSingleLetterVariableNames } /** * 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.+ * identifier that is not reserved — a prohibited single letter+ * (see [prohibitedSingleLetterVariableNames]), the multi-letter+ * constants (`pi`/`tau`/`phi`/`theta`), `ans`, a function name, or+ * a multi-letter unit token. Any other single letter is allowed. */ 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 prohibitedSingleLetterVariableNames) 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@@ -585,14 +606,13 @@ 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.+ // A known (assignable) variable wins over other single-word+ // meanings in variable position. Only the calculator tab ever+ // passes known variables, and only names it has actually+ // assigned; [parse] filters prohibited single letters out of+ // the known set, so `e`/`x`/`t` and unit spellings such as+ // `g`/`m` always keep their original meaning, and+ // graph/widget/intent parses (no known variables) are unchanged. if (name in knownVariables && peek() != '(') return NamedVar(name) return when (name) { "x", "t", "theta" -> Var
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 67ba289feb..a97501408a 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt@@ -67,23 +67,30 @@ class CalculatorTab { preview = preview, 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)- },- )- },+ variables = displayVariables(), unitOptions = unitOptions, selectedUnit = selectedUnit, unitCategories = UnitRegistry.categories, ) + /** Assigned variables as the screen shows them, with now-prohibited names dropped. */+ private fun displayVariables(): Map<String, String> =+ variables+ .filterKeys { Expression.isVariableNameAvailable(it) }+ .entries+ .sortedBy { it.key }+ .associate { (name, value) ->+ name to+ formatQuantity(+ value,+ if (value.isDimensionless || value.instant) {+ null+ } else {+ UnitRegistry.defaultUnitFor(value.dimension)+ },+ )+ }+ fun updateInput(value: String) { input = value recomputePreview()@@ -126,7 +133,13 @@ class CalculatorTab { for ((index, line) in lines.withIndex()) { val (quantity, assignTo) = try {- evalLine(line, rebuiltVars, ans)+ // A pre-existing line may still hold an assignment to a+ // letter that is now prohibited (assigned before the+ // ban): ignore that assignment — evaluate the line's+ // value, drop the variable — instead of failing the+ // whole re-evaluation. Only the line being submitted+ // (targetPos) gets the honest rejection.+ evalLine(line, rebuiltVars, ans, ignoreProhibitedAssignment = index != targetPos) } catch (ignored: ExpressionError) { return // leave input and history untouched; the preview already flagged the problem }@@ -182,9 +195,9 @@ class CalculatorTab { /** * 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.+ * dropup's only action (variable names are entered only this way). * 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.+ * (`x`, `e`, `m`, `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. */@@ -210,9 +223,21 @@ class CalculatorTab { text: String, vars: Map<String, Quantity>, ans: Double,+ ignoreProhibitedAssignment: Boolean = false, ): Pair<Quantity, String?> {+ val match = ASSIGNMENT_REGEX.matchEntire(text.trim())+ if (match != null && ignoreProhibitedAssignment) {+ val name = match.groupValues[1]+ if (name.lowercase() in Expression.prohibitedSingleLetterVariableNames) {+ val quantity =+ Expression+ .parse(match.groupValues[2], vars.keys)+ .evalQuantity(angle = angleMode, ans = ans, variables = vars)+ return quantity to null+ }+ } val target = assignmentTarget(text)- val body = if (target == null) text else ASSIGNMENT_REGEX.matchEntire(text.trim())!!.groupValues[2]+ val body = if (target == null) text else match!!.groupValues[2] val quantity = Expression.parse(body, vars.keys).evalQuantity(angle = angleMode, ans = ans, variables = vars) return quantity to target }
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 bc30a24418..fd5b3b51b8 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",- variables = mapOf("a" to "5"),+ variables = mapOf("d" to "5"), history = listOf(HistoryEntry("2+3", "5")), unitOptions = lengthUnits, selectedUnit = lengthUnits.firstOrNull { it.token == "m" },@@ -50,7 +50,7 @@ class KeypadDirectComposeTest { } rule.onNodeWithText("2km").assertIsDisplayed() rule.onNodeWithText("2000 m").assertIsDisplayed()- rule.onNodeWithText("a = 5").assertIsDisplayed()+ rule.onNodeWithText("d = 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/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.ktindex 98bc9e9e28..b99920148e 100644--- a/calculator/src/test/java/com/vayunmathur/calculator/util/MultiLineVariablesTest.kt+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/MultiLineVariablesTest.kt@@ -1,5 +1,6 @@ package com.vayunmathur.calculator.util +import com.vayunmathur.calculator.domain.Quantity import com.vayunmathur.calculator.platform.CalculatorTab import com.vayunmathur.calculator.platform.HistoryEntry import kotlin.test.Test@@ -10,18 +11,18 @@ class MultiLineVariablesTest { @Test fun assignmentStoresVariableForLaterLines() { val tab = CalculatorTab()- tab.updateInput("a=5")+ tab.updateInput("d=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)+ assertEquals(HistoryEntry("d=5", "5"), tab.history[0])+ assertEquals(mapOf("d" to "5"), tab.uiState.variables) - tab.updateInput("a*2")+ tab.updateInput("d*2") assertEquals("10", tab.preview) tab.evaluate() assertEquals(10.0, tab.lastAnswer, 0.0)- assertEquals(HistoryEntry("a*2", "10"), tab.history[0])+ assertEquals(HistoryEntry("d*2", "10"), tab.history[0]) } @Test@@ -29,18 +30,18 @@ class MultiLineVariablesTest { 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.insertVariable("d")+ assertEquals("d", tab.input) tab.append("=") tab.append("5")- assertEquals("a=5", tab.input)+ assertEquals("d=5", tab.input) assertEquals("5", tab.preview) tab.evaluate() assertEquals(5.0, tab.lastAnswer, 0.0)- assertEquals(mapOf("a" to "5"), tab.uiState.variables)+ assertEquals(mapOf("d" to "5"), tab.uiState.variables) // The assigned variable is usable in a later line.- tab.updateInput("a*2")+ tab.updateInput("d*2") tab.evaluate() assertEquals(10.0, tab.lastAnswer, 0.0) }@@ -48,11 +49,11 @@ class MultiLineVariablesTest { @Test fun dropupSelectionMidExpressionInsertsJustTheNameAsOperand() { val tab = CalculatorTab()- tab.updateInput("a=3")+ tab.updateInput("d=3") tab.evaluate() tab.updateInput("2+")- tab.insertVariable("a")- assertEquals("2+a", tab.input)+ tab.insertVariable("d")+ assertEquals("2+d", tab.input) tab.evaluate() assertEquals(5.0, tab.lastAnswer, 0.0) }@@ -60,40 +61,40 @@ class MultiLineVariablesTest { @Test fun nameThenEnterShowsTheVariablesValue() { val tab = CalculatorTab()- tab.updateInput("a=5")+ tab.updateInput("d=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.insertVariable("d")+ assertEquals("d", 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)+ assertEquals(HistoryEntry("d", "5"), tab.history[0])+ assertEquals(mapOf("d" to "5"), tab.uiState.variables) } @Test fun expressionThenEnterEvaluatesWithoutAssigning() { val tab = CalculatorTab()- tab.updateInput("a=5")+ tab.updateInput("d=5") tab.evaluate()- tab.updateInput("a+1")+ tab.updateInput("d+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)+ assertEquals(HistoryEntry("d+1", "6"), tab.history[0])+ // Still 5: `d+1` + Enter evaluated, it did not assign.+ assertEquals(mapOf("d" to "5"), tab.uiState.variables) } @Test fun enterNeverAssignsUnlessLineIsLeadingNameEqualsExpression() { val tab = CalculatorTab()- // `a=` with no value: pressing Enter assigns nothing.- tab.updateInput("a=")+ // `d=` with no value: pressing Enter assigns nothing.+ tab.updateInput("d=") tab.evaluate() assertTrue(tab.history.isEmpty())- assertEquals("a=", tab.input)+ assertEquals("d=", tab.input) assertTrue(tab.uiState.variables.isEmpty()) // A leading `=` is not an assignment either. tab.updateInput("=5")@@ -104,7 +105,7 @@ class MultiLineVariablesTest { @Test fun dropupSelectionRejectsReservedAndNonAssignableNames() {- for (name in listOf("e", "pi", "ans", "sin", "log", "radius", "")) {+ for (name in listOf("e", "m", "g", "x", "a", "b", "pi", "ans", "sin", "log", "radius", "")) { val tab = CalculatorTab() tab.insertVariable(name) assertEquals("", tab.input, name)@@ -113,58 +114,86 @@ class MultiLineVariablesTest { } @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.+ fun zAssignmentWorksAndProhibitedXAssignmentIsRejected() { 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")+ // `x` is the graph free variable: it can never be assigned.+ tab.updateInput("x=5") tab.evaluate()- assertEquals(5.0, tab.lastAnswer, 0.0)- assertEquals(HistoryEntry("x", "5"), tab.history[0])+ assertTrue(tab.history.isEmpty())+ assertEquals("x=5", tab.input)+ assertTrue(tab.uiState.variables.isEmpty()) - // Start clean: evaluate seeds the input with the result token.- tab.clear()+ tab.updateInput("") tab.insertVariable("z") tab.append("=") tab.append("7") tab.evaluate() assertEquals("7", tab.uiState.variables["z"])- tab.updateInput("x+z")+ tab.updateInput("z*2") tab.evaluate()- assertEquals(12.0, tab.lastAnswer, 0.0)+ assertEquals(14.0, tab.lastAnswer, 0.0) } @Test- fun unitSpellingVariableWinsInVariablePositionOnceAssigned() {+ fun unitSpellingCannotBeAssignedAndKeepsItsUnitMeaning() { 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)+ // `h` is hour, `m` is metre: assignment to either is rejected the+ // same way as `e=5`, and the letters keep their unit meaning.+ for (src in listOf("h=5", "m=5", "g=5")) {+ val fresh = CalculatorTab()+ fresh.updateInput(src)+ fresh.evaluate()+ assertTrue(fresh.history.isEmpty(), src)+ assertEquals(src, fresh.input, src)+ assertTrue(fresh.uiState.variables.isEmpty(), src)+ } tab.updateInput("2h") tab.evaluate()- assertEquals(10.0, tab.lastAnswer, 0.0)+ assertEquals(7200.0, tab.lastAnswer, 0.0)+ }++ @Test+ fun assignmentToEachProhibitedLetterIsRejected() {+ for (name in com.vayunmathur.calculator.domain.Expression.prohibitedSingleLetterVariableNames) {+ val tab = CalculatorTab()+ tab.updateInput("$name=5")+ tab.evaluate()+ assertTrue(tab.history.isEmpty(), name)+ assertEquals("$name=5", tab.input, name)+ assertTrue(tab.uiState.variables.isEmpty(), name)+ val picker = CalculatorTab()+ picker.insertVariable(name)+ assertEquals("", picker.input, name)+ }+ }++ @Test+ fun preExistingProhibitedAssignmentIsIgnoredOnReevaluation() {+ // Simulate a stored assignment from before the ban: the history+ // line `m=5` plus its variable. Re-evaluating a later allowed+ // line drops `m` instead of failing or resurrecting it.+ val tab = CalculatorTab()+ tab.history.add(HistoryEntry("m=5", "5"))+ tab.variables["m"] =+ Quantity+ .scalar(5.0)+ tab.updateInput("d=2")+ tab.evaluate()+ assertEquals(mapOf("d" to "2"), tab.uiState.variables)+ assertEquals(2.0, tab.lastAnswer, 0.0) } @Test fun implicitMultiplicationAndReassignment() { val tab = CalculatorTab()- tab.updateInput("a=3")+ tab.updateInput("d=3") tab.evaluate()- tab.updateInput("2a")+ tab.updateInput("2d") tab.evaluate() assertEquals(6.0, tab.lastAnswer, 0.0)- tab.updateInput("a=4")+ tab.updateInput("d=4") tab.evaluate()- tab.updateInput("2a")+ tab.updateInput("2d") tab.evaluate() assertEquals(8.0, tab.lastAnswer, 0.0) }@@ -172,23 +201,23 @@ class MultiLineVariablesTest { @Test fun editingAnAssignmentLineRecomputesLaterLines() { val tab = CalculatorTab()- tab.updateInput("a=5")+ tab.updateInput("d=5") tab.evaluate()- tab.updateInput("a*2")+ tab.updateInput("d*2") tab.evaluate() assertEquals(2, tab.history.size) tab.editHistory(tab.history[1])- assertEquals("a=5", tab.input)- tab.updateInput("a=6")+ assertEquals("d=5", tab.input)+ tab.updateInput("d=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)+ assertEquals(HistoryEntry("d*2", "12"), tab.history[0])+ assertEquals(HistoryEntry("d=6", "6"), tab.history[1])+ assertEquals(mapOf("d" to "6"), tab.uiState.variables) } @Test@@ -209,7 +238,7 @@ class MultiLineVariablesTest { @Test fun reservedOrUnknownNamesDoNotEvaluate() {- for (src in listOf("e=5", "pi=3", "sin=1", "ans=1", "a+1")) {+ for (src in listOf("e=5", "m=5", "g=5", "x=5", "a=5", "pi=3", "sin=1", "ans=1", "d+1")) { val tab = CalculatorTab() tab.updateInput(src) tab.evaluate()@@ -221,12 +250,12 @@ class MultiLineVariablesTest { @Test fun assignmentCanUsePreviousVariableAndAns() { val tab = CalculatorTab()- tab.updateInput("a=2")+ tab.updateInput("d=2") tab.evaluate()- tab.updateInput("b=a*3")+ tab.updateInput("p=d*3") tab.evaluate() assertEquals(6.0, tab.lastAnswer, 0.0)- tab.updateInput("b+ans")+ tab.updateInput("p+ans") tab.evaluate() assertEquals(12.0, tab.lastAnswer, 0.0) }@@ -234,10 +263,10 @@ class MultiLineVariablesTest { @Test fun clearKeepsVariablesLikeMemory() { val tab = CalculatorTab()- tab.updateInput("a=5")+ tab.updateInput("d=5") tab.evaluate() tab.clear()- tab.updateInput("a+1")+ tab.updateInput("d+1") assertEquals("6", tab.preview) } }
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.ktindex 0d17b5105e..0ba0774cbc 100644--- a/calculator/src/test/java/com/vayunmathur/calculator/util/VariableExpressionTest.kt+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/VariableExpressionTest.kt@@ -12,86 +12,95 @@ 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))+ val expr = Expression.parse("d*2+p", knownVariables = setOf("d", "p"))+ val vars = mapOf("d" to Quantity.scalar(3.0), "p" 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))))+ val expr = Expression.parse("2d", knownVariables = setOf("d"))+ assertEquals(6.0, expr.eval(variables = mapOf("d" to Quantity.scalar(3.0)))) } @Test fun unknownBareSymbolStillFailsWithoutKnownVariables() { assertFailsWith<ExpressionError> { Expression.parse("y").eval() }- assertFailsWith<ExpressionError> { Expression.parse("a+1").eval() }+ assertFailsWith<ExpressionError> { Expression.parse("d+1").eval() } } @Test fun knownVariableMissingAtEvalTimeFailsAsExpressionError() {- val expr = Expression.parse("a+1", knownVariables = setOf("a"))+ val expr = Expression.parse("d+1", knownVariables = setOf("d")) 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))))+ val expr = Expression.parse("D+1", knownVariables = setOf("d"))+ assertEquals(4.0, expr.eval(variables = mapOf("d" 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("d")) assertTrue(Expression.isVariableNameAvailable("radius"))- assertFalse(Expression.isVariableNameAvailable("2a"))+ assertFalse(Expression.isVariableNameAvailable("2d")) 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)+ fun prohibitedSingleLettersMatchTheEnginesReservedSymbols() {+ // Derived from the engine itself: `e` (Euler), `x`/`t` (free+ // variable) in the parser, plus every single-letter token/alias in+ // UnitRegistry.parseTokens — a/A ampere, b/B byte, c/C coulomb and+ // Celsius alias, f/F farad, g gram, h hour, j/J joule, k/K kelvin,+ // l/L litre, m metre, n/N newton, s second, v/V volt, w/W watt.+ val expected =+ setOf("a", "b", "c", "e", "f", "g", "h", "j", "k", "l", "m", "n", "s", "t", "v", "w", "x")+ assertEquals(expected, Expression.prohibitedSingleLetterVariableNames)+ for (name in expected) {+ assertFalse(Expression.isVariableNameAvailable(name), name)+ assertFalse(name in Expression.assignableVariableNames, name)+ }+ // Case-insensitive: an uppercase spelling of a unit is prohibited too.+ for (name in listOf("A", "B", "C", "F", "J", "K", "L", "M", "N", "V", "W", "X", "E")) {+ assertFalse(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))+ fun allowedSingleLettersCanBeVariables() {+ for (name in listOf("d", "i", "o", "p", "q", "r", "u", "y", "z")) {+ assertTrue(Expression.isVariableNameAvailable(name), name)+ }+ assertEquals(+ listOf("d", "i", "o", "p", "q", "r", "u", "y", "z"),+ Expression.assignableVariableNames,+ )+ assertTrue(Expression.assignableVariableNames.all { Expression.isVariableNameAvailable(it) }) } @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)+ fun xStaysTheFreeVariableEvenWhenPassedAsAKnownVariable() {+ // Prohibited letters are filtered out of the known set at parse+ // time, so `x` can never be shadowed by a variable.+ val expr = Expression.parse("x*2", knownVariables = setOf("x"))+ assertEquals(8.0, expr.eval(variable = 4.0, variables = mapOf("x" to Quantity.scalar(3.0))))+ assertEquals(8.0, Expression.parse("x*2").eval(variable = 4.0)) } @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) })+ fun unitSpellingStaysAUnitEvenWhenPassedAsAKnownVariable() {+ // `g` is gram and `m` is metre, whatever the caller passes.+ val asUnit = Expression.parse("2g", knownVariables = setOf("g"))+ assertEquals(0.002, asUnit.evalQuantity(variables = mapOf("g" to Quantity.scalar(5.0))).baseValue, 1e-12)+ assertEquals(2.0, Expression.parse("2m", knownVariables = setOf("m")).evalQuantity().baseValue, 1e-12)+ // An allowed letter still wins as a variable: `2d` with d = 5 is 10.+ val asVariable = Expression.parse("2d", knownVariables = setOf("d"))+ assertEquals(10.0, asVariable.eval(variables = mapOf("d" to Quantity.scalar(5.0)))) } }