solve-engine 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/{PackageCompatibility-CCdud__Q.d.cts → PackageCompatibility-BG0iur4I.d.cts} +1 -1
  2. package/dist/{PackageCompatibility-4QtIErfx.d.ts → PackageCompatibility-BlIcQg5v.d.ts} +1 -1
  3. package/dist/{PackageRegistry-B7wkfSrY.d.ts → PackageRegistry-BJ0QQd3k.d.ts} +4 -4
  4. package/dist/{PackageRegistry-Hx85XD01.d.cts → PackageRegistry-DeGDZkNt.d.cts} +4 -4
  5. package/dist/{Parselet-CTNpfuEB.d.cts → Parselet-BSndkWEY.d.cts} +1 -1
  6. package/dist/{Parselet-DONNUpur.d.ts → Parselet-Blq8B0Gj.d.ts} +1 -1
  7. package/dist/{ScopeManager-BkbDXK_R.d.ts → ScopeManager-CF3cZUqW.d.ts} +2 -2
  8. package/dist/{ScopeManager-Cvgypcu4.d.cts → ScopeManager-D8nLv--u.d.cts} +2 -2
  9. package/dist/{VMCheckpoints-9zBQnTsN.d.ts → VMCheckpoints-BsR5_auF.d.ts} +2 -2
  10. package/dist/{VMCheckpoints-CBMGiSqw.d.cts → VMCheckpoints-Dy39SVHa.d.cts} +2 -2
  11. package/dist/{Value-D1XlMwe2.d.cts → Value-DCTqTSeP.d.cts} +22 -5
  12. package/dist/{Value-D1XlMwe2.d.ts → Value-DCTqTSeP.d.ts} +22 -5
  13. package/dist/chunk-5AMJNF7J.js +3 -0
  14. package/dist/chunk-5AMJNF7J.js.map +1 -0
  15. package/dist/chunk-5TCSFTZD.js +2 -0
  16. package/dist/chunk-5TCSFTZD.js.map +1 -0
  17. package/dist/chunk-5TVI2UPZ.cjs +2 -0
  18. package/dist/chunk-5TVI2UPZ.cjs.map +1 -0
  19. package/dist/{chunk-ZOOVGXMK.cjs → chunk-75XDS65A.cjs} +2 -2
  20. package/dist/{chunk-ZOOVGXMK.cjs.map → chunk-75XDS65A.cjs.map} +1 -1
  21. package/dist/chunk-A33K7NY4.js +2 -0
  22. package/dist/chunk-A33K7NY4.js.map +1 -0
  23. package/dist/chunk-AQWNEO7M.cjs +2 -0
  24. package/dist/{chunk-Z5KBBQOJ.cjs.map → chunk-AQWNEO7M.cjs.map} +1 -1
  25. package/dist/{chunk-OVQ3V4CG.cjs → chunk-B7J24Q5T.cjs} +2 -2
  26. package/dist/{chunk-OVQ3V4CG.cjs.map → chunk-B7J24Q5T.cjs.map} +1 -1
  27. package/dist/{chunk-HMEZJXLX.js → chunk-CVY2A3TP.js} +2 -2
  28. package/dist/{chunk-HMEZJXLX.js.map → chunk-CVY2A3TP.js.map} +1 -1
  29. package/dist/{chunk-HOQU47MF.cjs → chunk-FNNIAJNY.cjs} +2 -2
  30. package/dist/{chunk-HOQU47MF.cjs.map → chunk-FNNIAJNY.cjs.map} +1 -1
  31. package/dist/{chunk-3AVWA5IZ.cjs → chunk-FUDVKPB7.cjs} +2 -2
  32. package/dist/{chunk-3AVWA5IZ.cjs.map → chunk-FUDVKPB7.cjs.map} +1 -1
  33. package/dist/chunk-GYX6S6OS.cjs +3 -0
  34. package/dist/chunk-GYX6S6OS.cjs.map +1 -0
  35. package/dist/{chunk-GKDZ7TSX.cjs → chunk-HAEOMJE3.cjs} +2 -2
  36. package/dist/{chunk-GKDZ7TSX.cjs.map → chunk-HAEOMJE3.cjs.map} +1 -1
  37. package/dist/{chunk-T52Y5G24.js → chunk-HF4H7LYA.js} +4 -4
  38. package/dist/{chunk-T52Y5G24.js.map → chunk-HF4H7LYA.js.map} +1 -1
  39. package/dist/chunk-HTJPV42D.js +2 -0
  40. package/dist/{chunk-XTM4HTRB.js.map → chunk-HTJPV42D.js.map} +1 -1
  41. package/dist/chunk-IHZBKT7L.cjs +3 -0
  42. package/dist/chunk-IHZBKT7L.cjs.map +1 -0
  43. package/dist/{chunk-SWKYVSMP.js → chunk-JEFMG6CV.js} +2 -2
  44. package/dist/{chunk-SWKYVSMP.js.map → chunk-JEFMG6CV.js.map} +1 -1
  45. package/dist/{chunk-P6BLASAA.js → chunk-JQBG3LX4.js} +2 -2
  46. package/dist/{chunk-P6BLASAA.js.map → chunk-JQBG3LX4.js.map} +1 -1
  47. package/dist/{chunk-GHW2X7PS.js → chunk-KHCNMNZZ.js} +2 -2
  48. package/dist/{chunk-GHW2X7PS.js.map → chunk-KHCNMNZZ.js.map} +1 -1
  49. package/dist/{chunk-4XTD4B77.js → chunk-KXM7EY27.js} +3 -3
  50. package/dist/{chunk-4XTD4B77.js.map → chunk-KXM7EY27.js.map} +1 -1
  51. package/dist/{chunk-R7T3NGUE.cjs → chunk-MVP2YD4X.cjs} +2 -2
  52. package/dist/{chunk-R7T3NGUE.cjs.map → chunk-MVP2YD4X.cjs.map} +1 -1
  53. package/dist/chunk-N4HJTHZR.js +2 -0
  54. package/dist/{chunk-ZJPAPBP3.js.map → chunk-N4HJTHZR.js.map} +1 -1
  55. package/dist/chunk-P5EMTVMJ.js +3 -0
  56. package/dist/chunk-P5EMTVMJ.js.map +1 -0
  57. package/dist/chunk-PNDQRCRQ.cjs +2 -0
  58. package/dist/chunk-PNDQRCRQ.cjs.map +1 -0
  59. package/dist/{chunk-B4P4M4ZW.cjs → chunk-W7VOTR2J.cjs} +3 -3
  60. package/dist/{chunk-B4P4M4ZW.cjs.map → chunk-W7VOTR2J.cjs.map} +1 -1
  61. package/dist/{chunk-VYWGUMFW.js → chunk-WTEXBPBR.js} +2 -2
  62. package/dist/{chunk-VYWGUMFW.js.map → chunk-WTEXBPBR.js.map} +1 -1
  63. package/dist/{chunk-KSDTVFXA.cjs → chunk-ZRFUD2LX.cjs} +4 -4
  64. package/dist/{chunk-KSDTVFXA.cjs.map → chunk-ZRFUD2LX.cjs.map} +1 -1
  65. package/dist/constants.cjs +1 -1
  66. package/dist/constants.js +1 -1
  67. package/dist/engine.cjs +1 -1
  68. package/dist/engine.d.cts +7 -7
  69. package/dist/engine.d.ts +7 -7
  70. package/dist/engine.js +1 -1
  71. package/dist/format.cjs +1 -1
  72. package/dist/format.d.cts +1 -1
  73. package/dist/format.d.ts +1 -1
  74. package/dist/format.js +1 -1
  75. package/dist/index.cjs +1 -1
  76. package/dist/index.d.cts +7 -7
  77. package/dist/index.d.ts +7 -7
  78. package/dist/index.js +1 -1
  79. package/dist/language.d.cts +6 -6
  80. package/dist/language.d.ts +6 -6
  81. package/dist/packages.cjs +1 -1
  82. package/dist/packages.d.cts +6 -6
  83. package/dist/packages.d.ts +6 -6
  84. package/dist/packages.js +1 -1
  85. package/dist/parser.cjs +1 -1
  86. package/dist/parser.d.cts +3 -3
  87. package/dist/parser.d.ts +3 -3
  88. package/dist/parser.js +1 -1
  89. package/dist/{pipeline-DY0rhgQG.d.cts → pipeline-BM8xc0CZ.d.cts} +3 -3
  90. package/dist/{pipeline-BH7BFOTJ.d.ts → pipeline-J2ehIm7t.d.ts} +3 -3
  91. package/dist/resolvers.d.cts +1 -1
  92. package/dist/resolvers.d.ts +1 -1
  93. package/dist/testing.cjs +2 -2
  94. package/dist/testing.d.cts +6 -6
  95. package/dist/testing.d.ts +6 -6
  96. package/dist/testing.js +1 -1
  97. package/dist/uom.cjs +1 -1
  98. package/dist/uom.d.cts +1 -1
  99. package/dist/uom.d.ts +1 -1
  100. package/dist/uom.js +1 -1
  101. package/dist/vm.cjs +1 -1
  102. package/dist/vm.d.cts +6 -6
  103. package/dist/vm.d.ts +6 -6
  104. package/dist/vm.js +1 -1
  105. package/dist/worker.cjs +2 -2
  106. package/dist/worker.cjs.map +1 -1
  107. package/dist/worker.d.cts +15 -5
  108. package/dist/worker.d.ts +15 -5
  109. package/dist/worker.js +2 -2
  110. package/dist/worker.js.map +1 -1
  111. package/package.json +1 -1
  112. package/dist/chunk-3DD2RVBI.cjs +0 -3
  113. package/dist/chunk-3DD2RVBI.cjs.map +0 -1
  114. package/dist/chunk-5FGOIDLS.cjs +0 -2
  115. package/dist/chunk-5FGOIDLS.cjs.map +0 -1
  116. package/dist/chunk-5OIXCVB2.js +0 -3
  117. package/dist/chunk-5OIXCVB2.js.map +0 -1
  118. package/dist/chunk-ESUN2THE.cjs +0 -2
  119. package/dist/chunk-ESUN2THE.cjs.map +0 -1
  120. package/dist/chunk-IO374J6Z.js +0 -2
  121. package/dist/chunk-IO374J6Z.js.map +0 -1
  122. package/dist/chunk-R2ENWQ76.js +0 -2
  123. package/dist/chunk-R2ENWQ76.js.map +0 -1
  124. package/dist/chunk-SOSUS2SK.cjs +0 -3
  125. package/dist/chunk-SOSUS2SK.cjs.map +0 -1
  126. package/dist/chunk-T4Y5XOT2.js +0 -3
  127. package/dist/chunk-T4Y5XOT2.js.map +0 -1
  128. package/dist/chunk-XTM4HTRB.js +0 -2
  129. package/dist/chunk-Z5KBBQOJ.cjs +0 -2
  130. package/dist/chunk-ZJPAPBP3.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/symbolic/Rational.ts","../src/symbolic/Complex.ts","../src/symbolic/SymbolicNode.ts","../src/symbolic/Polynomial.ts","../src/symbolic/Gcd.ts","../src/symbolic/Radicals.ts","../src/symbolic/Simplify.ts","../src/symbolic/SymbolicFormat.ts","../src/vm/MatrixOps.ts","../src/decimal/Decimal.ts","../src/uom/CurrencyAliases.ts"],"names":["RATIONAL_ZERO","RATIONAL_ONE","RATIONAL_MINUS_ONE","RATIONAL_MAX_BITS","MAX_MAGNITUDE","bigintPow","base","exponent","result","factor","remaining","gcd","a","b","x","y","remainder","guardMagnitude","d","ErrorFactory","normalize","numerator","denominator","divisor","rational","DECIMAL_FORM","rationalFromNumber","value","parts","sign","integerDigits","fractionDigits","exponentDigits","rationalToNumber","r","direct","rationalAdd","rationalSub","rationalMul","rationalDiv","rationalNeg","rationalPow","positive","rationalCompare","left","right","isRationalZero","isRationalOne","isRationalMinusOne","isRationalInteger","MAX_DECIMAL_DIGITS","MAX_FRACTION_COMPONENT","formatRational","twos","fives","terminates","decimals","scaled","digits","whole","fraction","COMPLEX_ZERO","COMPLEX_ONE","COMPLEX_I","complex","re","im","isComplexZero","z","complexAdd","complexSub","complexMul","complexDiv","complexNeg","complexConjugate","complexNormSquared","complexPow","complexEquals","formatComplex","magnitude","imaginary","exactComplexSqrt","modulus","exactRationalSqrt","two","realPart","imaginaryPart","exactBigintSqrt","previous","current","SYMBOLIC_MAX_NODES","constNode","varNode","name","powNode","callNode","args","symbolicKey","node","nodesEqual","other","arg","i","nodeCount","limit","pending","total","freeVariables","names","collectVariables","into","substitute","variable","replacement","complexNode","EXPAND_MAX_POW_EXPONENT","POLYNOMIAL_MAX_TERMS","POLYNOMIAL_MAX_DEGREE","monomialToKey","monomial","monomialFromKey","key","caret","monomialDegree","build","terms","kept","coeff","constantPolynomial","polyAdd","existing","polySub","polyScale","polyMul","leftKey","leftCoeff","leftMonomial","rightKey","rightCoeff","combined","polyPow","p","next","k","polyDegree","highest","degree","polyUnivariateVar","polyCoefficients","coefficients","toPolynomial","allowDistribution","operand","compareMonomials","vars","degreeDifference","difference","monomialToNode","termToNode","fromPolynomial","keys","firstPositive","expandSymbolic","polynomial","trim","last","isZeroPolynomial","polynomialDivide","dividend","divisorDegree","leading","quotient","offset","monic","trimmed","coefficient","coefficientGcd","polynomialGcd","sharedVariable","coefficientsToPolynomial","power","cancelRational","gcdCoefficients","reducedNumerator","reducedDenominator","cancelSymbolic","reduced","divideOutConstant","original","constant","squareFreePart","derivative","shared","exactIntegerSqrt","exactIntegerCbrt","negative","low","high","middle","cube","surdNode","radicand","extracted","square","scale","root","signedSurdNode","flattenSum","negated","out","depth","MAX_SIMPLIFY_DEPTH","collectTerms","flat","order","coeffByName","term","termNodes","collectSum","rationalFloor","truncated","MAX_FOLDED_FACTORIAL","foldCall","first","rootN","rootD","simplifySymbolic","depthOnEntry","walkDepth","simplifyNode","simplified","simplifyNodeAt","asComplex","foldComplexBinary","kind","foldComplexCall","foldedAdd","foldedSub","foldedMul","foldedDiv","cancelled","product","folded","complexFolded","tryExtractCoeffVar","tryExtractCoeffPow","isAtomic","formatCoefficient","text","MAX_FORMAT_DEPTH","ELIDED","formatFactor","formatSum","coeffVar","coeffPow","inner","needsBrackets","collectDisplayTerms","isNegative","negativeReal","negativeImaginary","formatSymbolic","thrown","index","matIndex","m","matAt","row","col","inBounds","sameShape","isSquare","entryToSymbolic","entry","symbolicToEntry","matrixEntryToValue","cell","boolValue","symbolicValue","numberValue","rowMajorToColumnMajor","rows","cols","rowMajorData","data","c","columnMajorToRowMajor","matrixMultiply","l","lIsScalar","rIsScalar","useSymbolic","scalarOperand","matrixOperand","scalarNode","v","matrixValue","scalar","errorValue","resultRows","resultCols","checkedArray","acc","sum","matrixPower","n","identity","accumulated","squared","doubled","matrixCompare","cmp","transpose","toWorkingRows","EXACT_DETERMINANT_DIMENSION_LIMIT","toIntegerRows","integerDeterminant","candidate","swapped","j","numericDeterminant","integers","det","pivotRow","maxAbs","tmp","symbolicDeterminant","pivot","determinant","numericInverse","SYMBOLIC_INVERSE_DIMENSION_LIMIT","symbolicInverse","inverse","tooLarge","length","maxElements","collectionToValues","faulted","faultedOperand","DEFAULT_DIVISION_SCALE","POW10","pow10","makeDecimal","coef","decimalFromInteger","decimalFromNumberIfExact","decimalFromLiteral","s","dot","intPart","fracPart","align","decimalAdd","ca","cb","decimalSubtract","decimalMultiply","decimalNegate","decimalIsZero","roundCoefToScale","targetScale","q","decimalRound","decimalDivide","maxFractionDigits","num","den","decimalCompare","decimalToString","cut","frac","decimalToNumber","decimalToFixed","rounded","CURRENCY_SYMBOL_ALIASES","CURRENCY_WORD_ALIASES","resolveCurrencyAlias","CURRENCY_DISPLAY"],"mappings":"qHAuCO,IAAMA,CAAAA,CAA0B,CAAE,CAAA,CAAG,EAAA,CAAI,EAAG,EAAG,CAAA,CAGzCC,CAAAA,CAAyB,CAAE,CAAA,CAAG,EAAA,CAAI,CAAA,CAAG,EAAG,EAGxCC,CAAAA,CAA+B,CAAE,CAAA,CAAG,CAAC,EAAA,CAAI,CAAA,CAAG,EAAG,CAAA,CAa/C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AE,MAAA,CAAQ,IAAA,CAAM,QAAA,CAAU,QAAA,CAAU,OAAQ,IAAK,CAAA,CACtD,GAAA,CAAK,CAAE,OAAQ,SAAA,CAAM,QAAA,CAAU,QAAA,CAAU,MAAA,CAAQ,IAAK,CACxD","file":"chunk-ZOOVGXMK.cjs","sourcesContent":["/**\n * Exact rational arithmetic over `bigint`, the coefficient type for every\n * part of the symbolic algebra system.\n *\n * A computer-algebra system cannot work in IEEE doubles. Factoring\n * `x^2 - x/3 - 2/3` needs `1/3` to stay `1/3` rather than becoming\n * `0.3333333333333333`, and the rational-root theorem tests candidate roots\n * by exact division, where a rounding error is indistinguishable from a\n * genuine root. Every coefficient in `SymbolicNode`, `Polynomial`, `Factor`\n * and `Solve` is a Rational for that reason.\n *\n * Values are always normalized on construction (`d > 0n`, `gcd(|n|, d) === 1n`,\n * zero is exactly `0n/1n`), so structural equality on the `{n, d}` pair is\n * mathematical equality, and the pair can be used directly as a cache key.\n *\n * A Rational holds two `bigint`s. Structured clone, which is what the\n * playground's `postMessage` uses to ship a `SymbolicNode` to the VM trace\n * view, handles bigint correctly. `JSON.stringify` does not: it throws\n * `TypeError: Do not know how to serialize a BigInt`. Do not introduce a JSON\n * round-trip anywhere a Rational can reach.\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * An exact rational number.\n *\n * Always normalized, see this module's own doc comment for the invariant.\n * Construct via {@link rational} or {@link rationalFromNumber} rather than as\n * an object literal, which would bypass normalization.\n */\nexport interface Rational {\n\t/** Signed numerator. Carries the sign of the whole value. */\n\treadonly n: bigint;\n\t/** Denominator, always strictly positive. */\n\treadonly d: bigint;\n}\n\n/** The rational `0`. */\nexport const RATIONAL_ZERO: Rational = { n: 0n, d: 1n };\n\n/** The rational `1`. */\nexport const RATIONAL_ONE: Rational = { n: 1n, d: 1n };\n\n/** The rational `-1`. */\nexport const RATIONAL_MINUS_ONE: Rational = { n: -1n, d: 1n };\n\n/**\n * Magnitude ceiling, in bits, on either component of a Rational.\n *\n * Repeated exact elimination (a symbolic matrix inverse, synthetic division\n * down a long factor chain) multiplies denominators together, so an unbounded\n * Rational can grow until bigint arithmetic itself becomes the bottleneck.\n * 4096 bits is far beyond any coefficient a human writes, while still bounding\n * a single multiply to microseconds. Follows the precedent set by\n * `vm/MatrixOps.ts`'s own `SYMBOLIC_INVERSE_DIMENSION_LIMIT`: a named\n * constant with a stated reason rather than an arbitrary inline number.\n */\nexport const RATIONAL_MAX_BITS = 4096;\n\n/** Precomputed `2 ** RATIONAL_MAX_BITS`, so the guard is one comparison rather than a `toString(2)` walk. */\nconst MAX_MAGNITUDE = 1n << BigInt(RATIONAL_MAX_BITS);\n\n/**\n * Bigint exponentiation by repeated squaring.\n *\n * Written out rather than using `**`, deliberately. The test tsconfig targets\n * ES6, where TypeScript lowers `a ** b` to `Math.pow(a, b)`, and `Math.pow`\n * throws `TypeError: Cannot convert a BigInt value to a number`. So `10n ** 3n`\n * compiles fine and passes a typecheck, then fails only at runtime under the\n * test target. Do not reintroduce `**` on bigints anywhere in this module.\n */\nfunction bigintPow(base: bigint, exponent: bigint): bigint {\n\tlet result = 1n;\n\tlet factor = base;\n\tlet remaining = exponent;\n\twhile (remaining > 0n) {\n\t\tif (remaining % 2n === 1n) result *= factor;\n\t\tfactor *= factor;\n\t\tremaining /= 2n;\n\t}\n\treturn result;\n}\n\n/** Euclid's algorithm on absolute values. Returns `0n` only when both inputs are zero. */\nfunction gcd(a: bigint, b: bigint): bigint {\n\tlet x = a < 0n ? -a : a;\n\tlet y = b < 0n ? -b : b;\n\twhile (y !== 0n) {\n\t\tconst remainder = x % y;\n\t\tx = y;\n\t\ty = remainder;\n\t}\n\treturn x;\n}\n\n/** Raises {@link RATIONAL_MAX_BITS} as an error rather than letting bigint growth run away silently. */\nfunction guardMagnitude(n: bigint, d: bigint): void {\n\tconst magnitude = n < 0n ? -n : n;\n\tif (magnitude >= MAX_MAGNITUDE || d >= MAX_MAGNITUDE) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_RATIONAL_OVERFLOW\",\n\t\t\t`This calculation produced a fraction too large to represent exactly (over ${RATIONAL_MAX_BITS} bits).`,\n\t\t\t{ limitBits: RATIONAL_MAX_BITS },\n\t\t);\n\t}\n}\n\n/**\n * Reduces a numerator/denominator pair to the normalized form this module\n * guarantees everywhere.\n *\n * @param n - Numerator, may be negative.\n * @param d - Denominator, may be negative, must not be zero.\n * @returns The normalized rational.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` when `d` is zero,\n * `SYMBOLIC_RATIONAL_OVERFLOW` past {@link RATIONAL_MAX_BITS}.\n */\nfunction normalize(n: bigint, d: bigint): Rational {\n\tif (d === 0n) {\n\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Division by zero in a symbolic expression.\");\n\t}\n\tif (n === 0n) return RATIONAL_ZERO;\n\n\t// Carry the sign on the numerator so `d > 0n` always holds, which is what\n\t// lets rationalCompare() cross-multiply without tracking sign flips.\n\tlet numerator = d < 0n ? -n : n;\n\tlet denominator = d < 0n ? -d : d;\n\n\tconst divisor = gcd(numerator, denominator);\n\tnumerator /= divisor;\n\tdenominator /= divisor;\n\n\tguardMagnitude(numerator, denominator);\n\treturn { n: numerator, d: denominator };\n}\n\n/**\n * Builds a normalized rational from bigint components.\n *\n * @param numerator - The numerator.\n * @param denominator - The denominator, defaulting to `1n`.\n * @returns The normalized rational.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` when `denominator` is zero.\n */\nexport function rational(numerator: bigint, denominator: bigint = 1n): Rational {\n\treturn normalize(numerator, denominator);\n}\n\n/** Matches every form `Number.prototype.toString` produces for a finite value, including the `e±n` variants used outside `[1e-6, 1e21)`. */\nconst DECIMAL_FORM = /^(-?)(\\d+)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;\n\n/**\n * Converts a JavaScript number to its exact rational value **as written**,\n * via the decimal string form rather than the IEEE expansion.\n *\n * This distinction is the single sharpest edge in this module. The double\n * nearest to `0.1` is exactly `3602879701896397 / 36028797018963968`, which is\n * mathematically correct and useless to display or factor with. Going through\n * `String(0.1)`, which is `\"0.1\"`, yields `1/10`: the number the user actually\n * typed. `Number.prototype.toString` is specified to emit the shortest decimal\n * that round-trips, so this is well defined rather than a heuristic.\n *\n * @param value - Any finite number.\n * @returns The exact rational for that number's decimal representation.\n * @throws {EngineError} `SYMBOLIC_NONFINITE_OPERAND` for `NaN` or `±Infinity`,\n * neither of which has a rational image.\n */\nexport function rationalFromNumber(value: number): Rational {\n\tif (!Number.isFinite(value)) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_NONFINITE_OPERAND\",\n\t\t\t`\"${String(value)}\" has no exact value, so it cannot appear in a symbolic expression.`,\n\t\t\t{ value: String(value) },\n\t\t);\n\t}\n\tif (Number.isInteger(value)) return normalize(BigInt(value), 1n);\n\n\tconst parts = DECIMAL_FORM.exec(String(value));\n\tif (parts === null) {\n\t\tthrow ErrorFactory.internal(\n\t\t\t\"INTERNAL_RATIONAL_PARSE\",\n\t\t\t`Internal error: could not read \"${String(value)}\" as a decimal number.`,\n\t\t\t{ value: String(value) },\n\t\t);\n\t}\n\n\tconst [, sign, integerDigits, fractionDigits = \"\", exponentDigits] = parts;\n\tlet numerator = BigInt(integerDigits + fractionDigits);\n\tlet denominator = bigintPow(10n, BigInt(fractionDigits.length));\n\n\tconst exponent = exponentDigits === undefined ? 0 : Number(exponentDigits);\n\tif (exponent > 0) numerator *= bigintPow(10n, BigInt(exponent));\n\telse if (exponent < 0) denominator *= bigintPow(10n, BigInt(-exponent));\n\n\treturn normalize(sign === \"-\" ? -numerator : numerator, denominator);\n}\n\n/**\n * Approximates a rational as a double, for the boundary back into ordinary\n * numeric Values and matrix cells.\n *\n * @param r - The rational.\n * @returns The nearest double, or `±Infinity` when the value genuinely\n * exceeds double range.\n */\nexport function rationalToNumber(r: Rational): number {\n\tif (r.d === 1n) return Number(r.n);\n\n\tconst direct = Number(r.n) / Number(r.d);\n\tif (!Number.isNaN(direct)) return direct;\n\n\t// Both components individually overflow a double, so the naive division is\n\t// Infinity/Infinity. Dividing in bigint space with 64 guard bits first\n\t// keeps the ratio, and scaling back by a power of two is exact in binary\n\t// floating point.\n\tconst GUARD_BITS = 64n;\n\treturn Number((r.n << GUARD_BITS) / r.d) / 2 ** 64;\n}\n\n/**\n * Exact addition.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a + b`, normalized.\n */\nexport function rationalAdd(a: Rational, b: Rational): Rational {\n\treturn normalize(a.n * b.d + b.n * a.d, a.d * b.d);\n}\n\n/**\n * Exact subtraction.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a - b`, normalized.\n */\nexport function rationalSub(a: Rational, b: Rational): Rational {\n\treturn normalize(a.n * b.d - b.n * a.d, a.d * b.d);\n}\n\n/**\n * Exact multiplication.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a * b`, normalized.\n */\nexport function rationalMul(a: Rational, b: Rational): Rational {\n\treturn normalize(a.n * b.n, a.d * b.d);\n}\n\n/**\n * Exact division.\n *\n * @param a - Dividend.\n * @param b - Divisor.\n * @returns `a / b`, normalized.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` when `b` is zero.\n */\nexport function rationalDiv(a: Rational, b: Rational): Rational {\n\tif (b.n === 0n) {\n\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Division by zero in a symbolic expression.\");\n\t}\n\treturn normalize(a.n * b.d, a.d * b.n);\n}\n\n/**\n * Exact negation.\n *\n * @param r - The rational to negate.\n * @returns `-r`. Already normalized, since negating cannot change the gcd.\n */\nexport function rationalNeg(r: Rational): Rational {\n\treturn r.n === 0n ? RATIONAL_ZERO : { n: -r.n, d: r.d };\n}\n\n/**\n * Exact integer power, including negative exponents (which invert the base).\n *\n * @param base - The base.\n * @param exponent - Integer exponent, may be negative.\n * @returns `base ** exponent`, normalized.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` for a zero base raised to a\n * negative exponent.\n */\nexport function rationalPow(base: Rational, exponent: bigint): Rational {\n\tif (exponent === 0n) return RATIONAL_ONE;\n\tif (exponent < 0n) {\n\t\tif (base.n === 0n) {\n\t\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Zero raised to a negative power is undefined.\");\n\t\t}\n\t\tconst positive = -exponent;\n\t\treturn normalize(bigintPow(base.d, positive), bigintPow(base.n, positive));\n\t}\n\treturn normalize(bigintPow(base.n, exponent), bigintPow(base.d, exponent));\n}\n\n/**\n * Three-way comparison.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `-1` when `a < b`, `0` when equal, `1` when `a > b`.\n */\nexport function rationalCompare(a: Rational, b: Rational): -1 | 0 | 1 {\n\t// Both denominators are positive by the normalization invariant, so\n\t// cross-multiplying cannot flip the inequality.\n\tconst left = a.n * b.d;\n\tconst right = b.n * a.d;\n\tif (left < right) return -1;\n\tif (left > right) return 1;\n\treturn 0;\n}\n\n/**\n * Whether a rational is exactly zero.\n *\n * The reason this exists rather than a `=== 0` on a double: a pivot that is\n * structurally zero can arrive as `5.551e-17` in floating point, so\n * `vm/MatrixOps.ts` used to treat a singular symbolic matrix as invertible.\n * With exact coefficients the test is decisive.\n *\n * @param r - The rational.\n * @returns True when `r` is zero.\n */\nexport function isRationalZero(r: Rational): boolean {\n\treturn r.n === 0n;\n}\n\n/**\n * Whether a rational is exactly one.\n *\n * @param r - The rational.\n * @returns True when `r` is one.\n */\nexport function isRationalOne(r: Rational): boolean {\n\treturn r.n === 1n && r.d === 1n;\n}\n\n/**\n * Whether a rational is exactly negative one.\n *\n * @param r - The rational.\n * @returns True when `r` is minus one.\n */\nexport function isRationalMinusOne(r: Rational): boolean {\n\treturn r.n === -1n && r.d === 1n;\n}\n\n/**\n * Whether a rational is a whole number.\n *\n * @param r - The rational.\n * @returns True when the denominator is one, which after normalization is the\n * only way a rational can be integral.\n */\nexport function isRationalInteger(r: Rational): boolean {\n\treturn r.d === 1n;\n}\n\n/**\n * Longest exact decimal this module will render in full.\n *\n * Ten digits matches what the previous double-based formatter produced, so\n * display width does not regress.\n */\nconst MAX_DECIMAL_DIGITS = 10;\n\n/**\n * Largest component either side of a fraction may have and still be shown as\n * one.\n *\n * This is what stops an exact conversion from being unreadable. `sqrt(2)`\n * evaluates numerically to `1.4142135623730951`, whose exact rational value is\n * `14142135623730951/10000000000000000`: correct, and useless on screen. A\n * fraction is only clearer than a decimal when its parts are small enough to\n * recognise, so past this bound the rounded decimal wins.\n */\nconst MAX_FRACTION_COMPONENT = 1_000_000n;\n\n/**\n * Renders a rational for display.\n *\n * A whole number prints as digits (`2`). A fraction whose denominator divides\n * a power of ten prints as its exact decimal (`2.5`), since that is how a user\n * wrote it and how they expect to read it back. Anything else prints as\n * `n/d` (`1/3`), which is exact where a decimal would have to lie.\n *\n * @param r - The rational to render.\n * @returns The display string, with a leading minus for negative values.\n */\nexport function formatRational(r: Rational): string {\n\tif (r.d === 1n) return String(r.n);\n\n\t// A fraction terminates in base ten exactly when its denominator's only\n\t// prime factors are 2 and 5. Strip those and see what is left.\n\tlet remaining = r.d;\n\tlet twos = 0;\n\tlet fives = 0;\n\twhile (remaining % 2n === 0n) {\n\t\tremaining /= 2n;\n\t\ttwos++;\n\t}\n\twhile (remaining % 5n === 0n) {\n\t\tremaining /= 5n;\n\t\tfives++;\n\t}\n\n\tconst terminates = remaining === 1n;\n\tconst decimals = Math.max(twos, fives);\n\tif (!terminates || decimals > MAX_DECIMAL_DIGITS) {\n\t\tconst magnitude = r.n < 0n ? -r.n : r.n;\n\t\tif (magnitude <= MAX_FRACTION_COMPONENT && r.d <= MAX_FRACTION_COMPONENT) return `${r.n}/${r.d}`;\n\t\t// Too large to read as a fraction, so fall back to the same rounded\n\t\t// decimal the previous double-based formatter produced.\n\t\treturn String(Math.round(rationalToNumber(r) * 1e10) / 1e10);\n\t}\n\n\tconst scaled = (r.n < 0n ? -r.n : r.n) * bigintPow(10n, BigInt(decimals)) / r.d;\n\tconst digits = String(scaled).padStart(decimals + 1, \"0\");\n\tconst whole = digits.slice(0, digits.length - decimals);\n\tconst fraction = digits.slice(digits.length - decimals).replace(/0+$/, \"\");\n\tconst sign = r.n < 0n ? \"-\" : \"\";\n\treturn fraction.length === 0 ? `${sign}${whole}` : `${sign}${whole}.${fraction}`;\n}\n","/**\n * Exact complex arithmetic over the Gaussian rationals.\n *\n * Both components are {@link Rational}, so this is exact in the same sense the\n * rest of the system is: `(1+2i)/(3-4i)` has an exact answer and gets it,\n * rather than a pair of doubles that are nearly right. That matters most where\n * a complex value has to be recognised as zero, which is how a cubic's\n * *casus irreducibilis* is detected and how a conjugate pair cancels.\n *\n * ## Why the number tower stops here\n *\n * Real values stay {@link Rational} throughout. A complex value only appears\n * when something genuinely produces one: a negative discriminant, a square root\n * of a negative number, or an explicit `i`. That keeps every real-only path\n * paying nothing for complex support, and it keeps `factor` and `solve` working\n * over the rationals by default, which is what a CAS is expected to do.\n *\n * A complex whose imaginary part is zero is collapsed back to a real constant\n * at the boundary, so `(1+i)*(1-i)` reads as `2` rather than `2+0i`.\n */\n\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalZero,\n\tisRationalOne,\n\tformatRational,\n} from \"@solve-js/symbolic/Rational\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * An exact complex number, `re + im * i`, with both parts rational.\n *\n * Construct through {@link complex} rather than as an object literal, so the\n * real-collapse convention below stays consistent.\n */\nexport interface Complex {\n\t/** Real part. */\n\treadonly re: Rational;\n\t/** Imaginary part. Zero means this value is really a real number. */\n\treadonly im: Rational;\n}\n\n/** The complex zero. */\nexport const COMPLEX_ZERO: Complex = { re: RATIONAL_ZERO, im: RATIONAL_ZERO };\n\n/** The complex one. */\nexport const COMPLEX_ONE: Complex = { re: RATIONAL_ONE, im: RATIONAL_ZERO };\n\n/** The imaginary unit. */\nexport const COMPLEX_I: Complex = { re: RATIONAL_ZERO, im: RATIONAL_ONE };\n\n/**\n * Builds a complex number from its two parts.\n *\n * @param re - Real part.\n * @param im - Imaginary part, defaulting to zero.\n * @returns The complex value.\n */\nexport function complex(re: Rational, im: Rational = RATIONAL_ZERO): Complex {\n\treturn { re, im };\n}\n\n/**\n * Whether a complex value is really a real one.\n *\n * @param z - The value to test.\n * @returns True when the imaginary part is exactly zero. Exact, which is the\n * point: in floating point a conjugate pair's imaginary parts cancel to\n * something near zero but rarely to zero, so a real answer would keep an\n * imaginary trace forever.\n */\nexport function isReal(z: Complex): boolean {\n\treturn isRationalZero(z.im);\n}\n\n/**\n * Whether a complex value is exactly zero.\n *\n * @param z - The value to test.\n * @returns True when both parts are zero.\n */\nexport function isComplexZero(z: Complex): boolean {\n\treturn isRationalZero(z.re) && isRationalZero(z.im);\n}\n\n/**\n * Whether a complex value is exactly one.\n *\n * @param z - The value to test.\n * @returns True when it equals one.\n */\nexport function isComplexOne(z: Complex): boolean {\n\treturn isRationalOne(z.re) && isRationalZero(z.im);\n}\n\n/**\n * Exact addition.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a + b`.\n */\nexport function complexAdd(a: Complex, b: Complex): Complex {\n\treturn { re: rationalAdd(a.re, b.re), im: rationalAdd(a.im, b.im) };\n}\n\n/**\n * Exact subtraction.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a - b`.\n */\nexport function complexSub(a: Complex, b: Complex): Complex {\n\treturn { re: rationalSub(a.re, b.re), im: rationalSub(a.im, b.im) };\n}\n\n/**\n * Exact multiplication.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a * b`, by the usual `(ac - bd) + (ad + bc)i`.\n */\nexport function complexMul(a: Complex, b: Complex): Complex {\n\treturn {\n\t\tre: rationalSub(rationalMul(a.re, b.re), rationalMul(a.im, b.im)),\n\t\tim: rationalAdd(rationalMul(a.re, b.im), rationalMul(a.im, b.re)),\n\t};\n}\n\n/**\n * Exact division, by multiplying through by the conjugate.\n *\n * @param a - Dividend.\n * @param b - Divisor.\n * @returns `a / b`.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` when `b` is zero.\n */\nexport function complexDiv(a: Complex, b: Complex): Complex {\n\tif (isComplexZero(b)) {\n\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Division by zero in a complex expression.\");\n\t}\n\t// |b|^2, which is real and non-zero, so the two component divisions are exact.\n\tconst denominator = rationalAdd(rationalMul(b.re, b.re), rationalMul(b.im, b.im));\n\treturn {\n\t\tre: rationalDiv(rationalAdd(rationalMul(a.re, b.re), rationalMul(a.im, b.im)), denominator),\n\t\tim: rationalDiv(rationalSub(rationalMul(a.im, b.re), rationalMul(a.re, b.im)), denominator),\n\t};\n}\n\n/**\n * Exact negation.\n *\n * @param z - The value to negate.\n * @returns `-z`.\n */\nexport function complexNeg(z: Complex): Complex {\n\treturn { re: rationalNeg(z.re), im: rationalNeg(z.im) };\n}\n\n/**\n * The complex conjugate.\n *\n * @param z - The value.\n * @returns `z` with the sign of its imaginary part flipped.\n */\nexport function complexConjugate(z: Complex): Complex {\n\treturn { re: z.re, im: rationalNeg(z.im) };\n}\n\n/**\n * The squared modulus, which stays exact where the modulus itself would not.\n *\n * @param z - The value.\n * @returns `re^2 + im^2`, a rational. The modulus is its square root, which is\n * usually irrational, so callers wanting a magnitude should take the root of\n * this rather than expect one here.\n */\nexport function complexNormSquared(z: Complex): Rational {\n\treturn rationalAdd(rationalMul(z.re, z.re), rationalMul(z.im, z.im));\n}\n\n/**\n * Exact integer power, by repeated squaring.\n *\n * @param base - The base.\n * @param exponent - Integer exponent, which may be negative.\n * @returns `base ** exponent`.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` for a zero base raised to a\n * negative power.\n */\nexport function complexPow(base: Complex, exponent: bigint): Complex {\n\tif (exponent === 0n) return COMPLEX_ONE;\n\tif (exponent < 0n) {\n\t\tif (isComplexZero(base)) {\n\t\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Zero raised to a negative power is undefined.\");\n\t\t}\n\t\treturn complexDiv(COMPLEX_ONE, complexPow(base, -exponent));\n\t}\n\tlet result = COMPLEX_ONE;\n\tlet factor = base;\n\tlet remaining = exponent;\n\twhile (remaining > 0n) {\n\t\tif (remaining % 2n === 1n) result = complexMul(result, factor);\n\t\tfactor = complexMul(factor, factor);\n\t\tremaining /= 2n;\n\t}\n\treturn result;\n}\n\n/**\n * Structural equality.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns True when both parts match. Exact, so this is mathematical equality\n * rather than a tolerance comparison.\n */\nexport function complexEquals(a: Complex, b: Complex): boolean {\n\treturn a.re.n === b.re.n && a.re.d === b.re.d && a.im.n === b.im.n && a.im.d === b.im.d;\n}\n\n/**\n * Renders a complex number the way it is written.\n *\n * `3i` rather than `0+3i`, `2-i` rather than `2+-1i`, and a bare real when the\n * imaginary part has vanished.\n *\n * @param z - The value to render.\n * @returns The display string.\n */\nexport function formatComplex(z: Complex): string {\n\tif (isRationalZero(z.im)) return formatRational(z.re);\n\n\tconst magnitude = z.im.n < 0n ? rationalNeg(z.im) : z.im;\n\t// A unit coefficient is written as a bare `i`, the way a person writes it.\n\tconst imaginary = isRationalOne(magnitude) ? \"i\" : `${formatRational(magnitude)}i`;\n\n\tif (isRationalZero(z.re)) return z.im.n < 0n ? `-${imaginary}` : imaginary;\n\treturn z.im.n < 0n ? `${formatRational(z.re)}-${imaginary}` : `${formatRational(z.re)}+${imaginary}`;\n}\n\n/**\n * The exact square roots of a complex number, when both are Gaussian rational.\n *\n * A square root is only exact here when the result stays in the Gaussian\n * rationals, which needs `|z|` and then the two components each to be rational\n * squares. `sqrt(-4)` is exactly `2i`; `sqrt(i)` is not rational and comes back\n * `null` so the caller can leave it symbolic rather than approximate it.\n *\n * @param z - The value to take the root of.\n * @returns The principal root, or `null` when it is not a Gaussian rational.\n */\nexport function exactComplexSqrt(z: Complex): Complex | null {\n\tif (isComplexZero(z)) return COMPLEX_ZERO;\n\n\t// |z| must be rational for either component to be.\n\tconst modulus = exactRationalSqrt(complexNormSquared(z));\n\tif (modulus === null) return null;\n\n\t// The standard half-angle construction: re' = sqrt((|z| + re)/2).\n\tconst two: Rational = { n: 2n, d: 1n };\n\tconst realPart = exactRationalSqrt(rationalDiv(rationalAdd(modulus, z.re), two));\n\tif (realPart === null) return null;\n\n\tif (isRationalZero(realPart)) {\n\t\t// z is a negative real, so the root is purely imaginary.\n\t\tconst imaginaryPart = exactRationalSqrt(rationalDiv(rationalSub(modulus, z.re), two));\n\t\treturn imaginaryPart === null ? null : { re: RATIONAL_ZERO, im: imaginaryPart };\n\t}\n\n\tconst imaginaryPart = rationalDiv(z.im, rationalMul(two, realPart));\n\treturn { re: realPart, im: imaginaryPart };\n}\n\n/** Exact square root of a non-negative rational, or `null` when it is irrational. */\nfunction exactRationalSqrt(value: Rational): Rational | null {\n\tif (value.n < 0n) return null;\n\tconst numerator = exactBigintSqrt(value.n);\n\tconst denominator = exactBigintSqrt(value.d);\n\treturn numerator === null || denominator === null ? null : { n: numerator, d: denominator };\n}\n\n/** Exact integer square root, or `null` when `value` is not a perfect square. */\nfunction exactBigintSqrt(value: bigint): bigint | null {\n\tif (value < 0n) return null;\n\tif (value < 2n) return value;\n\tlet previous = value;\n\tlet current = (value + 1n) / 2n;\n\twhile (current < previous) {\n\t\tprevious = current;\n\t\tcurrent = (previous + value / previous) / 2n;\n\t}\n\treturn previous * previous === value ? previous : null;\n}\n","/**\n * The symbolic expression tree: an algebraic formula over free variables,\n * rather than a concrete number.\n *\n * This is the data type the whole symbolic algebra system manipulates. It is\n * deliberately a plain discriminated union of immutable object literals, not a\n * class hierarchy, so a node can cross the worker boundary by structured clone\n * (see `diagnostics/events.ts`, which carries these in its VM trace payload)\n * and so pattern matching in the simplifier stays exhaustive under the\n * compiler's own checking.\n *\n * Two variants exist here that the original bounded simplifier did not have,\n * and they are what unlocks the rest of the system:\n *\n * - `pow` gives exponentiation a representation. Without it `x^2` had nowhere\n * to go, and `OpCode.EXP` fell through to `Math.pow(0, 2)` because\n * `Value.toNumber()` reports `0` for a symbolic operand, so `x^2 + 3x + 2`\n * silently evaluated to `3x+2`. Polynomials, derivatives and roots all need it.\n * - `call` gives function application a representation, so `sqrt(x)` and\n * `sin(x)` carry through a symbolic expression instead of collapsing to\n * `sqrt(0)`.\n *\n * Coefficients are exact rationals, never doubles. See `Rational.ts` for why.\n */\n\nimport type { Rational } from \"@solve-js/symbolic/Rational\";\nimport { rationalFromNumber } from \"@solve-js/symbolic/Rational\";\nimport type { Complex } from \"@solve-js/symbolic/Complex\";\nimport { complexEquals } from \"@solve-js/symbolic/Complex\";\n\n/**\n * A symbolic (algebraic) expression tree.\n *\n * Build nodes through the constructor functions in this module rather than as\n * object literals, so constants normalize consistently.\n */\nexport type SymbolicNode =\n\t| { kind: \"const\"; value: Rational }\n\t| { kind: \"complex\"; value: Complex }\n\t| { kind: \"var\"; name: string }\n\t| { kind: \"add\"; left: SymbolicNode; right: SymbolicNode }\n\t| { kind: \"sub\"; left: SymbolicNode; right: SymbolicNode }\n\t| { kind: \"mul\"; left: SymbolicNode; right: SymbolicNode }\n\t| { kind: \"div\"; left: SymbolicNode; right: SymbolicNode }\n\t| { kind: \"neg\"; operand: SymbolicNode }\n\t| { kind: \"pow\"; base: SymbolicNode; exponent: SymbolicNode }\n\t| { kind: \"call\"; name: string; args: readonly SymbolicNode[] };\n\n/**\n * Ceiling on the size of a tree the simplifier will accept.\n *\n * Simplification itself never grows a tree (see `Simplify.ts`'s stated\n * invariant), but a tree can arrive already large from repeated symbolic\n * matrix elimination, and every rule walks it. Ten thousand nodes is orders of\n * magnitude beyond any hand-written expression while still bounding a single\n * simplify to milliseconds.\n */\nexport const SYMBOLIC_MAX_NODES = 10_000;\n\n/**\n * A literal number in a symbolic expression.\n *\n * Accepts a plain `number` as well as a {@link Rational} so that the many\n * existing call sites reading a numeric Value can pass it straight through;\n * the number is converted by its decimal form, so `constNode(0.1)` is exactly\n * one tenth.\n *\n * @param value - The number, as a double or an exact rational.\n * @returns A constant node the simplifier can fold.\n */\nexport function constNode(value: number | Rational): SymbolicNode {\n\treturn { kind: \"const\", value: typeof value === \"number\" ? rationalFromNumber(value) : value };\n}\n\n/**\n * An unresolved name in a symbolic expression.\n *\n * @param name - The variable name.\n * @returns A variable node, which the simplifier carries through rather than\n * evaluating.\n */\nexport function varNode(name: string): SymbolicNode {\n\treturn { kind: \"var\", name };\n}\n\n/**\n * An exponentiation in a symbolic expression.\n *\n * @param base - The base expression.\n * @param exponent - The exponent expression, which does not have to be constant.\n * @returns A power node.\n */\nexport function powNode(base: SymbolicNode, exponent: SymbolicNode): SymbolicNode {\n\treturn { kind: \"pow\", base, exponent };\n}\n\n/**\n * A function application in a symbolic expression.\n *\n * @param name - The function name, matching the builtin naming in\n * `vm/SymbolicOps.ts`'s own index table so the two surfaces agree.\n * @param args - The argument expressions.\n * @returns A call node.\n */\nexport function callNode(name: string, args: readonly SymbolicNode[]): SymbolicNode {\n\treturn { kind: \"call\", name, args };\n}\n\n/**\n * A stable structural key for a tree.\n *\n * Two trees produce the same key exactly when they are structurally identical,\n * so this serves both as the equality test and as a `Map` key for memoizing\n * simplification. Prefix form (`\"+(*(2,x),6)\"`) rather than a hash, because a\n * hash would need collision handling to be sound and these strings stay short\n * for the expressions that actually occur.\n *\n * @param node - The tree to key.\n * @returns The structural key.\n */\nexport function symbolicKey(node: SymbolicNode): string {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\t\treturn `${node.value.n}/${node.value.d}`;\n\t\tcase \"complex\":\n\t\t\treturn `C(${node.value.re.n}/${node.value.re.d},${node.value.im.n}/${node.value.im.d})`;\n\t\tcase \"var\":\n\t\t\treturn `v:${node.name}`;\n\t\tcase \"neg\":\n\t\t\treturn `-(${symbolicKey(node.operand)})`;\n\t\tcase \"pow\":\n\t\t\treturn `^(${symbolicKey(node.base)},${symbolicKey(node.exponent)})`;\n\t\tcase \"call\":\n\t\t\treturn `${node.name}(${node.args.map(symbolicKey).join(\",\")})`;\n\t\tcase \"add\":\n\t\t\treturn `+(${symbolicKey(node.left)},${symbolicKey(node.right)})`;\n\t\tcase \"sub\":\n\t\t\treturn `-(${symbolicKey(node.left)},${symbolicKey(node.right)})`;\n\t\tcase \"mul\":\n\t\t\treturn `*(${symbolicKey(node.left)},${symbolicKey(node.right)})`;\n\t\tcase \"div\":\n\t\t\treturn `/(${symbolicKey(node.left)},${symbolicKey(node.right)})`;\n\t}\n}\n\n/**\n * Structural equality between two trees.\n *\n * @param a - Left tree.\n * @param b - Right tree.\n * @returns True when the two are structurally identical. Note this is\n * structural, not mathematical: `x+1` and `1+x` are different trees.\n */\nexport function nodesEqual(a: SymbolicNode, b: SymbolicNode): boolean {\n\tif (a.kind !== b.kind) return false;\n\tswitch (a.kind) {\n\t\tcase \"const\": {\n\t\t\tconst other = b as typeof a;\n\t\t\treturn a.value.n === other.value.n && a.value.d === other.value.d;\n\t\t}\n\t\tcase \"complex\":\n\t\t\treturn complexEquals(a.value, (b as typeof a).value);\n\t\tcase \"var\":\n\t\t\treturn a.name === (b as typeof a).name;\n\t\tcase \"neg\":\n\t\t\treturn nodesEqual(a.operand, (b as typeof a).operand);\n\t\tcase \"pow\": {\n\t\t\tconst other = b as typeof a;\n\t\t\treturn nodesEqual(a.base, other.base) && nodesEqual(a.exponent, other.exponent);\n\t\t}\n\t\tcase \"call\": {\n\t\t\tconst other = b as typeof a;\n\t\t\tif (a.name !== other.name || a.args.length !== other.args.length) return false;\n\t\t\treturn a.args.every((arg, i) => nodesEqual(arg, other.args[i]));\n\t\t}\n\t\tcase \"add\":\n\t\tcase \"sub\":\n\t\tcase \"mul\":\n\t\tcase \"div\": {\n\t\t\tconst other = b as typeof a;\n\t\t\treturn nodesEqual(a.left, other.left) && nodesEqual(a.right, other.right);\n\t\t}\n\t}\n}\n\n/**\n * Counts the nodes in a tree.\n *\n * Used by the simplifier's own limit check, and by the property test enforcing\n * that no simplification rule ever grows a tree.\n *\n * @param node - The tree to measure.\n * @returns The total node count, including `node` itself.\n */\nexport function nodeCount(node: SymbolicNode, limit = Number.POSITIVE_INFINITY): number {\n\t// Iterative rather than recursive, and deliberately so. A deeply nested tree\n\t// (a long `a+b+c+...` chain builds one nested `add` per term) would overflow\n\t// the native call stack before a recursive walk could finish, which made the\n\t// SYMBOLIC_NODE_LIMIT_EXCEEDED guard unreachable in exactly the case it\n\t// exists for: the caller crashed instead of being told the tree was too big.\n\t//\n\t// `limit` lets the walk stop as soon as the answer can no longer matter,\n\t// so the size guard costs O(limit) rather than O(tree).\n\tconst pending: SymbolicNode[] = [node];\n\tlet total = 0;\n\twhile (pending.length > 0) {\n\t\tconst current = pending.pop()!;\n\t\ttotal++;\n\t\tif (total > limit) return total;\n\t\tswitch (current.kind) {\n\t\t\tcase \"const\":\n\t\t\tcase \"complex\":\n\t\t\tcase \"var\":\n\t\t\t\tbreak;\n\t\t\tcase \"neg\":\n\t\t\t\tpending.push(current.operand);\n\t\t\t\tbreak;\n\t\t\tcase \"pow\":\n\t\t\t\tpending.push(current.base, current.exponent);\n\t\t\t\tbreak;\n\t\t\tcase \"call\":\n\t\t\t\tfor (const arg of current.args) pending.push(arg);\n\t\t\t\tbreak;\n\t\t\tcase \"add\":\n\t\t\tcase \"sub\":\n\t\t\tcase \"mul\":\n\t\t\tcase \"div\":\n\t\t\t\tpending.push(current.left, current.right);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn total;\n}\n\n/**\n * Every variable name appearing anywhere in a tree.\n *\n * @param node - The tree to scan.\n * @returns The set of free variable names. Iteration order is first\n * appearance, which callers needing determinism should sort rather than rely on.\n */\nexport function freeVariables(node: SymbolicNode): ReadonlySet<string> {\n\tconst names = new Set<string>();\n\tcollectVariables(node, names);\n\treturn names;\n}\n\n/** Recursive worker for {@link freeVariables}, kept separate so the public entry point allocates one set rather than one per level. */\nfunction collectVariables(node: SymbolicNode, into: Set<string>): void {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\tcase \"complex\":\n\t\t\treturn;\n\t\tcase \"var\":\n\t\t\tinto.add(node.name);\n\t\t\treturn;\n\t\tcase \"neg\":\n\t\t\tcollectVariables(node.operand, into);\n\t\t\treturn;\n\t\tcase \"pow\":\n\t\t\tcollectVariables(node.base, into);\n\t\t\tcollectVariables(node.exponent, into);\n\t\t\treturn;\n\t\tcase \"call\":\n\t\t\tfor (const arg of node.args) collectVariables(arg, into);\n\t\t\treturn;\n\t\tcase \"add\":\n\t\tcase \"sub\":\n\t\tcase \"mul\":\n\t\tcase \"div\":\n\t\t\tcollectVariables(node.left, into);\n\t\t\tcollectVariables(node.right, into);\n\t}\n}\n\n/**\n * Replaces every occurrence of a variable with an expression.\n *\n * @param node - The tree to rewrite.\n * @param variable - The variable name to replace.\n * @param replacement - What to put in its place.\n * @returns A new tree. The input is not modified.\n */\nexport function substitute(node: SymbolicNode, variable: string, replacement: SymbolicNode): SymbolicNode {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\tcase \"complex\":\n\t\t\treturn node;\n\t\tcase \"var\":\n\t\t\treturn node.name === variable ? replacement : node;\n\t\tcase \"neg\":\n\t\t\treturn { kind: \"neg\", operand: substitute(node.operand, variable, replacement) };\n\t\tcase \"pow\":\n\t\t\treturn {\n\t\t\t\tkind: \"pow\",\n\t\t\t\tbase: substitute(node.base, variable, replacement),\n\t\t\t\texponent: substitute(node.exponent, variable, replacement),\n\t\t\t};\n\t\tcase \"call\":\n\t\t\treturn { kind: \"call\", name: node.name, args: node.args.map(arg => substitute(arg, variable, replacement)) };\n\t\tcase \"add\":\n\t\tcase \"sub\":\n\t\tcase \"mul\":\n\t\tcase \"div\":\n\t\t\treturn {\n\t\t\t\tkind: node.kind,\n\t\t\t\tleft: substitute(node.left, variable, replacement),\n\t\t\t\tright: substitute(node.right, variable, replacement),\n\t\t\t};\n\t}\n}\n\n/**\n * A complex literal in a symbolic expression.\n *\n * Collapses to an ordinary real constant when the imaginary part is zero, so\n * `(1+i)*(1-i)` reads as `2` rather than `2+0i`. That collapse is why callers\n * should build complex values through here rather than as an object literal.\n *\n * @param value - The exact complex value.\n * @returns A complex node, or a `const` node when the value is really real.\n */\nexport function complexNode(value: Complex): SymbolicNode {\n\tif (value.im.n === 0n) return { kind: \"const\", value: value.re };\n\treturn { kind: \"complex\", value };\n}\n","/**\n * A canonical sparse multivariate polynomial over the rationals, and the\n * conversion both ways between it and a {@link SymbolicNode} tree.\n *\n * The tree is the right representation for arbitrary expressions but the wrong\n * one for algebra: `2*b + 3*b` and `5*b` are different trees for the same\n * value, so deciding they are equal means pattern matching on shape. A\n * polynomial keyed by monomial gives one canonical form per value, which is\n * what makes expansion, term collection through a product, factoring and root\n * finding possible at all.\n *\n * ## Not every expression is a polynomial, and that is the point\n *\n * {@link toPolynomial} returns `null` rather than guessing whenever the input\n * falls outside the representation: a non-constant denominator, a non-integer\n * or symbolic exponent, or any function call. **Bias every ambiguous case\n * toward `null`.** A wrong polynomial is far worse than no polynomial, because\n * the caller silently gets an answer for a different expression.\n *\n * That null return is also load-bearing for existing behaviour. `vx/sx-tx` is a\n * rational function, not a polynomial, so it converts to `null` and keeps the\n * tree simplifier's own handling, which is what preserves the shipped symbolic\n * matrix inverse output.\n *\n * Nothing here is reachable from `simplifySymbolic`'s `mul` or `div` cases, and\n * `expandSymbolic` is never called by the simplifier at all. See `Simplify.ts`\n * for the invariant.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalZero,\n\tisRationalOne,\n\tRATIONAL_MINUS_ONE,\n\tisRationalInteger,\n} from \"@solve-js/symbolic/Rational\";\n\n/**\n * The canonical text form of one monomial.\n *\n * Variables appear in sorted order joined by `*`, an exponent of one is\n * written bare, and the constant term is the empty string. `\"x^2*y\"` is the\n * key for `x squared times y`. Sorting is what makes the key canonical, so\n * `y*x^2` and `x^2*y` cannot produce two different entries for one term.\n */\nexport type MonomialKey = string;\n\n/**\n * A polynomial as a sum of monomial terms with rational coefficients.\n *\n * Build one with {@link toPolynomial} rather than by hand, so the invariants\n * hold: no term ever carries a zero coefficient, and {@link Polynomial.vars} is\n * sorted.\n */\nexport interface Polynomial {\n\t/** Non-zero terms only. A zero polynomial has an empty map. */\n\treadonly terms: ReadonlyMap<MonomialKey, Rational>;\n\t/** Every variable appearing in any term, sorted, so output order is deterministic. */\n\treadonly vars: readonly string[];\n}\n\n/**\n * Largest exponent {@link toPolynomial} will multiply out.\n *\n * `(x+y)^n` has `n+1` terms in one variable but grows combinatorially in\n * several, so this bounds the work before it starts rather than after.\n */\nexport const EXPAND_MAX_POW_EXPONENT = 32;\n\n/**\n * Largest number of distinct terms a polynomial may carry.\n *\n * Multiplying two dense multivariate polynomials multiplies their term counts,\n * so this is the ceiling that stops a product chain from exhausting memory.\n */\nexport const POLYNOMIAL_MAX_TERMS = 2_000;\n\n/**\n * Largest total degree any single term may reach.\n *\n * Degree grows additively under multiplication and multiplicatively under\n * exponentiation, so an unbounded chain of either escapes quickly.\n */\nexport const POLYNOMIAL_MAX_DEGREE = 64;\n\n/** A monomial as a variable-to-exponent map. Exponents are always positive integers; a variable with exponent zero is removed. */\nexport type Monomial = Map<string, number>;\n\n/**\n * Serializes a monomial to its canonical {@link MonomialKey}.\n *\n * @param monomial - The exponent map.\n * @returns The key, with variables in sorted order and an exponent of one left\n * implicit, so `{x: 2, y: 1}` becomes `\"x^2*y\"`.\n */\nexport function monomialToKey(monomial: Monomial): MonomialKey {\n\tconst names = [...monomial.keys()].sort();\n\treturn names.map(name => (monomial.get(name) === 1 ? name : `${name}^${monomial.get(name)}`)).join(\"*\");\n}\n\n/**\n * Parses a canonical {@link MonomialKey} back into a variable-to-exponent map.\n *\n * @param key - The key to parse. The empty key is the constant monomial.\n * @returns The exponent map.\n */\nexport function monomialFromKey(key: MonomialKey): Monomial {\n\tconst monomial: Monomial = new Map();\n\tif (key === \"\") return monomial;\n\tfor (const factor of key.split(\"*\")) {\n\t\tconst caret = factor.indexOf(\"^\");\n\t\tif (caret === -1) monomial.set(factor, 1);\n\t\telse monomial.set(factor.slice(0, caret), Number(factor.slice(caret + 1)));\n\t}\n\treturn monomial;\n}\n\n/** Total degree of a monomial, the sum of its exponents. */\nfunction monomialDegree(key: MonomialKey): number {\n\tlet total = 0;\n\tfor (const exponent of monomialFromKey(key).values()) total += exponent;\n\treturn total;\n}\n\n/** Assembles a Polynomial from a term map, dropping zero coefficients and deriving the sorted variable list. */\nfunction build(terms: Map<MonomialKey, Rational>): Polynomial | null {\n\tconst kept = new Map<MonomialKey, Rational>();\n\tconst names = new Set<string>();\n\tfor (const [key, coeff] of terms) {\n\t\tif (isRationalZero(coeff)) continue;\n\t\tif (monomialDegree(key) > POLYNOMIAL_MAX_DEGREE) return null;\n\t\tkept.set(key, coeff);\n\t\tfor (const name of monomialFromKey(key).keys()) names.add(name);\n\t}\n\tif (kept.size > POLYNOMIAL_MAX_TERMS) return null;\n\treturn { terms: kept, vars: [...names].sort() };\n}\n\n/** The polynomial equal to a single rational constant. */\nfunction constantPolynomial(value: Rational): Polynomial {\n\treturn isRationalZero(value)\n\t\t? { terms: new Map(), vars: [] }\n\t\t: { terms: new Map([[\"\", value]]), vars: [] };\n}\n\n/**\n * Adds two polynomials.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns The sum, or `null` when a safety limit would be exceeded.\n */\nexport function polyAdd(a: Polynomial, b: Polynomial): Polynomial | null {\n\tconst terms = new Map(a.terms);\n\tfor (const [key, coeff] of b.terms) {\n\t\tconst existing = terms.get(key);\n\t\tterms.set(key, existing === undefined ? coeff : rationalAdd(existing, coeff));\n\t}\n\treturn build(terms);\n}\n\n/**\n * Subtracts one polynomial from another.\n *\n * @param a - Minuend.\n * @param b - Subtrahend.\n * @returns The difference, or `null` when a safety limit would be exceeded.\n */\nexport function polySub(a: Polynomial, b: Polynomial): Polynomial | null {\n\treturn polyAdd(a, polyScale(b, RATIONAL_MINUS_ONE));\n}\n\n/**\n * Multiplies two polynomials, distributing every term pair.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns The product, or `null` when a safety limit would be exceeded.\n */\nexport function polyMul(a: Polynomial, b: Polynomial): Polynomial | null {\n\t// The term count of a product is bounded by the product of the term counts,\n\t// so check before doing the work rather than after allocating it.\n\tif (a.terms.size * b.terms.size > POLYNOMIAL_MAX_TERMS) return null;\n\n\tconst terms = new Map<MonomialKey, Rational>();\n\tfor (const [leftKey, leftCoeff] of a.terms) {\n\t\tconst leftMonomial = monomialFromKey(leftKey);\n\t\tfor (const [rightKey, rightCoeff] of b.terms) {\n\t\t\tconst combined: Monomial = new Map(leftMonomial);\n\t\t\tfor (const [name, exponent] of monomialFromKey(rightKey)) {\n\t\t\t\tcombined.set(name, (combined.get(name) ?? 0) + exponent);\n\t\t\t}\n\t\t\tconst key = monomialToKey(combined);\n\t\t\tconst coeff = rationalMul(leftCoeff, rightCoeff);\n\t\t\tconst existing = terms.get(key);\n\t\t\tterms.set(key, existing === undefined ? coeff : rationalAdd(existing, coeff));\n\t\t}\n\t}\n\treturn build(terms);\n}\n\n/**\n * Raises a polynomial to a non-negative integer power by repeated multiplication.\n *\n * @param p - The base polynomial.\n * @param exponent - A non-negative integer exponent.\n * @returns The power, or `null` for a negative exponent, one past\n * {@link EXPAND_MAX_POW_EXPONENT}, or a safety-limit breach.\n */\nexport function polyPow(p: Polynomial, exponent: number): Polynomial | null {\n\tif (exponent < 0 || !Number.isInteger(exponent) || exponent > EXPAND_MAX_POW_EXPONENT) return null;\n\tlet result = constantPolynomial(RATIONAL_ONE);\n\tfor (let i = 0; i < exponent; i++) {\n\t\tconst next = polyMul(result, p);\n\t\tif (next === null) return null;\n\t\tresult = next;\n\t}\n\treturn result;\n}\n\n/**\n * Multiplies every coefficient by a rational.\n *\n * @param p - The polynomial.\n * @param k - The scale factor. Scaling by zero yields the zero polynomial.\n * @returns The scaled polynomial.\n */\nexport function polyScale(p: Polynomial, k: Rational): Polynomial {\n\tif (isRationalZero(k)) return { terms: new Map(), vars: [] };\n\tconst terms = new Map<MonomialKey, Rational>();\n\tfor (const [key, coeff] of p.terms) terms.set(key, rationalMul(coeff, k));\n\treturn { terms, vars: p.vars };\n}\n\n/**\n * The degree of a polynomial.\n *\n * @param p - The polynomial.\n * @param variable - When given, the highest exponent of that variable alone.\n * Otherwise the highest total degree across all terms.\n * @returns The degree. A zero polynomial has degree zero.\n */\nexport function polyDegree(p: Polynomial, variable?: string): number {\n\tlet highest = 0;\n\tfor (const key of p.terms.keys()) {\n\t\tconst degree = variable === undefined ? monomialDegree(key) : (monomialFromKey(key).get(variable) ?? 0);\n\t\tif (degree > highest) highest = degree;\n\t}\n\treturn highest;\n}\n\n/**\n * The single variable of a univariate polynomial.\n *\n * @param p - The polynomial.\n * @returns That variable's name, or `null` when the polynomial is constant or\n * involves more than one variable.\n */\nexport function polyUnivariateVar(p: Polynomial): string | null {\n\treturn p.vars.length === 1 ? p.vars[0] : null;\n}\n\n/**\n * Dense ascending coefficients of a univariate polynomial.\n *\n * @param p - The polynomial, which must involve no variable other than `variable`.\n * @param variable - The variable to read powers of.\n * @returns `[c0, c1, ..., cn]` where index `i` is the coefficient of\n * `variable^i`, with explicit zeros for absent powers.\n */\nexport function polyCoefficients(p: Polynomial, variable: string): Rational[] {\n\tconst degree = polyDegree(p, variable);\n\tconst coefficients: Rational[] = new Array(degree + 1).fill(RATIONAL_ZERO);\n\tfor (const [key, coeff] of p.terms) {\n\t\tcoefficients[monomialFromKey(key).get(variable) ?? 0] = coeff;\n\t}\n\treturn coefficients;\n}\n\n/**\n * Converts an expression tree into canonical polynomial form.\n *\n * @param node - The tree to convert. It should already be simplified, though\n * this does not require it.\n * @returns The polynomial, or `null` when `node` is not a polynomial over the\n * rationals: a non-constant denominator, a non-integer or symbolic exponent,\n * any function call, or a safety-limit breach.\n */\nexport function toPolynomial(node: SymbolicNode, allowDistribution = true): Polynomial | null {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\t\treturn constantPolynomial(node.value);\n\t\tcase \"var\":\n\t\t\treturn { terms: new Map([[node.name, RATIONAL_ONE]]), vars: [node.name] };\n\t\tcase \"neg\": {\n\t\t\tconst operand = toPolynomial(node.operand, allowDistribution);\n\t\t\treturn operand === null ? null : polyScale(operand, RATIONAL_MINUS_ONE);\n\t\t}\n\t\tcase \"add\": {\n\t\t\tconst left = toPolynomial(node.left, allowDistribution);\n\t\t\tconst right = left === null ? null : toPolynomial(node.right, allowDistribution);\n\t\t\treturn left === null || right === null ? null : polyAdd(left, right);\n\t\t}\n\t\tcase \"sub\": {\n\t\t\tconst left = toPolynomial(node.left, allowDistribution);\n\t\t\tconst right = left === null ? null : toPolynomial(node.right, allowDistribution);\n\t\t\treturn left === null || right === null ? null : polySub(left, right);\n\t\t}\n\t\tcase \"mul\": {\n\t\t\tconst left = toPolynomial(node.left, allowDistribution);\n\t\t\tconst right = left === null ? null : toPolynomial(node.right, allowDistribution);\n\t\t\tif (left === null || right === null) return null;\n\t\t\t// Multiplying into a multi-term sum is expansion, and the simplifier\n\t\t\t// is not allowed to do that (see `Simplify.ts`), so it converts with\n\t\t\t// distribution disabled and gets `null` here, leaving `(x+1)*(x+2)`\n\t\t\t// as the user wrote it.\n\t\t\t//\n\t\t\t// Refusing only when BOTH sides are sums is not enough. Distributing\n\t\t\t// a single factor over `(x-4)` copies that factor into both terms,\n\t\t\t// and distributing a bare constant over a three-term sum grows the\n\t\t\t// tree as well. So in this mode a product converts only when both\n\t\t\t// sides are single terms, which is exactly what collecting `2b + 3b`\n\t\t\t// into `5b` needs and nothing beyond it.\n\t\t\tif (!allowDistribution && (left.terms.size > 1 || right.terms.size > 1)) return null;\n\t\t\treturn polyMul(left, right);\n\t\t}\n\t\tcase \"div\": {\n\t\t\t// Only a genuinely constant, non-zero denominator is divisible here.\n\t\t\t// Anything else is a rational function, which this representation\n\t\t\t// cannot express, so it must come back null rather than be approximated.\n\t\t\tconst right = toPolynomial(node.right, allowDistribution);\n\t\t\tif (right === null || right.vars.length > 0) return null;\n\t\t\tconst divisor = right.terms.get(\"\") ?? RATIONAL_ZERO;\n\t\t\tif (isRationalZero(divisor)) return null;\n\t\t\tconst left = toPolynomial(node.left, allowDistribution);\n\t\t\treturn left === null ? null : polyScale(left, rationalDiv(RATIONAL_ONE, divisor));\n\t\t}\n\t\tcase \"pow\": {\n\t\t\tif (node.exponent.kind !== \"const\" || !isRationalInteger(node.exponent.value)) return null;\n\t\t\tconst exponent = Number(node.exponent.value.n);\n\t\t\tconst base = toPolynomial(node.base, allowDistribution);\n\t\t\tif (base === null) return null;\n\t\t\t// Raising a sum to a power is expansion too, for the same reason.\n\t\t\tif (!allowDistribution && base.terms.size > 1) return null;\n\t\t\treturn polyPow(base, exponent);\n\t\t}\n\t\tcase \"complex\":\n\t\t\t// Coefficients here are rational by construction, so a complex literal\n\t\t\t// puts the expression outside this representation. Returning null is what\n\t\t\t// keeps factor and solve working over the rationals by default.\n\t\t\treturn null;\n\t\tcase \"call\":\n\t\t\t// A function of an unknown is never a polynomial in it.\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Orders two monomials for display, highest first, by graded lexicographic\n * order: total degree, then the exponent of each variable in turn.\n *\n * This is what makes `(x+y)^2` read as `x^2+2x*y+y^2` rather than\n * `2x*y+x^2+y^2`. Sorting the key strings instead would order by character\n * code, where `*` (42) sorts before `^` (94), putting the cross term first.\n * Comparing exponent vectors is both conventional and independent of how a key\n * happens to be spelled.\n *\n * @param a - The first monomial key.\n * @param b - The second.\n * @param vars - The variable names, in sorted order, which fixes the tie-break.\n * @returns Negative when `a` sorts first, positive when `b` does, zero when\n * they are the same monomial.\n */\nexport function compareMonomials(a: MonomialKey, b: MonomialKey, vars: readonly string[]): number {\n\tconst degreeDifference = monomialDegree(b) - monomialDegree(a);\n\tif (degreeDifference !== 0) return degreeDifference;\n\n\tconst left = monomialFromKey(a);\n\tconst right = monomialFromKey(b);\n\tfor (const name of vars) {\n\t\tconst difference = (right.get(name) ?? 0) - (left.get(name) ?? 0);\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn 0;\n}\n\n/** Builds the node for one monomial, `x^2*y`, as a left-leaning product of powers. */\nfunction monomialToNode(key: MonomialKey): SymbolicNode {\n\tconst monomial = monomialFromKey(key);\n\tconst names = [...monomial.keys()].sort();\n\tlet result: SymbolicNode | null = null;\n\tfor (const name of names) {\n\t\tconst exponent = monomial.get(name)!;\n\t\tconst factor = exponent === 1 ? varNode(name) : powNode(varNode(name), constNode({ n: BigInt(exponent), d: 1n }));\n\t\tresult = result === null ? factor : { kind: \"mul\", left: result, right: factor };\n\t}\n\treturn result ?? constNode(RATIONAL_ONE);\n}\n\n/** Builds the node for one term, folding the coefficient in and wrapping a negative one in `neg` so the formatter renders `x-3` rather than `x+-3`. */\nfunction termToNode(key: MonomialKey, coeff: Rational): SymbolicNode {\n\tif (key === \"\") return constNode(coeff);\n\n\tconst magnitude = coeff.n < 0n ? rationalNeg(coeff) : coeff;\n\tconst monomial = monomialToNode(key);\n\tconst positive = isRationalOne(magnitude)\n\t\t? monomial\n\t\t: { kind: \"mul\" as const, left: constNode(magnitude), right: monomial };\n\treturn coeff.n < 0n ? { kind: \"neg\", operand: positive } : positive;\n}\n\n/**\n * Converts a polynomial back into an expression tree.\n *\n * Terms come out in descending total degree, then lexicographically by\n * monomial key, so `x^2+3x+2` reads the way it is conventionally written and\n * two equal polynomials always render identically.\n *\n * @param p - The polynomial to render.\n * @returns The tree. A zero polynomial becomes the constant `0`.\n */\nexport function fromPolynomial(p: Polynomial): SymbolicNode {\n\tconst keys = [...p.terms.keys()].sort((a, b) => compareMonomials(a, b, p.vars));\n\tif (keys.length === 0) return constNode(RATIONAL_ZERO);\n\n\t// Lead with a positive term when the polynomial has one, so `5 - y` comes\n\t// back as `5-y` rather than `-y+5`. Two reasons, and the second is the one\n\t// that matters. It reads the way a person writes it. And it keeps the tree\n\t// from growing: a leading negative needs a `neg` wrapper where the original\n\t// had a `sub`, which broke `Simplify.ts`'s promise never to grow a tree, by\n\t// one node for every additive level. The rule is deterministic and depends\n\t// only on the polynomial, so two equal polynomials still render identically.\n\tif (p.terms.get(keys[0])!.n < 0n) {\n\t\tconst firstPositive = keys.findIndex(key => p.terms.get(key)!.n > 0n);\n\t\tif (firstPositive > 0) keys.unshift(...keys.splice(firstPositive, 1));\n\t}\n\n\tlet result = termToNode(keys[0], p.terms.get(keys[0])!);\n\tfor (let i = 1; i < keys.length; i++) {\n\t\tconst coeff = p.terms.get(keys[i])!;\n\t\t// A negative term becomes a subtraction rather than an addition of a\n\t\t// negation. That is one node smaller, which matters: `Simplify.ts`\n\t\t// promises never to grow a tree, and routing `x - y` through here as\n\t\t// `x + (-y)` broke exactly that promise by a node every time.\n\t\tif (coeff.n < 0n) {\n\t\t\tresult = { kind: \"sub\", left: result, right: termToNode(keys[i], rationalNeg(coeff)) };\n\t\t} else {\n\t\t\tresult = { kind: \"add\", left: result, right: termToNode(keys[i], coeff) };\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * Multiplies out every product and power in an expression.\n *\n * Never called from `simplifySymbolic`, which is forbidden from growing a\n * tree. This is the explicitly-invoked counterpart.\n *\n * @param node - The expression to expand.\n * @returns The expanded expression, or `node` unchanged when it is not a\n * polynomial. `expand(sin(x))` is `sin(x)` rather than an error, since there is\n * nothing to expand but nothing wrong either.\n */\nexport function expandSymbolic(node: SymbolicNode): SymbolicNode {\n\tconst polynomial = toPolynomial(node);\n\treturn polynomial === null ? node : fromPolynomial(polynomial);\n}\n","/**\n * Polynomial division and greatest common divisors over the rationals.\n *\n * This is the piece the rest of the rational-function machinery stands on.\n * Cancelling `(x^2-1)/(x-1)` to `x+1`, splitting a fraction into partial\n * fractions, and integrating a rational function all reduce to \"divide these\n * two polynomials and find what they share\".\n *\n * Everything here is univariate. Multivariate GCD is a genuinely harder problem\n * (the usual approaches are modular or use Kronecker substitution), and the\n * univariate case covers what cancellation, partial fractions and rational\n * integration actually need. {@link polynomialGcd} declines rather than guessing\n * when handed more than one variable.\n *\n * Coefficients are exact, which matters more here than almost anywhere else in\n * the system: the Euclidean algorithm decides at every step whether a remainder\n * is zero, and in floating point that question has no reliable answer.\n */\n\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\tisRationalZero,\n\tisRationalOne,\n} from \"@solve-js/symbolic/Rational\";\nimport {\n\ttype Polynomial,\n\ttoPolynomial,\n\tfromPolynomial,\n\tpolyDegree,\n\tpolyUnivariateVar,\n\tpolyCoefficients,\n} from \"@solve-js/symbolic/Polynomial\";\nimport type { SymbolicNode } from \"@solve-js/symbolic/SymbolicNode\";\n\n/** A polynomial as dense coefficients, index `i` holding the coefficient of `x^i`. */\nexport type Coefficients = readonly Rational[];\n\n/** Drops trailing zero coefficients, so the degree is always the real one. */\nfunction trim(coefficients: Rational[]): Rational[] {\n\tlet last = coefficients.length - 1;\n\twhile (last >= 0 && isRationalZero(coefficients[last])) last--;\n\treturn coefficients.slice(0, last + 1);\n}\n\n/**\n * Whether a coefficient list is the zero polynomial.\n *\n * @param coefficients - Ascending coefficients.\n * @returns True when every coefficient is zero.\n */\nexport function isZeroPolynomial(coefficients: Coefficients): boolean {\n\treturn coefficients.every(isRationalZero);\n}\n\n/**\n * Divides one polynomial by another, exactly.\n *\n * @param dividend - Ascending coefficients of the numerator.\n * @param divisor - Ascending coefficients of the denominator, which must not be\n * the zero polynomial.\n * @returns The quotient and remainder, both ascending, satisfying\n * `dividend = divisor * quotient + remainder` with the remainder of lower\n * degree than the divisor.\n * @throws {Error} When the divisor is zero, which is a caller error rather than\n * a user-facing condition.\n */\nexport function polynomialDivide(\n\tdividend: Coefficients,\n\tdivisor: Coefficients,\n): { quotient: Rational[]; remainder: Rational[] } {\n\tconst numerator = trim([...dividend]);\n\tconst denominator = trim([...divisor]);\n\tif (denominator.length === 0) throw new Error(\"polynomialDivide: division by the zero polynomial\");\n\n\tconst divisorDegree = denominator.length - 1;\n\tconst leading = denominator[divisorDegree];\n\tconst remainder = [...numerator];\n\tconst quotient: Rational[] = new Array(Math.max(0, numerator.length - divisorDegree)).fill(RATIONAL_ZERO);\n\n\tfor (let degree = remainder.length - 1; degree >= divisorDegree; degree--) {\n\t\tif (isRationalZero(remainder[degree])) continue;\n\t\tconst factor = rationalDiv(remainder[degree], leading);\n\t\tconst offset = degree - divisorDegree;\n\t\tquotient[offset] = factor;\n\t\tfor (let i = 0; i <= divisorDegree; i++) {\n\t\t\tremainder[offset + i] = rationalSub(remainder[offset + i], rationalMul(factor, denominator[i]));\n\t\t}\n\t}\n\n\treturn { quotient: trim(quotient), remainder: trim(remainder) };\n}\n\n/** Scales a coefficient list so its leading coefficient is one, which makes the GCD canonical. */\nfunction monic(coefficients: Rational[]): Rational[] {\n\tconst trimmed = trim(coefficients);\n\tif (trimmed.length === 0) return trimmed;\n\tconst leading = trimmed[trimmed.length - 1];\n\tif (isRationalOne(leading)) return trimmed;\n\treturn trimmed.map(coefficient => rationalDiv(coefficient, leading));\n}\n\n/**\n * The greatest common divisor of two coefficient lists, by Euclid's algorithm.\n *\n * @param a - Ascending coefficients.\n * @param b - Ascending coefficients.\n * @returns The monic GCD. Two polynomials sharing no factor give `[1]`, and the\n * GCD of zero with anything is that other polynomial.\n */\nexport function coefficientGcd(a: Coefficients, b: Coefficients): Rational[] {\n\tlet left = trim([...a]);\n\tlet right = trim([...b]);\n\n\twhile (right.length > 0) {\n\t\tconst { remainder } = polynomialDivide(left, right);\n\t\tleft = right;\n\t\tright = remainder;\n\t}\n\treturn monic(left);\n}\n\n/**\n * The greatest common divisor of two polynomials.\n *\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns The monic GCD, or `null` when either polynomial involves more than\n * one variable, which this does not attempt.\n */\nexport function polynomialGcd(a: Polynomial, b: Polynomial): Polynomial | null {\n\tconst variable = sharedVariable(a, b);\n\tif (variable === undefined) return null;\n\n\t// A constant shares no polynomial factor with anything, so the GCD is one.\n\tif (variable === null) return toPolynomial({ kind: \"const\", value: RATIONAL_ONE });\n\n\tconst gcd = coefficientGcd(polyCoefficients(a, variable), polyCoefficients(b, variable));\n\treturn coefficientsToPolynomial(gcd, variable);\n}\n\n/**\n * The one variable two polynomials are written in.\n *\n * @returns The variable name, `null` when both are constants, or `undefined`\n * when they involve more than one variable between them and so are outside what\n * this module handles.\n */\nfunction sharedVariable(a: Polynomial, b: Polynomial): string | null | undefined {\n\tconst names = new Set([...a.vars, ...b.vars]);\n\tif (names.size === 0) return null;\n\tif (names.size > 1) return undefined;\n\treturn [...names][0];\n}\n\n/** Rebuilds a Polynomial from ascending coefficients in one variable. */\nfunction coefficientsToPolynomial(coefficients: Coefficients, variable: string): Polynomial {\n\tconst terms = new Map<string, Rational>();\n\tcoefficients.forEach((coefficient, power) => {\n\t\tif (isRationalZero(coefficient)) return;\n\t\tterms.set(power === 0 ? \"\" : power === 1 ? variable : `${variable}^${power}`, coefficient);\n\t});\n\treturn { terms, vars: terms.size > 0 && coefficients.length > 1 ? [variable] : [] };\n}\n\n/**\n * Reduces a fraction of two polynomials to lowest terms.\n *\n * @param numerator - The numerator.\n * @param denominator - The denominator.\n * @returns The reduced pair, or `null` when the two are outside what\n * {@link polynomialGcd} handles or share no factor worth cancelling.\n */\nexport function cancelRational(\n\tnumerator: Polynomial,\n\tdenominator: Polynomial,\n): { numerator: Polynomial; denominator: Polynomial } | null {\n\tconst gcd = polynomialGcd(numerator, denominator);\n\tif (gcd === null) return null;\n\t// A constant GCD means there is nothing to cancel, and reporting that as\n\t// \"no change\" rather than rebuilding an identical pair keeps the caller from\n\t// looping.\n\tif (polyDegree(gcd) === 0) return null;\n\n\tconst variable = polyUnivariateVar(gcd);\n\tif (variable === null) return null;\n\n\tconst gcdCoefficients = polyCoefficients(gcd, variable);\n\tconst reducedNumerator = polynomialDivide(polyCoefficients(numerator, variable), gcdCoefficients);\n\tconst reducedDenominator = polynomialDivide(polyCoefficients(denominator, variable), gcdCoefficients);\n\n\treturn {\n\t\tnumerator: coefficientsToPolynomial(reducedNumerator.quotient, variable),\n\t\tdenominator: coefficientsToPolynomial(reducedDenominator.quotient, variable),\n\t};\n}\n\n/**\n * Cancels the common factors of a quotient of two expressions.\n *\n * This is the explicit counterpart to the simplifier's own narrow cancellation:\n * it multiplies out both sides, divides by their greatest common divisor, and\n * rebuilds. `(x^2-1)/(x-1)` becomes `x+1`.\n *\n * @param node - The expression to reduce.\n * @returns The reduced expression, or `node` unchanged when it is not a\n * quotient of polynomials in one variable, or when there is nothing to cancel.\n */\nexport function cancelSymbolic(node: SymbolicNode): SymbolicNode {\n\tif (node.kind !== \"div\") return node;\n\n\tconst numerator = toPolynomial(node.left);\n\tconst denominator = toPolynomial(node.right);\n\tif (numerator === null || denominator === null) return node;\n\n\tconst reduced = cancelRational(numerator, denominator);\n\tif (reduced === null) return node;\n\n\t// The constant is only divided through as the last step of a cancellation\n\t// that already happened. Doing it unconditionally would rewrite `x/3` as\n\t// `1/3x`, which is the same number and a worse way to write it.\n\treturn divideOutConstant(reduced.numerator, reduced.denominator, node);\n}\n\n/**\n * Rebuilds a reduced fraction, folding a constant denominator into the\n * numerator.\n *\n * The polynomial GCD is monic, so it never carries a numeric factor away with\n * it: `(2x^2+4x)/(2x)` cancels to `(2x+4)/2` and stops. Dividing through by a\n * leftover constant denominator finishes the job and gives `x+2`.\n *\n * @param numerator - The reduced numerator.\n * @param denominator - The reduced denominator.\n * @param original - Returned unchanged when nothing improved, so the caller can\n * detect \"no progress\" by identity.\n * @returns The rebuilt expression.\n */\nfunction divideOutConstant(numerator: Polynomial, denominator: Polynomial, original: SymbolicNode): SymbolicNode {\n\tif (polyDegree(denominator) === 0) {\n\t\tconst constant = denominator.terms.get(\"\") ?? RATIONAL_ONE;\n\t\tif (isRationalZero(constant)) return original;\n\t\tconst scaled = new Map<string, Rational>();\n\t\tfor (const [key, coefficient] of numerator.terms) scaled.set(key, rationalDiv(coefficient, constant));\n\t\treturn fromPolynomial({ terms: scaled, vars: numerator.vars });\n\t}\n\treturn { kind: \"div\", left: fromPolynomial(numerator), right: fromPolynomial(denominator) };\n}\n\n/**\n * The square-free part of a polynomial, and the multiplicities it came from.\n *\n * A polynomial shares a factor with its own derivative exactly where that factor\n * is repeated, so `gcd(p, p')` isolates the repeats. This is what lets a\n * factorization report `(x-1)^2` rather than two identical factors, and it is\n * the first step of most serious factoring algorithms.\n *\n * @param coefficients - Ascending coefficients.\n * @returns The square-free part, ascending and monic.\n */\nexport function squareFreePart(coefficients: Coefficients): Rational[] {\n\tconst trimmed = trim([...coefficients]);\n\tif (trimmed.length <= 1) return monic(trimmed);\n\n\tconst derivative: Rational[] = [];\n\tfor (let power = 1; power < trimmed.length; power++) {\n\t\tderivative.push(rationalMul(trimmed[power], { n: BigInt(power), d: 1n }));\n\t}\n\n\tconst shared = coefficientGcd(trimmed, derivative);\n\tif (shared.length <= 1) return monic(trimmed);\n\treturn monic(polynomialDivide(trimmed, shared).quotient);\n}\n\n/**\n * Evaluates ascending coefficients at a rational point, by Horner's method.\n *\n * @param coefficients - Ascending coefficients.\n * @param x - The point.\n * @returns The value there.\n */\nexport function evaluateCoefficients(coefficients: Coefficients, x: Rational): Rational {\n\tlet total = RATIONAL_ZERO;\n\tfor (let i = coefficients.length - 1; i >= 0; i--) {\n\t\ttotal = rationalAdd(rationalMul(total, x), coefficients[i]);\n\t}\n\treturn total;\n}\n","/**\n * Exact integer roots, and the surd forms built on them.\n *\n * Two questions are asked constantly once a solver starts producing radicals:\n * \"is this a perfect power?\", which decides whether an answer is rational or\n * irrational, and \"how do I write this root so a person can read it?\". Both\n * answers live here so the quadratic, cubic and quartic paths give the same\n * shape rather than each inventing one.\n *\n * The reduction matters more than it looks. `sqrt(8)` and `2*sqrt(2)` are the\n * same number, but a solver that emits the first leaves the user to finish the\n * work, and two roots of the same equation can end up written in visibly\n * different styles depending on which one happened to cancel.\n */\n\nimport { type SymbolicNode, constNode } from \"@solve-js/symbolic/SymbolicNode\";\nimport { type Rational, rational } from \"@solve-js/symbolic/Rational\";\n\n/**\n * The exact integer square root, or `null` when the input is not a perfect\n * square.\n *\n * This is the predicate that keeps `sqrt(2)` unfolded. Newton's method on\n * integers, so it stays exact at any size.\n *\n * @param value - A non-negative integer. Negative input gives `null`, since it\n * has no integer square root.\n * @returns The root, or `null`.\n */\nexport function exactIntegerSqrt(value: bigint): bigint | null {\n\tif (value < 0n) return null;\n\tif (value < 2n) return value;\n\tlet previous = value;\n\tlet current = (value + 1n) / 2n;\n\twhile (current < previous) {\n\t\tprevious = current;\n\t\tcurrent = (previous + value / previous) / 2n;\n\t}\n\treturn previous * previous === value ? previous : null;\n}\n\n/**\n * The exact integer cube root, or `null` when the input is not a perfect cube.\n *\n * Unlike the square root this accepts negatives, because every real number has\n * a real cube root and `cbrt(-8)` is exactly `-2`.\n *\n * @param value - Any integer.\n * @returns The root, or `null`.\n */\nexport function exactIntegerCbrt(value: bigint): bigint | null {\n\tconst negative = value < 0n;\n\tconst magnitude = negative ? -value : value;\n\tif (magnitude < 2n) return negative ? -magnitude : magnitude;\n\n\tlet low = 1n;\n\tlet high = magnitude;\n\twhile (low <= high) {\n\t\tconst middle = (low + high) / 2n;\n\t\tconst cube = middle * middle * middle;\n\t\tif (cube === magnitude) return negative ? -middle : middle;\n\t\tif (cube < magnitude) low = middle + 1n;\n\t\telse high = middle - 1n;\n\t}\n\treturn null;\n}\n\n/**\n * The exact square root of a rational, or `null` when it is irrational.\n *\n * Both the numerator and the denominator have to be perfect squares, since the\n * root of a reduced fraction is taken componentwise.\n *\n * @param value - A non-negative rational.\n * @returns The exact root, or `null`.\n */\nexport function exactRationalSqrt(value: Rational): Rational | null {\n\tconst numerator = exactIntegerSqrt(value.n);\n\tconst denominator = exactIntegerSqrt(value.d);\n\treturn numerator === null || denominator === null ? null : { n: numerator, d: denominator };\n}\n\n/**\n * The square root of a non-negative rational, in lowest surd form.\n *\n * `sqrt(8)` comes back as `2*sqrt(2)`, and a perfect square comes back as a\n * plain constant. Written as a `sqrt` call rather than a power of one half so it\n * reads the way it is normally written, and so the simplifier's own exact\n * folding collapses it when the radicand turns out to be a perfect square after\n * all.\n *\n * `sqrt(n/d)` is computed as `sqrt(n*d)/d`, which keeps the extraction of square\n * factors entirely in integers.\n *\n * @param value - A non-negative rational.\n * @returns The root as an expression, or as a constant when it is rational.\n */\nexport function surdNode(value: Rational): SymbolicNode {\n\tconst radicand = value.n * value.d;\n\n\t// Pull out the largest square factor by trial division.\n\tlet extracted = 1n;\n\tlet remaining = radicand;\n\tfor (let factor = 2n; factor * factor <= remaining; factor++) {\n\t\tconst square = factor * factor;\n\t\twhile (remaining % square === 0n) {\n\t\t\tremaining /= square;\n\t\t\textracted *= factor;\n\t\t}\n\t}\n\n\t// Built through `rational` rather than as a literal: the extracted factor\n\t// comes from `n*d` and so can share a factor with `d`, and an unreduced pair\n\t// would surface as a coefficient written `6/108`.\n\tconst scale = rational(extracted, value.d);\n\tif (remaining === 1n) return constNode(scale);\n\n\tconst root: SymbolicNode = { kind: \"call\", name: \"sqrt\", args: [constNode({ n: remaining, d: 1n })] };\n\treturn scale.n === 1n && scale.d === 1n ? root : { kind: \"mul\", left: constNode(scale), right: root };\n}\n\n/**\n * The square root of a rational of either sign, as a real surd or an imaginary\n * one.\n *\n * @param value - Any rational.\n * @returns `sqrt(value)` for a non-negative input, and `sqrt(-value)*i` for a\n * negative one. The simplifier's own complex handling produces the same shape,\n * so the two agree.\n */\nexport function signedSurdNode(value: Rational): SymbolicNode {\n\tif (value.n >= 0n) return surdNode(value);\n\treturn { kind: \"call\", name: \"sqrt\", args: [constNode(value)] };\n}\n\n/**\n * The cube root of a rational, exact when the input is a perfect cube.\n *\n * @param value - Any rational.\n * @returns A constant when the root is rational, and a `cbrt` call otherwise.\n */\nexport function cbrtNode(value: Rational): SymbolicNode {\n\tconst numerator = exactIntegerCbrt(value.n);\n\tconst denominator = exactIntegerCbrt(value.d);\n\tif (numerator !== null && denominator !== null) return constNode({ n: numerator, d: denominator });\n\treturn { kind: \"call\", name: \"cbrt\", args: [constNode(value)] };\n}\n","/**\n * Bounded, bottom-up simplification of a {@link SymbolicNode}.\n *\n * ## The invariant that governs this module\n *\n * **`simplifySymbolic` never expands and never factors.** `expandSymbolic()`,\n * `factorSymbolic()` and `toPolynomial()` are separate, explicitly-invoked\n * entry points and are never reachable from here.\n *\n * Concretely, and as enforced by the property test in\n * `__tests__/symbolic/Simplify.spec.ts`:\n *\n * 1. **No distribution.** `(x+1)*(x+2)` and `2*(x+y+1)` come back exactly as\n * written. This is what \"never expands\" means, and it is enforced at the\n * source: {@link collectSum} converts to polynomial form with distribution\n * disabled, so a product only converts when both sides are single terms.\n * That is precisely what collecting `2b + 3b` into `5b` needs, and nothing\n * beyond it.\n * 2. **Idempotent.** Simplifying a result again changes nothing.\n * 3. **Bounded size.** Node count never grows by more than one, and the single\n * permitted node has one cause: an all-negative sum has no positive term to\n * lead with, so canonical order needs a `neg` where the input had a negative\n * constant. It cannot compound, because the result is idempotent.\n *\n * These rules are load-bearing. `vm/VMConversion.ts`'s `binaryOp()` calls this\n * once per symbolic arithmetic operation, so a rule that genuinely grew the\n * tree would compound across a long chain. And rule 1 keeps `pow` safe:\n * `simplify(x^2)` stays `x^2` rather than becoming `x*x`, so a polynomial keeps\n * the compact shape the rest of the system reads.\n *\n * ## What it does\n *\n * - Constant folding over exact rationals, including `pow` with an integer\n * exponent and a small set of functions with exact rational images.\n * - Additive and multiplicative identities (`x+0`, `x*1`, `x*0`, `x/1`, `--x`,\n * `x^1`, `x^0`).\n * - Flatten-and-collect of like terms across a top-level sum: a chain of\n * `+`/`-`/unary `-` over bare constants and bare variable names, so\n * `1+2+b+3+b` becomes `2b+6`. A `mul`/`div` node is not flattened through.\n * - One narrow exception to that last point: `div` cancels a single common\n * factor when the denominator is structurally identical to one whole factor\n * of a top-level product (`sx*tx/sx` becomes `tx`). This exists for\n * triangular-matrix symbolic inverses and is not a general polynomial\n * division capability.\n *\n * Function folding is deliberately conservative. `sqrt(4)` folds to `2`\n * because four is a perfect square; **`sqrt(2)` does not fold**, because it has\n * no rational value and inventing `1.4142135624` here is how a system that\n * advertises exact arithmetic starts lying.\n *\n * See `vm/VMConversion.ts`'s `binaryOp()` for where this plugs into the\n * ordinary arithmetic opcodes, and `SymbolicFormat.ts` for display.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tnodesEqual,\n\tnodeCount,\n\tSYMBOLIC_MAX_NODES,\n\tcomplexNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\tRATIONAL_MINUS_ONE,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\trationalPow,\n\tisRationalZero,\n\tisRationalOne,\n\tisRationalMinusOne,\n\tisRationalInteger,\n} from \"@solve-js/symbolic/Rational\";\nimport { toPolynomial, fromPolynomial } from \"@solve-js/symbolic/Polynomial\";\nimport { cancelSymbolic } from \"@solve-js/symbolic/Gcd\";\nimport { exactIntegerSqrt, exactIntegerCbrt } from \"@solve-js/symbolic/Radicals\";\nimport {\n\ttype Complex,\n\tcomplex,\n\tcomplexAdd,\n\tcomplexSub,\n\tcomplexMul,\n\tcomplexDiv,\n\tcomplexNeg,\n\tcomplexPow,\n\tcomplexConjugate,\n\tcomplexNormSquared,\n\texactComplexSqrt,\n\tisComplexZero,\n\tCOMPLEX_I,\n} from \"@solve-js/symbolic/Complex\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n// ── Flatten-and-collect (top-level sums only) ──────────────────────────────\n\ninterface FlatTerm {\n\tcoeff: Rational;\n\t/** `null` means this term is the accumulated constant. */\n\tname: string | null;\n}\n\n/**\n * Recursively unrolls an `add`/`sub`/`neg` chain into a flat list of signed\n * terms. Returns `false` (callers discard `out` on a `false` return) the moment\n * it meets anything that is not a constant, a bare variable, or another\n * additive node, since collecting terms through a product is out of scope here.\n */\nfunction flattenSum(node: SymbolicNode, negated: boolean, out: FlatTerm[], depth = 0): boolean {\n\t// A second walk of its own, so the depth guard on `simplifyNode` does not\n\t// cover it: this one is entered at whatever depth the simplifier reached\n\t// and then descends the whole remaining chain, which for `a+(b+(c+...))`\n\t// is as deep as the tree. `false` is the answer this function already gives\n\t// for anything it cannot flatten, and the caller already knows what to do\n\t// with it, so the guard needs no new outcome.\n\tif (depth >= MAX_SIMPLIFY_DEPTH) return false;\n\tswitch (node.kind) {\n\t\tcase \"add\":\n\t\t\treturn flattenSum(node.left, negated, out, depth + 1) && flattenSum(node.right, negated, out, depth + 1);\n\t\tcase \"sub\":\n\t\t\treturn flattenSum(node.left, negated, out, depth + 1) && flattenSum(node.right, !negated, out, depth + 1);\n\t\tcase \"neg\":\n\t\t\treturn flattenSum(node.operand, !negated, out, depth + 1);\n\t\tcase \"const\":\n\t\t\tout.push({ coeff: negated ? rationalNeg(node.value) : node.value, name: null });\n\t\t\treturn true;\n\t\tcase \"var\":\n\t\t\tout.push({ coeff: negated ? RATIONAL_MINUS_ONE : RATIONAL_ONE, name: node.name });\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/**\n * Collects like terms in a fully-flattenable `add`/`sub` chain, so\n * `1+2+b+3+b` becomes `2b+6`: variable terms first in first-seen order, then\n * the combined constant last, with a zero-coefficient term dropped entirely to\n * match the `x+0 -> x` identity. Returns `node` unchanged when it is not fully\n * flattenable, which is what keeps a rational-function shape such as\n * `vx/sx-tx` intact.\n */\nfunction collectTerms(node: SymbolicNode): SymbolicNode {\n\tconst flat: FlatTerm[] = [];\n\tif (!flattenSum(node, false, flat)) return node;\n\n\tconst order: string[] = [];\n\tconst coeffByName = new Map<string, Rational>();\n\tlet constant = RATIONAL_ZERO;\n\tfor (const term of flat) {\n\t\tif (term.name === null) {\n\t\t\tconstant = rationalAdd(constant, term.coeff);\n\t\t\tcontinue;\n\t\t}\n\t\tconst existing = coeffByName.get(term.name);\n\t\tif (existing === undefined) {\n\t\t\torder.push(term.name);\n\t\t\tcoeffByName.set(term.name, term.coeff);\n\t\t} else {\n\t\t\tcoeffByName.set(term.name, rationalAdd(existing, term.coeff));\n\t\t}\n\t}\n\n\tconst termNodes: SymbolicNode[] = [];\n\tfor (const name of order) {\n\t\tconst coeff = coeffByName.get(name)!;\n\t\tif (isRationalZero(coeff)) continue;\n\t\tif (isRationalOne(coeff)) termNodes.push(varNode(name));\n\t\telse if (isRationalMinusOne(coeff)) termNodes.push({ kind: \"neg\", operand: varNode(name) });\n\t\telse termNodes.push({ kind: \"mul\", left: constNode(coeff), right: varNode(name) });\n\t}\n\n\tif (termNodes.length === 0) return constNode(constant);\n\n\tlet result = termNodes[0];\n\tfor (let i = 1; i < termNodes.length; i++) {\n\t\tresult = { kind: \"add\", left: result, right: termNodes[i] };\n\t}\n\tif (!isRationalZero(constant)) {\n\t\tresult = { kind: \"add\", left: result, right: constNode(constant) };\n\t}\n\treturn result;\n}\n\n/**\n * Collects a sum, preferring the canonical polynomial form and falling back to\n * the tree-level {@link collectTerms} when the expression is not a polynomial.\n *\n * The two-step shape is what lets like terms combine through a product\n * (`2b + 3b` becomes `5b`, which the tree walk alone cannot do, since it stops\n * at the first `mul`) without disturbing anything the polynomial form cannot\n * represent. `vx/sx - tx` is a rational function, so `toPolynomial` reports\n * `null` and the original handling runs untouched. That fallback is what keeps\n * symbolic matrix inverses rendering as they always have.\n *\n * Only `add` and `sub` route through here. The `mul` and `div` cases keep their\n * own rules verbatim, including the reciprocal canonicalization and the\n * single-common-factor cancellation, because the polynomial form can express\n * neither.\n *\n * This does not violate the module's no-growth invariant: a polynomial is a\n * collected sum, so the round trip only ever merges terms.\n */\nfunction collectSum(node: SymbolicNode): SymbolicNode {\n\t// Distribution disabled: collecting like terms must never multiply out a\n\t// product of sums, which would be expansion by another name.\n\tconst polynomial = toPolynomial(node, false);\n\tif (polynomial !== null) return fromPolynomial(polynomial);\n\treturn collectTerms(node);\n}\n\n// ── Exact function folding ──────────────────────────────────────────────────\n\n/** Greatest integer not exceeding `r`. Bigint division truncates toward zero, so a negative non-integer needs one more step down. */\nfunction rationalFloor(r: Rational): bigint {\n\tconst truncated = r.n / r.d;\n\treturn r.n < 0n && truncated * r.d !== r.n ? truncated - 1n : truncated;\n}\n\n/** Largest factorial this will fold. Beyond this the exact result is enormous and the caller almost certainly wants the numeric builtin instead. */\nconst MAX_FOLDED_FACTORIAL = 500n;\n\n/**\n * Folds a function application whose arguments are all constant, but **only**\n * when the exact result is rational.\n *\n * Returning `null` leaves the call symbolic, which is always the safe answer.\n * Adding a function here that has an irrational result for some rational input\n * would make the simplifier produce a confidently wrong value.\n */\nfunction foldCall(name: string, args: readonly Rational[]): Rational | null {\n\tconst first = args[0];\n\tswitch (name) {\n\t\tcase \"abs\":\n\t\t\treturn args.length === 1 ? (first.n < 0n ? rationalNeg(first) : first) : null;\n\t\tcase \"sign\":\n\t\t\tif (args.length !== 1) return null;\n\t\t\treturn first.n === 0n ? RATIONAL_ZERO : { n: first.n < 0n ? -1n : 1n, d: 1n };\n\t\tcase \"floor\":\n\t\t\treturn args.length === 1 ? { n: rationalFloor(first), d: 1n } : null;\n\t\tcase \"ceil\":\n\t\t\treturn args.length === 1 ? { n: -rationalFloor(rationalNeg(first)), d: 1n } : null;\n\t\tcase \"trunc\":\n\t\t\treturn args.length === 1 ? { n: first.n / first.d, d: 1n } : null;\n\t\tcase \"round\":\n\t\t\t// Matches Math.round: halfway cases go toward positive infinity.\n\t\t\treturn args.length === 1 ? { n: rationalFloor(rationalAdd(first, { n: 1n, d: 2n })), d: 1n } : null;\n\t\tcase \"sqrt\": {\n\t\t\tif (args.length !== 1 || first.n < 0n) return null;\n\t\t\tconst rootN = exactIntegerSqrt(first.n);\n\t\t\tconst rootD = exactIntegerSqrt(first.d);\n\t\t\treturn rootN === null || rootD === null ? null : { n: rootN, d: rootD };\n\t\t}\n\t\tcase \"cbrt\": {\n\t\t\t// Unlike the square root this accepts a negative: every real number has\n\t\t\t// a real cube root, so `cbrt(-8)` is exactly `-2`. Cardano's formula\n\t\t\t// leans on this, which is how a cubic whose closed form happens to be\n\t\t\t// rational still comes back as a plain number.\n\t\t\tif (args.length !== 1) return null;\n\t\t\tconst rootN = exactIntegerCbrt(first.n);\n\t\t\tconst rootD = exactIntegerCbrt(first.d);\n\t\t\treturn rootN === null || rootD === null ? null : { n: rootN, d: rootD };\n\t\t}\n\t\t// Exact values at the points where these functions are rational. Every\n\t\t// entry is exact, not rounded, which is what lets a Taylor series about\n\t\t// the origin come out with exact coefficients. Deliberately narrow:\n\t\t// `sin(1)` and `log(2)` are irrational and must stay symbolic.\n\t\tcase \"sin\":\n\t\tcase \"tan\":\n\t\tcase \"asin\":\n\t\tcase \"atan\":\n\t\tcase \"sinh\":\n\t\tcase \"tanh\":\n\t\t\treturn args.length === 1 && isRationalZero(first) ? RATIONAL_ZERO : null;\n\t\tcase \"cos\":\n\t\tcase \"exp\":\n\t\tcase \"cosh\":\n\t\t\treturn args.length === 1 && isRationalZero(first) ? RATIONAL_ONE : null;\n\t\tcase \"log\":\n\t\t\treturn args.length === 1 && isRationalOne(first) ? RATIONAL_ZERO : null;\n\t\tcase \"acos\":\n\t\t\t// acos(1) = 0 is the only rational value; acos(0) is pi/2, which is not.\n\t\t\treturn args.length === 1 && isRationalOne(first) ? RATIONAL_ZERO : null;\n\t\tcase \"fact\": {\n\t\t\tif (args.length !== 1 || !isRationalInteger(first) || first.n < 0n || first.n > MAX_FOLDED_FACTORIAL) return null;\n\t\t\tlet total = 1n;\n\t\t\tfor (let i = 2n; i <= first.n; i++) total *= i;\n\t\t\treturn { n: total, d: 1n };\n\t\t}\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n// ── simplify ────────────────────────────────────────────────────────────────\n\n/**\n * Simplifies a symbolic expression bottom-up under this module's stated\n * invariant.\n *\n * Always terminates and is idempotent in structural terms, so it is safe to\n * call repeatedly (once per `binaryOp()`, for instance) without accumulating\n * tree depth across a long chain of operations.\n *\n * @param node - The tree to simplify.\n * @returns The simplified tree, which is never larger than the input.\n * @throws {EngineError} `SYMBOLIC_NODE_LIMIT_EXCEEDED` when the input exceeds\n * {@link SYMBOLIC_MAX_NODES}.\n */\nexport function simplifySymbolic(node: SymbolicNode): SymbolicNode {\n\t// The limit is passed through so the walk stops as soon as it is exceeded.\n\t// Without it a tree far past the ceiling would be counted in full before\n\t// being rejected, which is the opposite of what a guard is for.\n\tif (nodeCount(node, SYMBOLIC_MAX_NODES) > SYMBOLIC_MAX_NODES) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_NODE_LIMIT_EXCEEDED\",\n\t\t\t`This symbolic expression is too large to simplify (over ${SYMBOLIC_MAX_NODES} terms).`,\n\t\t\t{ limit: SYMBOLIC_MAX_NODES },\n\t\t);\n\t}\n\t// Restored rather than zeroed, because this function is genuinely reentrant\n\t// (`vm/MatrixOps.ts` simplifies each cell of a symbolic product from inside\n\t// a walk that is already in progress), so a nested call has to add to the\n\t// enclosing depth rather than forget it. The `finally` is what makes a\n\t// throw from deep inside, a rational overflow for instance, unable to leave\n\t// the counter high and the simplifier quietly switched off for the rest of\n\t// the process, which is the one failure mode a guard must not have.\n\tconst depthOnEntry = walkDepth;\n\ttry {\n\t\treturn simplifyNode(node);\n\t} finally {\n\t\twalkDepth = depthOnEntry;\n\t}\n}\n\n/**\n * How deep the simplifier will walk before leaving a subtree alone.\n *\n * `SYMBOLIC_MAX_NODES` bounds a tree's SIZE, and size and depth come apart\n * completely for a chain, where a thousand nodes is a thousand levels. The\n * recursive walk below runs out of native stack at around four thousand levels,\n * which is well inside the ten thousand nodes the size guard admits, so there\n * was a whole band of trees the engine called legal and then died on with a raw\n * \"Maximum call stack size exceeded\" that no host can tell from a bug in its\n * own code. `SymbolicNode.ts`'s `nodeCount()` was made iterative for exactly\n * this reason; that made the size guard reachable without making the functions\n * it guards able to walk what it admits.\n *\n * A quarter of the measured native limit, because these functions are called\n * from inside the VM's dispatch loop, which has already spent stack of its own.\n *\n * Past it the subtree is returned as it came in. Simplification is an\n * improvement to a tree, never a requirement of one, so an unsimplified branch\n * is still exactly the expression the user wrote; the alternative, an error, is\n * worse for a document whose deep line is otherwise perfectly answerable.\n */\nconst MAX_SIMPLIFY_DEPTH = 900;\n\n/** How deep the walk currently is. Module state; see {@link simplifySymbolic} for how it is kept honest. */\nlet walkDepth = 0;\n\n/**\n * Depth-bounded wrapper around the real worker.\n *\n * Every recursive call in {@link simplifyNodeAt} goes through here, so one\n * increment per level is all the bookkeeping the guard needs. The decrement is\n * deliberately not in a `finally`: a throw skips it, and the `finally` in\n * {@link simplifySymbolic} restores the whole counter at the point the throw is\n * caught, which is cheaper per node and exactly as correct.\n */\nfunction simplifyNode(node: SymbolicNode): SymbolicNode {\n\tif (walkDepth >= MAX_SIMPLIFY_DEPTH) return node;\n\twalkDepth++;\n\tconst simplified = simplifyNodeAt(node);\n\twalkDepth--;\n\treturn simplified;\n}\n\n/**\n * Reads a numeric atom as a complex value, so the arithmetic cases can treat a\n * real constant and a complex one uniformly.\n *\n * Returns `null` for anything that is not a literal number, which is what keeps\n * the real fast paths below from being disturbed.\n */\nfunction asComplex(node: SymbolicNode): Complex | null {\n\tif (node.kind === \"complex\") return node.value;\n\tif (node.kind === \"const\") return complex(node.value);\n\treturn null;\n}\n\n/**\n * Folds an arithmetic node whose operands are both literal numbers and at least\n * one of which is complex.\n *\n * Returns `null` when the node is not that shape, leaving every real-only path\n * exactly as it was: a pair of rational constants never reaches this, so\n * ordinary arithmetic pays nothing for complex support.\n */\nfunction foldComplexBinary(kind: \"add\" | \"sub\" | \"mul\" | \"div\", left: SymbolicNode, right: SymbolicNode): SymbolicNode | null {\n\tif (left.kind !== \"complex\" && right.kind !== \"complex\") return null;\n\tconst a = asComplex(left);\n\tconst b = asComplex(right);\n\tif (a === null || b === null) return null;\n\tswitch (kind) {\n\t\tcase \"add\": return complexNode(complexAdd(a, b));\n\t\tcase \"sub\": return complexNode(complexSub(a, b));\n\t\tcase \"mul\": return complexNode(complexMul(a, b));\n\t\tcase \"div\": return isComplexZero(b) ? null : complexNode(complexDiv(a, b));\n\t}\n}\n\n/**\n * Folds a function whose exact answer is complex.\n *\n * The only entries are the ones whose real-domain versions have a genuine hole:\n * `sqrt` and `abs` of a negative, and the accessors that take a complex value\n * apart. `sqrt(-4)` is exactly `2i`, which the real-only table above had to\n * decline. Anything whose complex value is irrational, `sqrt(i)` for instance,\n * still comes back `null` and stays symbolic.\n *\n * @returns The folded node, or `null` to leave the call alone.\n */\nfunction foldComplexCall(name: string, args: readonly SymbolicNode[]): SymbolicNode | null {\n\tif (args.length !== 1) return null;\n\tconst value = asComplex(args[0]);\n\tif (value === null) return null;\n\n\tswitch (name) {\n\t\tcase \"sqrt\": {\n\t\t\tconst root = exactComplexSqrt(value);\n\t\t\tif (root !== null) return complexNode(root);\n\t\t\t// A negative real whose magnitude has no rational root is still worth\n\t\t\t// rewriting: `sqrt(-2)` is `sqrt(2)*i`, which pulls the imaginary unit\n\t\t\t// out where the rest of the system can work with it, instead of\n\t\t\t// leaving a square root of a negative number sitting in the tree.\n\t\t\tif (isRationalZero(value.im) && value.re.n < 0n) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"mul\",\n\t\t\t\t\tleft: { kind: \"call\", name: \"sqrt\", args: [constNode(rationalNeg(value.re))] },\n\t\t\t\t\tright: complexNode(COMPLEX_I),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\tcase \"conj\":\n\t\t\treturn complexNode(complexConjugate(value));\n\t\tcase \"re\":\n\t\t\treturn constNode(value.re);\n\t\tcase \"im\":\n\t\t\treturn constNode(value.im);\n\t\tcase \"abs\": {\n\t\t\t// |z| is the square root of a rational, so it is only exact when that\n\t\t\t// root is. The real-only table already handles a real argument.\n\t\t\tif (isRationalZero(value.im)) return null;\n\t\t\tconst modulus = exactComplexSqrt(complex(complexNormSquared(value)));\n\t\t\treturn modulus === null || !isRationalZero(modulus.im) ? null : constNode(modulus.re);\n\t\t}\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/** Recursive worker for {@link simplifySymbolic}, past the one-time size guard and under the depth guard in {@link simplifyNode}. */\nfunction simplifyNodeAt(node: SymbolicNode): SymbolicNode {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\tcase \"complex\":\n\t\tcase \"var\":\n\t\t\treturn node;\n\n\t\tcase \"neg\": {\n\t\t\tconst operand = simplifyNode(node.operand);\n\t\t\tif (operand.kind === \"const\") return constNode(rationalNeg(operand.value));\n\t\t\tif (operand.kind === \"complex\") return complexNode(complexNeg(operand.value));\n\t\t\tif (operand.kind === \"neg\") return operand.operand;\n\t\t\treturn { kind: \"neg\", operand };\n\t\t}\n\n\t\tcase \"add\": {\n\t\t\tconst left = simplifyNode(node.left);\n\t\t\tconst right = simplifyNode(node.right);\n\t\t\tif (left.kind === \"const\" && right.kind === \"const\") return constNode(rationalAdd(left.value, right.value));\n\t\t\tconst foldedAdd = foldComplexBinary(\"add\", left, right);\n\t\t\tif (foldedAdd !== null) return foldedAdd;\n\t\t\tif (left.kind === \"const\" && isRationalZero(left.value)) return right;\n\t\t\tif (right.kind === \"const\" && isRationalZero(right.value)) return left;\n\t\t\treturn collectSum({ kind: \"add\", left, right });\n\t\t}\n\n\t\tcase \"sub\": {\n\t\t\tconst left = simplifyNode(node.left);\n\t\t\tconst right = simplifyNode(node.right);\n\t\t\tif (left.kind === \"const\" && right.kind === \"const\") return constNode(rationalSub(left.value, right.value));\n\t\t\tconst foldedSub = foldComplexBinary(\"sub\", left, right);\n\t\t\tif (foldedSub !== null) return foldedSub;\n\t\t\tif (right.kind === \"const\" && isRationalZero(right.value)) return left;\n\t\t\tif (left.kind === \"const\" && isRationalZero(left.value)) return simplifyNode({ kind: \"neg\", operand: right });\n\t\t\treturn collectSum({ kind: \"sub\", left, right });\n\t\t}\n\n\t\tcase \"mul\": {\n\t\t\tconst left = simplifyNode(node.left);\n\t\t\tconst right = simplifyNode(node.right);\n\t\t\tif (left.kind === \"const\" && right.kind === \"const\") return constNode(rationalMul(left.value, right.value));\n\t\t\tconst foldedMul = foldComplexBinary(\"mul\", left, right);\n\t\t\tif (foldedMul !== null) return foldedMul;\n\t\t\tif ((left.kind === \"const\" && isRationalZero(left.value)) || (right.kind === \"const\" && isRationalZero(right.value))) {\n\t\t\t\treturn constNode(RATIONAL_ZERO);\n\t\t\t}\n\t\t\tif (left.kind === \"const\" && isRationalOne(left.value)) return right;\n\t\t\tif (right.kind === \"const\" && isRationalOne(right.value)) return left;\n\t\t\tif (left.kind === \"const\" && isRationalMinusOne(left.value)) return simplifyNode({ kind: \"neg\", operand: right });\n\t\t\tif (right.kind === \"const\" && isRationalMinusOne(right.value)) return simplifyNode({ kind: \"neg\", operand: left });\n\t\t\t// Gather adjacent constant factors: c1*(c2*rest) -> (c1*c2)*rest, and\n\t\t\t// the mirrored shape. Differentiation builds exactly these, so without\n\t\t\t// this the second derivative of x^3 stays as 3*(2*x) rather than 6x.\n\t\t\t// This removes a node rather than adding one, so the module's\n\t\t\t// no-growth invariant still holds.\n\t\t\tif (left.kind === \"const\" && right.kind === \"mul\" && right.left.kind === \"const\") {\n\t\t\t\treturn simplifyNode({ kind: \"mul\", left: constNode(rationalMul(left.value, right.left.value)), right: right.right });\n\t\t\t}\n\t\t\tif (right.kind === \"const\" && left.kind === \"mul\" && left.left.kind === \"const\") {\n\t\t\t\treturn simplifyNode({ kind: \"mul\", left: constNode(rationalMul(right.value, left.left.value)), right: left.right });\n\t\t\t}\n\t\t\t// Canonicalize a reciprocal factor into division: (1/a)*b -> b/a,\n\t\t\t// a*(1/b) -> a/b. A narrow display-canonicalization rule, needed\n\t\t\t// because matrix multiply builds cells as mul(entry, entry) in\n\t\t\t// encounter order, so a symbolic inverse's `1/sx` entry times a `vx`\n\t\t\t// cell produces `(1/sx)*vx` rather than the spec's own `vx/sx`,\n\t\t\t// mathematically identical but a different tree shape. Not a general\n\t\t\t// reciprocal-detection rule: it fires only when a factor is literally\n\t\t\t// `1/x`, never an arbitrary fraction.\n\t\t\tif (left.kind === \"div\" && left.left.kind === \"const\" && isRationalOne(left.left.value)) {\n\t\t\t\treturn simplifyNode({ kind: \"div\", left: right, right: left.right });\n\t\t\t}\n\t\t\tif (right.kind === \"div\" && right.left.kind === \"const\" && isRationalOne(right.left.value)) {\n\t\t\t\treturn simplifyNode({ kind: \"div\", left, right: right.right });\n\t\t\t}\n\t\t\treturn { kind: \"mul\", left, right };\n\t\t}\n\n\t\tcase \"div\": {\n\t\t\tconst left = simplifyNode(node.left);\n\t\t\tconst right = simplifyNode(node.right);\n\t\t\t// A constant denominator of zero is left unfolded rather than folded\n\t\t\t// or thrown. The previous double-based simplifier folded `1/0` to\n\t\t\t// `Infinity`; a Rational has no such value, and throwing from inside\n\t\t\t// a bottom-up walk would fail the whole line over a subexpression the\n\t\t\t// user may never see. Leaving `1/0` intact reports the situation\n\t\t\t// honestly and lets the caller decide.\n\t\t\tif (left.kind === \"const\" && right.kind === \"const\" && !isRationalZero(right.value)) {\n\t\t\t\treturn constNode(rationalDiv(left.value, right.value));\n\t\t\t}\n\t\t\tconst foldedDiv = foldComplexBinary(\"div\", left, right);\n\t\t\tif (foldedDiv !== null) return foldedDiv;\n\t\t\tif (right.kind === \"const\" && isRationalOne(right.value)) return left;\n\t\t\tif (left.kind === \"const\" && isRationalZero(left.value)) return constNode(RATIONAL_ZERO);\n\t\t\t// Cancel a single common factor: (a*b)/a -> b, (a*b)/b -> a. A narrow,\n\t\t\t// disclosed exception to \"never collects through mul/div\", needed for\n\t\t\t// the symbolic triangular-matrix-inverse case (`sx*tx/sx -> tx`). It\n\t\t\t// fires only when the denominator is structurally identical to one\n\t\t\t// whole factor of a top-level product, never a partial or nested match.\n\t\t\tif (left.kind === \"mul\") {\n\t\t\t\tif (nodesEqual(left.left, right)) return left.right;\n\t\t\t\tif (nodesEqual(left.right, right)) return left.left;\n\t\t\t}\n\t\t\t// Cancel a genuine common polynomial factor, so `(x^2-1)/(x-1)` reduces\n\t\t\t// to `x+1`. This is contraction rather than expansion: the result is\n\t\t\t// always smaller, so the no-growth invariant holds. A rational function\n\t\t\t// in more than one variable, `vx/sx`, has no univariate gcd and comes\n\t\t\t// back untouched.\n\t\t\tconst cancelled = cancelSymbolic({ kind: \"div\", left, right });\n\t\t\tif (cancelled.kind !== \"div\" || cancelled.left !== left || cancelled.right !== right) {\n\t\t\t\treturn simplifyNode(cancelled);\n\t\t\t}\n\t\t\t// The same cancellation through a leading minus: -(a*b)/a -> -b.\n\t\t\t// Without this the rule is asymmetric, and a quadratic's two surd\n\t\t\t// roots render differently from each other: `sqrt(2)` for the one\n\t\t\t// that cancelled and `-2*sqrt(2)/2` for the one that did not.\n\t\t\tif (left.kind === \"neg\" && left.operand.kind === \"mul\") {\n\t\t\t\tconst product = left.operand;\n\t\t\t\tif (nodesEqual(product.left, right)) return simplifyNode({ kind: \"neg\", operand: product.right });\n\t\t\t\tif (nodesEqual(product.right, right)) return simplifyNode({ kind: \"neg\", operand: product.left });\n\t\t\t}\n\t\t\treturn { kind: \"div\", left, right };\n\t\t}\n\n\t\tcase \"pow\": {\n\t\t\tconst base = simplifyNode(node.base);\n\t\t\tconst exponent = simplifyNode(node.exponent);\n\n\t\t\tif (exponent.kind === \"const\") {\n\t\t\t\tif (isRationalZero(exponent.value)) return constNode(RATIONAL_ONE);\n\t\t\t\tif (isRationalOne(exponent.value)) return base;\n\t\t\t\tif (base.kind === \"const\" && isRationalInteger(exponent.value)) {\n\t\t\t\t\treturn constNode(rationalPow(base.value, exponent.value.n));\n\t\t\t\t}\n\t\t\t\tif (base.kind === \"complex\" && isRationalInteger(exponent.value)) {\n\t\t\t\t\treturn complexNode(complexPow(base.value, exponent.value.n));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (base.kind === \"const\" && isRationalOne(base.value)) return constNode(RATIONAL_ONE);\n\t\t\t// 0^x is zero only for a positive exponent. 0^0 is one (handled\n\t\t\t// above) and 0^-1 is a division by zero, so neither may reach here.\n\t\t\tif (base.kind === \"const\" && isRationalZero(base.value) && exponent.kind === \"const\" && exponent.value.n > 0n) {\n\t\t\t\treturn constNode(RATIONAL_ZERO);\n\t\t\t}\n\t\t\t// (a^b)^c -> a^(b*c) is unsound in general (it loses a branch for a\n\t\t\t// negative base with fractional exponents), so it is allowed only\n\t\t\t// when both exponents are integers, where it always holds.\n\t\t\tif (\n\t\t\t\tbase.kind === \"pow\" &&\n\t\t\t\tbase.exponent.kind === \"const\" &&\n\t\t\t\texponent.kind === \"const\" &&\n\t\t\t\tisRationalInteger(base.exponent.value) &&\n\t\t\t\tisRationalInteger(exponent.value)\n\t\t\t) {\n\t\t\t\treturn simplifyNode({\n\t\t\t\t\tkind: \"pow\",\n\t\t\t\t\tbase: base.base,\n\t\t\t\t\texponent: constNode(rationalMul(base.exponent.value, exponent.value)),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { kind: \"pow\", base, exponent };\n\t\t}\n\n\t\tcase \"call\": {\n\t\t\tconst args = node.args.map(simplifyNode);\n\t\t\tif (args.every(arg => arg.kind === \"const\")) {\n\t\t\t\tconst folded = foldCall(node.name, args.map(arg => (arg as { kind: \"const\"; value: Rational }).value));\n\t\t\t\tif (folded !== null) return constNode(folded);\n\t\t\t}\n\t\t\tconst complexFolded = foldComplexCall(node.name, args);\n\t\t\tif (complexFolded !== null) return complexFolded;\n\t\t\treturn { kind: \"call\", name: node.name, args };\n\t\t}\n\t}\n}\n","/**\n * Rendering a {@link SymbolicNode} as display text.\n *\n * The conventions here match how the expressions are written rather than how\n * the tree is shaped: a coefficient juxtaposes its variable with no operator\n * (`2b`, not `2*b`), sums join with the correct sign (`2b+6` and `x-3`, never\n * `2b+-6`), and parentheses appear only where precedence genuinely needs them.\n *\n * This module does not simplify. Call `simplifySymbolic()` first for a\n * canonical, minimal rendering.\n */\n\nimport type { SymbolicNode } from \"@solve-js/symbolic/SymbolicNode\";\nimport { type Rational, formatRational } from \"@solve-js/symbolic/Rational\";\nimport { formatComplex } from \"@solve-js/symbolic/Complex\";\n\n/** Extracts `{coeff, name}` from a `const*var` or `var*const` shape, or `null` when `node` is not one. */\nfunction tryExtractCoeffVar(node: SymbolicNode & { kind: \"mul\" }): { coeff: Rational; name: string } | null {\n\tif (node.left.kind === \"const\" && node.right.kind === \"var\") return { coeff: node.left.value, name: node.right.name };\n\tif (node.right.kind === \"const\" && node.left.kind === \"var\") return { coeff: node.right.value, name: node.left.name };\n\treturn null;\n}\n\n/** Extracts `{coeff, power}` from a `const*pow` or `pow*const` shape, so `2x^2` renders without an asterisk. */\nfunction tryExtractCoeffPow(node: SymbolicNode & { kind: \"mul\" }): { coeff: Rational; power: SymbolicNode } | null {\n\tif (node.left.kind === \"const\" && node.right.kind === \"pow\") return { coeff: node.left.value, power: node.right };\n\tif (node.right.kind === \"const\" && node.left.kind === \"pow\") return { coeff: node.right.value, power: node.left };\n\treturn null;\n}\n\n/** Whether a node renders as a single indivisible token, so an exponent can follow it without parentheses. */\nfunction isAtomic(node: SymbolicNode): boolean {\n\tif (node.kind === \"var\" || node.kind === \"call\") return true;\n\t// A negative constant needs brackets under an exponent: `-2^2` parses as\n\t// `-(2^2)`, which is a different value from `(-2)^2`.\n\treturn node.kind === \"const\" && node.value.n >= 0n;\n}\n\n/** Renders `coeff` immediately followed by `text`, collapsing the 1 and -1 cases the way a person writes them. */\nfunction formatCoefficient(coeff: Rational, text: string): string {\n\tif (coeff.n === 1n && coeff.d === 1n) return text;\n\tif (coeff.n === -1n && coeff.d === 1n) return `-${text}`;\n\treturn `${formatRational(coeff)}${text}`;\n}\n\n/**\n * How deep the printer will walk before eliding the rest.\n *\n * This walk and {@link collectDisplayTerms} call each other down the tree with\n * nothing counting the levels, so the native stack was the only bound on\n * either, and it is reached at about 1,170 levels (measured, three frames per\n * level). `SYMBOLIC_MAX_NODES` admits ten thousand nodes, and for a chain size\n * and depth are the same number, so there was a wide band of trees the engine\n * called legal and could not print. What came out of that band was a raw\n * `RangeError` reading \"Maximum call stack size exceeded\", from `formatValue()`\n * of all places, which is the one call a host makes to render an answer it has\n * already been given and therefore the one it is least likely to have wrapped\n * in a `try`.\n *\n * About half the measured limit rather than the quarter that would be\n * comfortable, because an expression five hundred levels deep must still print\n * in full (pinned in `__tests__/hardening/DenialOfServiceRecursionDepth.spec.ts`)\n * and a printer that elides what it can render is its own kind of wrong answer.\n * {@link formatSymbolic} therefore also catches the overflow itself, so the\n * margin being wrong somewhere with less stack to spare degrades the display\n * rather than escaping as a RangeError.\n *\n * Eliding rather than throwing, because the caller asked to display a value and\n * an ellipsis is a display. It is also honest in a way silent truncation would\n * not be: the marker says the text is not the whole tree.\n */\nconst MAX_FORMAT_DEPTH = 600;\n\n/** What stands in for the part of a tree too deep to print. */\nconst ELIDED = \"...\";\n\n/**\n * Formats a factor, wrapping a nested sum in parentheses, which is needed\n * whenever it appears inside a `mul`, `div`, `neg` or `pow`.\n */\nfunction formatFactor(node: SymbolicNode, depth: number): string {\n\tif (depth >= MAX_FORMAT_DEPTH) return ELIDED;\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\t\treturn formatRational(node.value);\n\t\tcase \"complex\":\n\t\t\t// Only a value with BOTH parts is a sum, and only a sum needs brackets\n\t\t\t// inside a product: `(2+3i)*x` but `sqrt(2)*i`. Bracketing every\n\t\t\t// complex would make the common imaginary-only case read as `(i)`.\n\t\t\treturn node.value.re.n !== 0n && node.value.im.n !== 0n\n\t\t\t\t? `(${formatComplex(node.value)})`\n\t\t\t\t: formatComplex(node.value);\n\t\tcase \"var\":\n\t\t\treturn node.name;\n\t\tcase \"add\":\n\t\tcase \"sub\":\n\t\t\t// Not `depth + 1`: this hands the SAME node to the sum printer, and\n\t\t\t// the counter has to measure tree levels rather than call frames, or\n\t\t\t// a five-hundred-level expression would be elided at two hundred and\n\t\t\t// fifty. Every other recursion below descends into a child, and\n\t\t\t// those do count.\n\t\t\treturn `(${formatSum(node, depth)})`;\n\t\tcase \"neg\":\n\t\t\treturn `-${formatFactor(node.operand, depth + 1)}`;\n\t\tcase \"call\":\n\t\t\t// Written as an arrow rather than passing `formatSum` to `map`\n\t\t\t// directly: `map` calls its callback with the index as a second\n\t\t\t// argument, which would arrive here as the depth.\n\t\t\treturn `${node.name}(${node.args.map(arg => formatSum(arg, depth + 1)).join(\", \")})`;\n\t\tcase \"pow\": {\n\t\t\tconst base = isAtomic(node.base) ? formatFactor(node.base, depth + 1) : `(${formatSum(node.base, depth + 1)})`;\n\t\t\t// An exponent that is itself compound needs brackets, since `x^n+1`\n\t\t\t// would otherwise read as `(x^n)+1`.\n\t\t\tconst exponent = isAtomic(node.exponent) ? formatFactor(node.exponent, depth + 1) : `(${formatSum(node.exponent, depth + 1)})`;\n\t\t\treturn `${base}^${exponent}`;\n\t\t}\n\t\tcase \"mul\": {\n\t\t\tconst coeffVar = tryExtractCoeffVar(node);\n\t\t\tif (coeffVar) return formatCoefficient(coeffVar.coeff, coeffVar.name);\n\t\t\tconst coeffPow = tryExtractCoeffPow(node);\n\t\t\tif (coeffPow) return formatCoefficient(coeffPow.coeff, formatFactor(coeffPow.power, depth + 1));\n\t\t\t// A coefficient on a longer monomial juxtaposes too, so `2*x*y`\n\t\t\t// renders `2x*y`, consistent with `2b` and `2x^2` above. Only the\n\t\t\t// leading coefficient collapses; the `*` between distinct variables\n\t\t\t// stays, matching how the rest of the engine writes products.\n\t\t\t//\n\t\t\t// The digit guard is not cosmetic. Juxtaposing onto text that itself\n\t\t\t// starts with a digit produces a different number: `3*(2*x)` would\n\t\t\t// render as `32x`, which reads as thirty-two x. Such a shape should\n\t\t\t// have been folded to `6x` by the simplifier, so this is a safety net\n\t\t\t// rather than the normal path, but a formatter must never be able to\n\t\t\t// print one value as another.\n\t\t\tif (node.left.kind === \"const\" && node.right.kind === \"mul\") {\n\t\t\t\tconst inner = formatFactor(node.right, depth + 1);\n\t\t\t\tif (!/^[\\d.]/.test(inner)) return formatCoefficient(node.left.value, inner);\n\t\t\t}\n\t\t\treturn `${formatFactor(node.left, depth + 1)}*${formatFactor(node.right, depth + 1)}`;\n\t\t}\n\t\tcase \"div\": {\n\t\t\t// A denominator that is itself a product or a quotient must be\n\t\t\t// bracketed. Without this, `1/(2*sqrt(x))` prints as `1/2*sqrt(x)`,\n\t\t\t// which reads back as `(1/2)*sqrt(x)`, a different number: at x=9 the\n\t\t\t// tree is 1/6 and the text says 1.5. `a/(b/c)` had the same problem,\n\t\t\t// printing `a/b/c`, which regroups left-to-right into `(a/b)/c`.\n\t\t\t// A sum or difference is already bracketed by formatFactor itself, and\n\t\t\t// a power binds tighter than division so `1/x^2` needs nothing.\n\t\t\tconst denominator = formatFactor(node.right, depth + 1);\n\t\t\tconst needsBrackets = node.right.kind === \"mul\" || node.right.kind === \"div\";\n\t\t\treturn `${formatFactor(node.left, depth + 1)}/${needsBrackets ? `(${denominator})` : denominator}`;\n\t\t}\n\t}\n}\n\n/**\n * Collects a possibly-unsimplified `add`/`sub`/`neg` chain into signed display\n * terms. Mirrors the simplifier's own `flattenSum` traversal, but tolerant:\n * a `mul`/`div`/`pow`/`call` subtree becomes one opaque signed term via\n * {@link formatFactor} rather than aborting the whole walk.\n */\nfunction collectDisplayTerms(node: SymbolicNode, negated: boolean, out: { negated: boolean; text: string }[], depth: number): void {\n\tif (depth >= MAX_FORMAT_DEPTH) {\n\t\tout.push({ negated, text: ELIDED });\n\t\treturn;\n\t}\n\tswitch (node.kind) {\n\t\tcase \"add\":\n\t\t\tcollectDisplayTerms(node.left, negated, out, depth + 1);\n\t\t\tcollectDisplayTerms(node.right, negated, out, depth + 1);\n\t\t\treturn;\n\t\tcase \"sub\":\n\t\t\tcollectDisplayTerms(node.left, negated, out, depth + 1);\n\t\t\tcollectDisplayTerms(node.right, !negated, out, depth + 1);\n\t\t\treturn;\n\t\tcase \"neg\":\n\t\t\tcollectDisplayTerms(node.operand, !negated, out, depth + 1);\n\t\t\treturn;\n\t\tcase \"const\": {\n\t\t\t// An embedded zero term contributes nothing to the display.\n\t\t\tif (node.value.n === 0n) return;\n\t\t\tconst isNegative = node.value.n < 0n;\n\t\t\tconst magnitude = isNegative ? { n: -node.value.n, d: node.value.d } : node.value;\n\t\t\tout.push({ negated: isNegative !== negated, text: formatRational(magnitude) });\n\t\t\treturn;\n\t\t}\n\t\tcase \"complex\": {\n\t\t\t// Split into two display terms so a complex at the top level joins the\n\t\t\t// surrounding sum naturally: `2+3i` and `-1-2i` rather than a single\n\t\t\t// bracketed blob. The bracketing in formatFactor is for when a complex\n\t\t\t// sits inside a product, where it genuinely needs it.\n\t\t\tconst { re, im } = node.value;\n\t\t\tif (re.n !== 0n) {\n\t\t\t\tconst negativeReal = re.n < 0n;\n\t\t\t\tout.push({ negated: negativeReal !== negated, text: formatRational(negativeReal ? { n: -re.n, d: re.d } : re) });\n\t\t\t}\n\t\t\tif (im.n !== 0n) {\n\t\t\t\tconst negativeImaginary = im.n < 0n;\n\t\t\t\tconst magnitude = negativeImaginary ? { n: -im.n, d: im.d } : im;\n\t\t\t\tconst text = magnitude.n === 1n && magnitude.d === 1n ? \"i\" : `${formatRational(magnitude)}i`;\n\t\t\t\tout.push({ negated: negativeImaginary !== negated, text });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tdefault: {\n\t\t\t// Same node, so same depth. See formatFactor's add/sub case.\n\t\t\tconst text = formatFactor(node, depth);\n\t\t\t// A product or quotient whose leading coefficient is negative renders\n\t\t\t// with the minus already inside it, and joining that to a sum with `+`\n\t\t\t// gives `0.5*log(x-1)+-0.5*log(x+1)`. Lifting the sign out turns it back\n\t\t\t// into the subtraction it is. Only these two kinds: for a `pow` a leading\n\t\t\t// minus belongs to the base rather than to the whole factor, so `-2^2`\n\t\t\t// must not become a subtracted `2^2`.\n\t\t\tconst liftsSign = (node.kind === \"mul\" || node.kind === \"div\") && text.startsWith(\"-\");\n\t\t\tif (liftsSign) out.push({ negated: !negated, text: text.slice(1) });\n\t\t\telse out.push({ negated, text });\n\t\t}\n\t}\n}\n\n/**\n * Renders a symbolic expression as display text.\n *\n * @param node - The tree to render.\n * @returns The display string. An expression whose terms all cancel renders as\n * `\"0\"` rather than as an empty string.\n */\nexport function formatSymbolic(node: SymbolicNode): string {\n\ttry {\n\t\treturn formatSum(node, 0);\n\t} catch (thrown) {\n\t\t// The depth guard above is what normally stops this, and this is the\n\t\t// backstop for it being set half a stack away from the native limit: a\n\t\t// caller that has already spent stack of its own can run out inside a\n\t\t// tree the guard would have allowed. A stack overflow is a RangeError\n\t\t// rather than an EngineError, so a host cannot tell it from a bug in its\n\t\t// own code, and it arrives through `formatValue()`, which is a request\n\t\t// to display an answer and has no business throwing. Nothing else is\n\t\t// swallowed: any other error is the caller's to see.\n\t\tif (thrown instanceof RangeError) return ELIDED;\n\t\tthrow thrown;\n\t}\n}\n\n/**\n * The body of {@link formatSymbolic}, carrying how deep the walk already is.\n *\n * Split out so the public entry point keeps its one-argument signature: it is\n * exported, and a second parameter on it would be filled in by anything that\n * passes it to `Array.prototype.map`.\n */\nfunction formatSum(node: SymbolicNode, depth: number): string {\n\tconst terms: { negated: boolean; text: string }[] = [];\n\tcollectDisplayTerms(node, false, terms, depth);\n\tif (terms.length === 0) return \"0\";\n\n\tlet out = \"\";\n\tterms.forEach((term, index) => {\n\t\tif (index === 0) out += term.negated ? `-${term.text}` : term.text;\n\t\telse out += term.negated ? `-${term.text}` : `+${term.text}`;\n\t});\n\treturn out;\n}\n","import { type MatrixData, type MatrixEntry, type RangeData, Value, ValueType, matrixValue, numberValue, boolValue, symbolicValue, errorValue, faultedOperand } from \"@solve-js/vm/Value\";\nimport { type SymbolicNode, constNode, simplifySymbolic, isRationalZero, rationalToNumber } from \"@solve-js/symbolic\";\nimport { checkedArray } from \"@solve-js/vm/AllocationBudget\";\n\n/**\n * Shared, pure helpers for reading/building {@link MatrixData}. Kept\n * separate from `VM.ts`'s opcode dispatch and `VMConversion.ts`'s\n * `binaryOp()` so every consumer (arithmetic, indexing, transpose/inverse,\n * map/reduce) reads/writes matrix storage through the same column-major\n * convention rather than each re-deriving the row/col math independently.\n */\n\n/** Column-major single-index read, `a[i]` in the spec's own notation. */\nexport function matIndex(m: MatrixData, index: number): MatrixEntry {\n\treturn m.data[index];\n}\n\n/** `[row, col]` read (both 0-based), via the column-major storage formula `row + col*rows`. */\nexport function matAt(m: MatrixData, row: number, col: number): MatrixEntry {\n\treturn m.data[row + col * m.rows];\n}\n\n/** Whether `[row, col]` is a valid cell for `m`. */\nexport function inBounds(m: MatrixData, row: number, col: number): boolean {\n\treturn row >= 0 && row < m.rows && col >= 0 && col < m.cols;\n}\n\n/**\n * Whether two matrices have identical dimensions.\n *\n * @param a - First matrix.\n * @param b - Second matrix.\n * @returns True when rows and columns both match, which is the precondition\n * for every element-wise operation.\n */\nexport function sameShape(a: MatrixData, b: MatrixData): boolean {\n\treturn a.rows === b.rows && a.cols === b.cols;\n}\n\n/**\n * Whether a matrix has as many rows as columns.\n *\n * @param m - The matrix.\n * @returns True when square. Determinant and inverse are defined only here.\n */\nexport function isSquare(m: MatrixData): boolean {\n\treturn m.rows === m.cols;\n}\n\n/** Converts a matrix cell into a SymbolicNode, its own tree if already symbolic, else a `const` node (boolean coerced to 0/1). */\nexport function entryToSymbolic(entry: MatrixEntry): SymbolicNode {\n\tif (typeof entry === \"object\" && entry !== null) return entry;\n\tif (typeof entry === \"boolean\") return constNode(entry ? 1 : 0);\n\treturn constNode(entry);\n}\n\n/** Collapses a simplified SymbolicNode back to a plain number when it's a pure constant, keeps matrix cells in their simplest representation rather than always carrying a wrapped tree. */\nexport function symbolicToEntry(node: SymbolicNode): MatrixEntry {\n\tconst simplified = simplifySymbolic(node);\n\t// Collapse to a plain number, never to the Rational itself. MatrixEntry is\n\t// `number | boolean | SymbolicNode`, and a leaked Rational would satisfy the\n\t// `typeof cell === \"object\"` test that FormatEngine.ts and Value.ts use to\n\t// recognise a symbolic cell, rendering as garbage rather than throwing.\n\treturn simplified.kind === \"const\" ? rationalToNumber(simplified.value) : simplified;\n}\n\n/** Converts a matrix cell into a real Value, Boolean/Symbolic preserved as-is, plain numbers wrapped via numberValue(). Used anywhere a cell needs to leave MatrixData and become an ordinary VM value (indexing, map/reduce collection iteration). */\nexport function matrixEntryToValue(cell: MatrixEntry): Value {\n\tif (typeof cell === \"boolean\") return boolValue(cell);\n\tif (typeof cell === \"object\" && cell !== null) return symbolicValue(cell);\n\treturn numberValue(cell);\n}\n\n/**\n * A matrix literal is naturally written and parsed row-major (`[1,2;3,4]`\n * reads row 0 then row 1), but {@link MatrixData.data} is stored\n * column-major (matching the spec's own `a[index]` semantics directly).\n * This is the one place that translation happens, every other consumer\n * of `MatrixData` just reads/writes column-major storage directly.\n */\nexport function rowMajorToColumnMajor(rows: number, cols: number, rowMajorData: readonly MatrixEntry[]): MatrixEntry[] {\n\tconst data = new Array<MatrixEntry>(rows * cols);\n\tfor (let r = 0; r < rows; r++) {\n\t\tfor (let c = 0; c < cols; c++) {\n\t\t\tdata[r + c * rows] = rowMajorData[r * cols + c];\n\t\t}\n\t}\n\treturn data;\n}\n\n/** Inverse of {@link rowMajorToColumnMajor}, used by display code, which reads back out row-by-row. */\nexport function columnMajorToRowMajor(m: MatrixData): MatrixEntry[] {\n\tconst data = new Array<MatrixEntry>(m.rows * m.cols);\n\tfor (let r = 0; r < m.rows; r++) {\n\t\tfor (let c = 0; c < m.cols; c++) {\n\t\t\tdata[r * m.cols + c] = matAt(m, r, c);\n\t\t}\n\t}\n\treturn data;\n}\n\n/**\n * `*` between two matrices, genuinely different from `+`/`-`/comparisons\n * which stay element-wise. Distinguishes three cases per the Calca spec:\n * a `1×1` operand (\"scalar\") broadcasts (multiplies every cell of the\n * other operand); otherwise, if the inner dimensions agree\n * (`l.cols === r.rows`), this is a real `(m×n)*(n×p)=(m×p)` matrix\n * product; anything else is a dimension mismatch. Called from VM.ts's MUL\n * case BEFORE falling through to the always-element-wise `binaryOp()`\n * `binaryOp()` itself never disambiguates multiplication this way.\n *\n * Symbolic-aware: when either operand `hasSymbolic`, every cell is\n * computed via `SymbolicNode` add/multiply + simplify instead of plain\n * `number` arithmetic, the ordinary numeric fast path only runs when\n * NEITHER operand carries any symbolic cell.\n *\n * The result array is asked for through `checkedArray()` rather than taken\n * with a bare `new Array`, because this is the one arithmetic result whose\n * size is the PRODUCT of two separately affordable operands, and the tally in\n * `vm/AllocationBudget.ts` cannot refuse an allocation that has already\n * happened. `OpCode.MUL` checks the same number before calling here, which is\n * a duplicate check and not a duplicate charge (`checkAllocation` refuses\n * without recording, deliberately). The check lives here as well because MUL\n * is not the only way in: `dot()` is this same multiplication reached through\n * `CALL_BUILTIN`, and `abs`, `det`, `inv` and `pow` reach it too, and every\n * one of those used to arrive at a bare `new Array(rows * cols)`. Four hundred\n * million cells through `dot()` aborted the process in 1.3 seconds while the\n * `*` spelling of the identical product was refused in 18 milliseconds.\n */\nexport function matrixMultiply(l: MatrixData, r: MatrixData): Value {\n\tconst lIsScalar = l.rows === 1 && l.cols === 1;\n\tconst rIsScalar = r.rows === 1 && r.cols === 1;\n\tconst useSymbolic = l.hasSymbolic || r.hasSymbolic;\n\n\tif (lIsScalar || rIsScalar) {\n\t\tconst [scalarOperand, matrixOperand] = lIsScalar ? [l, r] : [r, l];\n\t\tif (useSymbolic) {\n\t\t\tconst scalarNode = entryToSymbolic(scalarOperand.data[0]);\n\t\t\tconst result = matrixOperand.data.map(v => symbolicToEntry(simplifySymbolic({ kind: \"mul\", left: entryToSymbolic(v), right: scalarNode })));\n\t\t\treturn matrixValue(matrixOperand.rows, matrixOperand.cols, result);\n\t\t}\n\t\tconst scalar = scalarOperand.data[0] as number;\n\t\tconst result = matrixOperand.data.map(v => (v as number) * scalar);\n\t\treturn matrixValue(matrixOperand.rows, matrixOperand.cols, result);\n\t}\n\n\tif (l.cols !== r.rows) {\n\t\treturn errorValue(\n\t\t\t\"DIMENSION_MISMATCH\",\n\t\t\t`Cannot multiply a ${l.rows}x${l.cols} matrix by a ${r.rows}x${r.cols} matrix — inner dimensions must match (${l.cols} !== ${r.rows}).`,\n\t\t);\n\t}\n\n\tconst resultRows = l.rows;\n\tconst resultCols = r.cols;\n\tconst data = checkedArray<MatrixEntry>(resultRows * resultCols, \"matrix cells\");\n\tfor (let row = 0; row < resultRows; row++) {\n\t\tfor (let col = 0; col < resultCols; col++) {\n\t\t\tif (useSymbolic) {\n\t\t\t\tlet acc: SymbolicNode = constNode(0);\n\t\t\t\tfor (let k = 0; k < l.cols; k++) {\n\t\t\t\t\tconst term: SymbolicNode = { kind: \"mul\", left: entryToSymbolic(matAt(l, row, k)), right: entryToSymbolic(matAt(r, k, col)) };\n\t\t\t\t\tacc = simplifySymbolic({ kind: \"add\", left: acc, right: term });\n\t\t\t\t}\n\t\t\t\tdata[row + col * resultRows] = symbolicToEntry(acc);\n\t\t\t} else {\n\t\t\t\tlet sum = 0;\n\t\t\t\tfor (let k = 0; k < l.cols; k++) {\n\t\t\t\t\tsum += (matAt(l, row, k) as number) * (matAt(r, k, col) as number);\n\t\t\t\t}\n\t\t\t\tdata[row + col * resultRows] = sum;\n\t\t\t}\n\t\t}\n\t}\n\treturn matrixValue(resultRows, resultCols, data);\n}\n\n/**\n * `a^k` for a square matrix and a whole, non-negative `k`, by repeated\n * multiplication.\n *\n * Matrix power is repeated matrix multiplication, not the element-wise\n * `Math.pow` the `^` operator otherwise means, so this cannot go through\n * `binaryOp()`. `k = 0` is the identity, which is what makes the whole thing\n * consistent: `a^0 * a^n` is `a^n` for every n.\n *\n * Squaring rather than multiplying one factor at a time keeps `a^1000000`\n * to twenty multiplications instead of a million, so a large exponent is\n * slow arithmetic rather than a hung editor. Symbolic cells ride along for\n * free, since {@link matrixMultiply} already handles them.\n *\n * A non-square matrix, or an exponent that is negative or fractional, is\n * refused rather than answered: `a^-1` is spelled that way and is taken by\n * the parser's own caret-suffix rule (see `parser/PrecedenceParser.ts`), and\n * a fractional matrix power is a genuinely different problem (a matrix\n * square root need not exist, and need not be unique when it does).\n *\n * @param m - The base.\n * @param exponent - The power, which must be a non-negative integer.\n * @returns The resulting Matrix, or an error Value describing the refusal.\n */\nexport function matrixPower(m: MatrixData, exponent: number): Value {\n\tif (!isSquare(m)) {\n\t\treturn errorValue(\"MATRIX_POWER_REQUIRES_SQUARE_MATRIX\", `^: only a square matrix can be raised to a power (got ${m.rows}x${m.cols}).`);\n\t}\n\tif (!Number.isInteger(exponent) || exponent < 0) {\n\t\treturn errorValue(\n\t\t\t\"MATRIX_POWER_REQUIRES_WHOLE_EXPONENT\",\n\t\t\t`^: a matrix can only be raised to a whole number of 0 or more (got ${exponent}); \"^-1\" means the inverse and \"^T\" the transpose.`,\n\t\t);\n\t}\n\tconst n = m.rows;\n\tconst identity = new Array<MatrixEntry>(n * n).fill(0);\n\tfor (let i = 0; i < n; i++) identity[i + i * n] = 1;\n\tlet accumulated: MatrixData = { rows: n, cols: n, data: identity, hasSymbolic: false };\n\tlet squared = m;\n\tlet remaining = exponent;\n\twhile (remaining > 0) {\n\t\tif (remaining % 2 === 1) {\n\t\t\tconst product = matrixMultiply(accumulated, squared);\n\t\t\tif (product.type === ValueType.Error) return product;\n\t\t\taccumulated = product.value as MatrixData;\n\t\t}\n\t\tremaining = Math.floor(remaining / 2);\n\t\tif (remaining > 0) {\n\t\t\tconst doubled = matrixMultiply(squared, squared);\n\t\t\tif (doubled.type === ValueType.Error) return doubled;\n\t\t\tsquared = doubled.value as MatrixData;\n\t\t}\n\t}\n\t// Rebuilt through matrixValue() so the result carries a correctly\n\t// recomputed `hasSymbolic`, rather than the identity's own `false`.\n\treturn matrixValue(accumulated.rows, accumulated.cols, accumulated.data);\n}\n\n/**\n * Element-wise comparison, `[1,6;3,8] < [5,2;7,4] => [true,false;true,false]`.\n * Unlike arithmetic, comparison NEVER does matrix-vs-matrix \"real\" dispatch\n * (there's no such thing as a \"comparison product\"), always element-wise\n * same shape required, producing a Matrix of booleans.\n *\n * NOT symbolic-aware, comparing a free-variable formula's ordering has no\n * general meaning without knowing its value (is `sx < 5`? unknowable), and\n * no spec example compares two symbolic matrices, a disclosed, narrow gap\n * rather than attempted-and-wrong.\n */\nexport function matrixCompare(l: MatrixData, r: MatrixData, cmp: (a: number, b: number) => boolean): Value {\n\tif (!sameShape(l, r)) {\n\t\treturn errorValue(\n\t\t\t\"DIMENSION_MISMATCH\",\n\t\t\t`Cannot compare matrices of different shapes: ${l.rows}x${l.cols} and ${r.rows}x${r.cols}`,\n\t\t);\n\t}\n\tconst data: MatrixEntry[] = new Array(l.data.length);\n\tfor (let i = 0; i < l.data.length; i++) data[i] = cmp(l.data[i] as number, r.data[i] as number);\n\treturn matrixValue(l.rows, l.cols, data);\n}\n\n/** `a^T`, swaps rows/cols; cell `[r,c]` in the result is cell `[c,r]` in `m`. Cell-type-agnostic (just rearranges), so this needs no symbolic-aware variant. */\nexport function transpose(m: MatrixData): Value {\n\tconst data = new Array<MatrixEntry>(m.rows * m.cols);\n\tfor (let r = 0; r < m.cols; r++) {\n\t\tfor (let c = 0; c < m.rows; c++) {\n\t\t\tdata[r + c * m.cols] = matAt(m, c, r);\n\t\t}\n\t}\n\treturn matrixValue(m.cols, m.rows, data);\n}\n\n/**\n * Copies `m` into a plain row-major `number[][]` working copy for\n * elimination, {@link numericDeterminant}/{@link numericInverse} both\n * mutate their own copy in place rather than touching `m.data` (which\n * callers may still hold a reference to elsewhere).\n */\nfunction toWorkingRows(m: MatrixData): number[][] {\n\tconst rows: number[][] = [];\n\tfor (let r = 0; r < m.rows; r++) {\n\t\tconst row: number[] = [];\n\t\tfor (let c = 0; c < m.cols; c++) row.push(matAt(m, r, c) as number);\n\t\trows.push(row);\n\t}\n\treturn rows;\n}\n\n/**\n * Largest matrix {@link integerDeterminant} will attempt.\n *\n * Bareiss keeps every intermediate a minor of the original matrix, so the\n * bigints stay bounded by Hadamard's inequality rather than growing without\n * limit. What this bounds is the cubic loop itself, and it follows the\n * precedent of {@link SYMBOLIC_INVERSE_DIMENSION_LIMIT}: a named ceiling with\n * a stated reason rather than an arbitrary inline number. A larger matrix\n * still gets an answer, from the elimination below.\n */\nconst EXACT_DETERMINANT_DIMENSION_LIMIT = 12;\n\n/**\n * Every cell as an exact bigint, or `null` when the matrix is not wholly\n * integral.\n *\n * Booleans are excluded rather than coerced, so a matrix of comparison results\n * keeps whatever the elimination has always made of it.\n */\nfunction toIntegerRows(m: MatrixData): bigint[][] | null {\n\tif (m.rows > EXACT_DETERMINANT_DIMENSION_LIMIT) return null;\n\tconst rows: bigint[][] = [];\n\tfor (let r = 0; r < m.rows; r++) {\n\t\tconst row: bigint[] = [];\n\t\tfor (let c = 0; c < m.cols; c++) {\n\t\t\tconst cell = matAt(m, r, c);\n\t\t\tif (typeof cell !== \"number\" || !Number.isSafeInteger(cell)) return null;\n\t\t\trow.push(BigInt(cell));\n\t\t}\n\t\trows.push(row);\n\t}\n\treturn rows;\n}\n\n/**\n * The determinant of an integer matrix, exactly, by Bareiss's fraction-free\n * elimination.\n *\n * Ordinary elimination divides by the pivot at every step, and those divisions\n * are what leave `det([1,2,3;4,5,6;7,8,9])` reading `6.661338147750939e-16`\n * instead of the zero it is. The matrix is singular, and \"very nearly zero\" is\n * not a different answer from zero, it is the same answer with the reader left\n * to decide. Bareiss divides by the **previous** pivot instead, and that\n * division is exactly divisible as a theorem, so every intermediate stays a\n * whole number and a singular matrix comes out as an exact `0n`.\n *\n * @param rows - The matrix, row-major, which this mutates as its working copy.\n * @returns The determinant.\n */\nfunction integerDeterminant(rows: bigint[][]): bigint {\n\tconst n = rows.length;\n\tlet previous = 1n;\n\tlet sign = 1n;\n\n\tfor (let k = 0; k < n - 1; k++) {\n\t\tif (rows[k][k] === 0n) {\n\t\t\tlet candidate = -1;\n\t\t\tfor (let r = k + 1; r < n; r++) {\n\t\t\t\tif (rows[r][k] !== 0n) {\n\t\t\t\t\tcandidate = r;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// No pivot anywhere in the column means a zero column below k, so the\n\t\t\t// matrix is singular and its determinant is exactly zero.\n\t\t\tif (candidate === -1) return 0n;\n\t\t\tconst swapped = rows[k];\n\t\t\trows[k] = rows[candidate];\n\t\t\trows[candidate] = swapped;\n\t\t\tsign = -sign;\n\t\t}\n\t\tfor (let i = k + 1; i < n; i++) {\n\t\t\tfor (let j = k + 1; j < n; j++) {\n\t\t\t\trows[i][j] = (rows[i][j] * rows[k][k] - rows[i][k] * rows[k][j]) / previous;\n\t\t\t}\n\t\t}\n\t\tprevious = rows[k][k];\n\t}\n\treturn sign * rows[n - 1][n - 1];\n}\n\n/**\n * `|a|` / `det(a)`, exactly when every cell is a whole number, and otherwise by\n * Gaussian elimination with partial pivoting, reusing the elimination's own\n * running pivot product as the determinant (rather than a separate\n * cofactor-expansion implementation). A row swap flips the product's sign,\n * matching the standard determinant-under-row-swap identity. A zero pivot\n * column (no non-zero candidate at or below it) means the matrix is singular,\n * determinant 0, not an error, since 0 is the mathematically correct answer for\n * a singular matrix.\n *\n * The integer route is tried first because an integer matrix has an integer\n * determinant, and a method that cannot return one is answering a question\n * nobody asked. See {@link integerDeterminant}.\n */\nfunction numericDeterminant(m: MatrixData): Value {\n\tconst integers = toIntegerRows(m);\n\tif (integers !== null) return numberValue(Number(integerDeterminant(integers)));\n\n\tconst n = m.rows;\n\tconst a = toWorkingRows(m);\n\tlet det = 1;\n\tfor (let col = 0; col < n; col++) {\n\t\tlet pivotRow = col;\n\t\tlet maxAbs = Math.abs(a[col][col]);\n\t\tfor (let r = col + 1; r < n; r++) {\n\t\t\tif (Math.abs(a[r][col]) > maxAbs) { maxAbs = Math.abs(a[r][col]); pivotRow = r; }\n\t\t}\n\t\tif (maxAbs === 0) return numberValue(0);\n\t\tif (pivotRow !== col) {\n\t\t\tconst tmp = a[col]; a[col] = a[pivotRow]; a[pivotRow] = tmp;\n\t\t\tdet = -det;\n\t\t}\n\t\tdet *= a[col][col];\n\t\tfor (let r = col + 1; r < n; r++) {\n\t\t\tconst factor = a[r][col] / a[col][col];\n\t\t\tif (factor === 0) continue;\n\t\t\tfor (let c = col; c < n; c++) a[r][c] -= factor * a[col][c];\n\t\t}\n\t}\n\treturn numberValue(det);\n}\n\n/**\n * Symbolic determinant, SAME diagonal-first, NO-row-swap elimination\n * strategy as {@link symbolicInverse} (see its own doc comment for why:\n * row-swapping under free-variable pivots has no general \"is this bigger\"\n * ordering to search by). A pivot that simplifies to the exact constant\n * `0` yields determinant `0` (mathematically correct for a genuinely\n * singular structure); anything else, including a pivot that's an\n * unresolved formula which MIGHT be zero for some assignment, is treated\n * as non-zero and elimination proceeds. This is a disclosed limitation,\n * not full symbolic zero-detection (out of scope, \"not a general CAS\").\n */\nfunction symbolicDeterminant(m: MatrixData): Value {\n\tconst n = m.rows;\n\tconst a: SymbolicNode[][] = [];\n\tfor (let r = 0; r < n; r++) {\n\t\tconst row: SymbolicNode[] = [];\n\t\tfor (let c = 0; c < n; c++) row.push(entryToSymbolic(matAt(m, r, c)));\n\t\ta.push(row);\n\t}\n\tlet det: SymbolicNode = constNode(1);\n\tfor (let col = 0; col < n; col++) {\n\t\tconst pivot = simplifySymbolic(a[col][col]);\n\t\t// Exact, unlike the previous double comparison: a structurally-zero pivot\n\t\t// could arrive as 5.551e-17 and be treated as non-zero, so a singular\n\t\t// matrix reported a nonsense determinant instead of zero.\n\t\tif (pivot.kind === \"const\" && isRationalZero(pivot.value)) return numberValue(0);\n\t\tdet = simplifySymbolic({ kind: \"mul\", left: det, right: pivot });\n\t\tfor (let r = col + 1; r < n; r++) {\n\t\t\tconst factor = simplifySymbolic({ kind: \"div\", left: a[r][col], right: pivot });\n\t\t\tfor (let c = col; c < n; c++) {\n\t\t\t\ta[r][c] = simplifySymbolic({ kind: \"sub\", left: a[r][c], right: { kind: \"mul\", left: factor, right: a[col][c] } });\n\t\t\t}\n\t\t}\n\t}\n\treturn det.kind === \"const\" ? numberValue(rationalToNumber(det.value)) : symbolicValue(det);\n}\n\n/** `|a|` / `det(a)`, dispatches to the symbolic or plain-numeric implementation based on `m.hasSymbolic`. */\nexport function determinant(m: MatrixData): Value {\n\tif (!isSquare(m)) {\n\t\treturn errorValue(\"DETERMINANT_REQUIRES_SQUARE_MATRIX\", `det: matrix must be square (got ${m.rows}x${m.cols}).`);\n\t}\n\treturn m.hasSymbolic ? symbolicDeterminant(m) : numericDeterminant(m);\n}\n\n/**\n * `a^-1` / `inv(a)`, Gauss-Jordan elimination with partial pivoting on\n * the augmented `[A | I]` matrix, reducing the left half to the identity\n * while the right half becomes `A`'s inverse. Requires a square, non-\n * singular matrix, a near-zero pivot (below `1e-10`, guarding against\n * floating-point noise rather than requiring an exact zero) means the\n * matrix isn't invertible, reported as a clear error rather than\n * returning `Infinity`-poisoned cells.\n */\nfunction numericInverse(m: MatrixData): Value {\n\tconst n = m.rows;\n\tconst a = toWorkingRows(m);\n\tfor (let r = 0; r < n; r++) {\n\t\tfor (let c = 0; c < n; c++) a[r].push(c === r ? 1 : 0);\n\t}\n\tfor (let col = 0; col < n; col++) {\n\t\tlet pivotRow = col;\n\t\tlet maxAbs = Math.abs(a[col][col]);\n\t\tfor (let r = col + 1; r < n; r++) {\n\t\t\tif (Math.abs(a[r][col]) > maxAbs) { maxAbs = Math.abs(a[r][col]); pivotRow = r; }\n\t\t}\n\t\tif (maxAbs < 1e-10) {\n\t\t\treturn errorValue(\"SINGULAR_MATRIX\", `inv: a ${n}x${n} matrix with a zero (or near-zero) pivot column is not invertible.`);\n\t\t}\n\t\tif (pivotRow !== col) {\n\t\t\tconst tmp = a[col]; a[col] = a[pivotRow]; a[pivotRow] = tmp;\n\t\t}\n\t\tconst pivot = a[col][col];\n\t\tfor (let c = 0; c < 2 * n; c++) a[col][c] /= pivot;\n\t\tfor (let r = 0; r < n; r++) {\n\t\t\tif (r === col) continue;\n\t\t\tconst factor = a[r][col];\n\t\t\tif (factor === 0) continue;\n\t\t\tfor (let c = 0; c < 2 * n; c++) a[r][c] -= factor * a[col][c];\n\t\t}\n\t}\n\tconst data = new Array<MatrixEntry>(n * n);\n\tfor (let r = 0; r < n; r++) {\n\t\tfor (let c = 0; c < n; c++) data[r + c * n] = a[r][n + c];\n\t}\n\treturn matrixValue(n, n, data);\n}\n\n/** Matrices at or beyond this size are rejected for symbolic inversion. See {@link symbolicInverse}'s doc comment. */\nconst SYMBOLIC_INVERSE_DIMENSION_LIMIT = 9;\n\n/**\n * Symbolic Gauss-Jordan inverse, SAME [A|I] augmented-elimination shape\n * as {@link numericInverse}, but every cell is a `SymbolicNode` and every\n * arithmetic step (divide by pivot, multiply-and-subtract to eliminate a\n * column) goes through `simplifySymbolic()` instead of plain `number` ops.\n *\n * Deliberately uses a DIAGONAL-FIRST pivot strategy with NO row-swapping\n * a real, disclosed limitation: `numericInverse`'s partial-pivoting\n * searches for the numerically-largest candidate, but there's no general\n * \"is this free-variable formula bigger than that one\" ordering to search\n * by, so this always pivots on the diagonal entry as-is. A pivot that\n * simplifies to the exact constant `0` is reported as singular/unsolvable\n * via this strategy (a genuinely different structure, or one needing row\n * reordering the caller would have to do manually, produces this error)\n * this is sufficient for the spec's own already-triangular-friendly\n * example (`s`/`t`'s diagonal entries are never structurally zero).\n *\n * Capped at {@link SYMBOLIC_INVERSE_DIMENSION_LIMIT}, beyond this\n * expression trees from repeated symbolic elimination steps can grow\n * large enough to make the \"not a general CAS\" bounded simplifier\n * genuinely slow; the spec's own examples are all well under this size.\n */\nfunction symbolicInverse(m: MatrixData): Value {\n\tconst n = m.rows;\n\tif (n >= SYMBOLIC_INVERSE_DIMENSION_LIMIT) {\n\t\treturn errorValue(\n\t\t\t\"SYMBOLIC_INVERSE_DIMENSION_LIMIT\",\n\t\t\t`Symbolic matrix inversion is limited to matrices smaller than ${SYMBOLIC_INVERSE_DIMENSION_LIMIT}x${SYMBOLIC_INVERSE_DIMENSION_LIMIT} (got ${n}x${n}).`,\n\t\t);\n\t}\n\tconst a: SymbolicNode[][] = [];\n\tfor (let r = 0; r < n; r++) {\n\t\tconst row: SymbolicNode[] = [];\n\t\tfor (let c = 0; c < n; c++) row.push(entryToSymbolic(matAt(m, r, c)));\n\t\tfor (let c = 0; c < n; c++) row.push(constNode(c === r ? 1 : 0));\n\t\ta.push(row);\n\t}\n\tfor (let col = 0; col < n; col++) {\n\t\tconst pivot = simplifySymbolic(a[col][col]);\n\t\tif (pivot.kind === \"const\" && isRationalZero(pivot.value)) {\n\t\t\treturn errorValue(\n\t\t\t\t\"SYMBOLIC_SINGULAR_OR_UNSUPPORTED_PIVOT\",\n\t\t\t\t`Symbolic inverse: the pivot at row/col ${col} is exactly zero — this matrix's structure isn't invertible via this engine's diagonal-first symbolic elimination (no row-swapping); try reordering rows manually.`,\n\t\t\t);\n\t\t}\n\t\t// Eliminate first, divide the pivot row through afterwards, which is\n\t\t// the order {@link symbolicDeterminant} already uses and the reason it\n\t\t// answers 0 for a structurally singular matrix this used to invert.\n\t\t// Dividing first makes the factor the raw entry and the eliminated\n\t\t// cell `b - a*(b/a)`, and the simplifier does not cancel a division\n\t\t// buried under a multiplication, so the second pivot of `[a,b;a,b]`\n\t\t// arrived as `b-a*b/a` rather than as zero and the matrix was inverted\n\t\t// into cells containing `1/(b-a*b/a)`, a division by nothing. This\n\t\t// order divides before multiplying instead: the factor is `a/a`, which\n\t\t// does simplify to 1, leaving `b - b` and an exact zero pivot.\n\t\tfor (let r = 0; r < n; r++) {\n\t\t\tif (r === col) continue;\n\t\t\tconst factor = simplifySymbolic({ kind: \"div\", left: a[r][col], right: pivot });\n\t\t\tif (factor.kind === \"const\" && isRationalZero(factor.value)) continue;\n\t\t\tfor (let c = 0; c < 2 * n; c++) {\n\t\t\t\ta[r][c] = simplifySymbolic({ kind: \"sub\", left: a[r][c], right: { kind: \"mul\", left: factor, right: a[col][c] } });\n\t\t\t}\n\t\t}\n\t\tfor (let c = 0; c < 2 * n; c++) {\n\t\t\ta[col][c] = simplifySymbolic({ kind: \"div\", left: a[col][c], right: pivot });\n\t\t}\n\t}\n\tconst data = new Array<MatrixEntry>(n * n);\n\tfor (let r = 0; r < n; r++) {\n\t\tfor (let c = 0; c < n; c++) data[r + c * n] = symbolicToEntry(a[r][n + c]);\n\t}\n\treturn matrixValue(n, n, data);\n}\n\n/** `a^-1` / `inv(a)`, dispatches to the symbolic or plain-numeric implementation based on `m.hasSymbolic`. */\nexport function inverse(m: MatrixData): Value {\n\tif (!isSquare(m)) {\n\t\treturn errorValue(\"INVERSE_REQUIRES_SQUARE_MATRIX\", `inv: matrix must be square (got ${m.rows}x${m.cols}).`);\n\t}\n\treturn m.hasSymbolic ? symbolicInverse(m) : numericInverse(m);\n}\n\n/** The refusal {@link collectionToValues} answers with once a collection is bigger than the caller's ceiling. */\nfunction tooLarge(length: number, maxElements: number): Value {\n\treturn errorValue(\n\t\t\"COLLECTION_TOO_LARGE\",\n\t\t`This collection has ${length} elements, past the limit of ${maxElements} (see the engine's vm.maxCollectionSize setting).`,\n\t);\n}\n\n/**\n * Reads a `map`/`reduce` \"collection\" argument into a flat array of\n * per-cell Values, a Matrix's own cells (column-major order, matching\n * `MAT_INDEX1`'s reading convention) or a Range materialized into its\n * inclusive integer sequence (`0:3` -> `[0,1,2,3]`, matching `map(f,\n * 0:3)`'s spec example). Returns an error Value directly (not thrown) if\n * `v` is neither. Same \"propagate as a value, don't throw\" convention\n * `matrixMultiply`/`matrixCompare` above already use.\n *\n * `maxElements` bounds what a Range is allowed to become. It defaults to\n * unbounded so that a caller with no configured engine (a direct unit test\n * of this helper) behaves as before, every VM call site passes\n * `vm.getMaxCollectionSize()`.\n */\nexport function collectionToValues(v: Value, maxElements = Number.POSITIVE_INFINITY): Value[] | Value {\n\t// Pending as well as Error: neither is a collection, and a collection that\n\t// has not arrived is not an empty one. See `faultedOperand()` in vm/Value.ts.\n\tconst faulted = faultedOperand(v);\n\tif (faulted) return faulted;\n\tif (v.type === ValueType.Matrix) {\n\t\tconst m = v.value as MatrixData;\n\t\tif (m.data.length > maxElements) return tooLarge(m.data.length, maxElements);\n\t\treturn m.data.map(matrixEntryToValue);\n\t}\n\tif (v.type === ValueType.Range) {\n\t\tconst r = v.value as RangeData;\n\t\t// Counted before anything is allocated, not while allocating: the\n\t\t// expansion of `1:100000000` reaches the heap limit and aborts the\n\t\t// process, and an abort is not something a `try` can contain.\n\t\tconst length = r.max - r.min + 1;\n\t\tif (length > maxElements) return tooLarge(length, maxElements);\n\t\tconst out: Value[] = new Array<Value>(length);\n\t\tfor (let i = 0; i < length; i++) out[i] = numberValue(r.min + i);\n\t\treturn out;\n\t}\n\treturn errorValue(\n\t\t\"MAP_REDUCE_REQUIRES_COLLECTION\",\n\t\t`map/reduce requires a Matrix or Range collection (e.g. \"[1,2,3]\" or \"0:3\").`,\n\t);\n}\n","import { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * An exact base-ten number, held as an integer coefficient and a scale.\n *\n * The value is `coef * 10^(-scale)`, so `Decimal(30n, 2)` is exactly `0.30` and\n * `Decimal(1005n, 3)` is exactly `1.005`. `scale` is a non-negative integer\n * count of fractional digits, the sign lives on `coef`, and zero is\n * `Decimal(0n, s)` for any `s`.\n *\n * This is the representation money is carried in so that two prices a user\n * typed add and multiply without the binary-floating-point error a double\n * introduces (`0.1 + 0.2` is `0.30000000000000004` as a double, `0.30` here).\n * It is deliberately dependency-free: a bigint coefficient plus an integer\n * scale needs nothing the runtime does not already have, which keeps the\n * engine's single-runtime-dependency contract intact.\n */\nexport interface DecimalData {\n\t/** The integer coefficient, carrying the sign. */\n\treadonly coef: bigint;\n\t/** The number of fractional digits, a non-negative integer. */\n\treadonly scale: number;\n}\n\n/**\n * How division and display rounding break a tie.\n *\n * Half away from zero is the reading a person doing money by hand uses (a half\n * cent rounds up to the next cent, and a negative one rounds down to the next),\n * and it is what `Intl.NumberFormat` picks by default. It is the one mode this\n * module implements, named so the call sites read as decisions rather than\n * defaults.\n */\nexport type RoundingMode = \"halfAwayFromZero\";\n\n/**\n * How many fractional digits a non-terminating division keeps.\n *\n * `$10 / 3` has no exact decimal, so the quotient is rounded to this many\n * places. Twenty is far more than any currency displays and enough that the\n * double taken from it (via {@link decimalToNumber}) is the same one the\n * ordinary float division would have produced, so nothing downstream sees a\n * coarser answer than before.\n */\nexport const DEFAULT_DIVISION_SCALE = 20;\n\n/** Powers of ten, memoized, since scale alignment asks for the same few often. */\nconst POW10: bigint[] = [1n];\nfunction pow10(n: number): bigint {\n\tif (n < 0) {\n\t\tthrow ErrorFactory.internal(\"DECIMAL_NEGATIVE_POWER\", `pow10 needs a non-negative exponent, got ${n}`, { exponent: n });\n\t}\n\tfor (let i = POW10.length; i <= n; i++) POW10[i] = POW10[i - 1] * 10n;\n\treturn POW10[n];\n}\n\n/** Build a {@link DecimalData}, guarding the scale invariant in one place. */\nexport function makeDecimal(coef: bigint, scale: number): DecimalData {\n\tif (!Number.isInteger(scale) || scale < 0) {\n\t\tthrow ErrorFactory.internal(\"DECIMAL_INVALID_SCALE\", `A decimal scale must be a non-negative integer, got ${scale}`, { scale });\n\t}\n\treturn { coef, scale };\n}\n\n/** The exact decimal for a whole number. */\nexport function decimalFromInteger(n: bigint | number): DecimalData {\n\treturn { coef: typeof n === \"bigint\" ? n : BigInt(n), scale: 0 };\n}\n\n/**\n * The exact decimal a plain number stands for, or `null` when it has none.\n *\n * Only whole numbers convert: a whole-valued double is exactly the integer it\n * prints as, so lifting it is lossless. A fractional double (`0.1`, the result\n * of `sqrt(2)`) is NOT its printed decimal, it is the nearest double to it, so\n * there is no exact decimal to recover and this returns `null` rather than\n * inventing one. That null is the boundary that keeps float where float\n * belongs: a fractional double meeting money stays a double.\n */\nexport function decimalFromNumberIfExact(n: number): DecimalData | null {\n\tif (!Number.isFinite(n) || !Number.isInteger(n)) return null;\n\treturn decimalFromInteger(BigInt(n));\n}\n\n/**\n * Parse a normalized dot-decimal literal (`\"0.10\"`, `\"1.005\"`, `\"1234.5\"`).\n *\n * The input is what the parser has already reduced a number literal to: any\n * thousands grouping stripped and the locale's decimal separator rewritten as\n * a single `\".\"`. That is why this does not consult a locale, and why it is\n * exact where {@link decimalFromNumberIfExact} is not: the digits are read\n * straight into the coefficient without ever passing through a double.\n *\n * @throws A parsing `INVALID_DECIMAL_LITERAL` error for a string that is not a\n * plain decimal, which the caller should never produce (the lexer validates the\n * literal first) but which is reported rather than guessed at if it does.\n */\nexport function decimalFromLiteral(text: string): DecimalData {\n\tlet s = text;\n\tlet negative = false;\n\tif (s.startsWith(\"-\")) { negative = true; s = s.slice(1); }\n\telse if (s.startsWith(\"+\")) { s = s.slice(1); }\n\tconst dot = s.indexOf(\".\");\n\tconst intPart = dot < 0 ? s : s.slice(0, dot);\n\tconst fracPart = dot < 0 ? \"\" : s.slice(dot + 1);\n\t// A single trailing dot (\"5.\") or a bare fraction (\".5\") are both fine; the\n\t// halves just come out empty and read as zero digits.\n\tconst digits = (intPart + fracPart) || \"0\";\n\tif (!/^[0-9]+$/.test(digits)) {\n\t\tthrow ErrorFactory.parsing(\"INVALID_DECIMAL_LITERAL\", `Not a decimal literal: \"${text}\"`, { raw: text });\n\t}\n\tlet coef = BigInt(digits);\n\tif (negative) coef = -coef;\n\treturn { coef, scale: fracPart.length };\n}\n\n/** Bring two decimals to a shared scale, returning both coefficients and it. */\nfunction align(a: DecimalData, b: DecimalData): { ca: bigint; cb: bigint; scale: number } {\n\tif (a.scale === b.scale) return { ca: a.coef, cb: b.coef, scale: a.scale };\n\tif (a.scale > b.scale) return { ca: a.coef, cb: b.coef * pow10(a.scale - b.scale), scale: a.scale };\n\treturn { ca: a.coef * pow10(b.scale - a.scale), cb: b.coef, scale: b.scale };\n}\n\n/** Exact sum. */\nexport function decimalAdd(a: DecimalData, b: DecimalData): DecimalData {\n\tconst { ca, cb, scale } = align(a, b);\n\treturn { coef: ca + cb, scale };\n}\n\n/** Exact difference. */\nexport function decimalSubtract(a: DecimalData, b: DecimalData): DecimalData {\n\tconst { ca, cb, scale } = align(a, b);\n\treturn { coef: ca - cb, scale };\n}\n\n/** Exact product. The scales add, which is exactly the base-ten rule. */\nexport function decimalMultiply(a: DecimalData, b: DecimalData): DecimalData {\n\treturn { coef: a.coef * b.coef, scale: a.scale + b.scale };\n}\n\n/** Exact negation. */\nexport function decimalNegate(a: DecimalData): DecimalData {\n\treturn { coef: -a.coef, scale: a.scale };\n}\n\n/** Whether the value is exactly zero, regardless of scale. */\nexport function decimalIsZero(a: DecimalData): boolean {\n\treturn a.coef === 0n;\n}\n\n/**\n * Round a coefficient/scale pair to `targetScale` fractional digits, breaking\n * ties away from zero.\n *\n * Scaling UP is exact (append zeros). Scaling DOWN drops digits, and the tie\n * rule looks only at whether twice the dropped remainder reaches the divisor,\n * which is the half-away-from-zero test done in integers so it never rounds a\n * value it was handed exactly.\n */\nfunction roundCoefToScale(coef: bigint, scale: number, targetScale: number): bigint {\n\tif (targetScale >= scale) return coef * pow10(targetScale - scale);\n\tconst divisor = pow10(scale - targetScale);\n\tconst negative = coef < 0n;\n\tconst magnitude = negative ? -coef : coef;\n\tlet q = magnitude / divisor;\n\tconst r = magnitude % divisor;\n\t// Away from zero on a tie: 2*r === divisor rounds up, as does 2*r > divisor.\n\tif (r * 2n >= divisor) q += 1n;\n\treturn negative ? -q : q;\n}\n\n/** Round to `targetScale` fractional digits, half away from zero. */\nexport function decimalRound(a: DecimalData, targetScale: number): DecimalData {\n\treturn { coef: roundCoefToScale(a.coef, a.scale, targetScale), scale: targetScale };\n}\n\n/**\n * Quotient of two decimals, exact where it terminates and rounded to\n * `maxFractionDigits` where it does not.\n *\n * The caller guarantees a non-zero divisor: exact decimal division has no\n * answer at zero, the same way integer division does not, so the money\n * arithmetic checks {@link decimalIsZero} first and keeps the double's Infinity\n * for that case rather than routing it here.\n */\nexport function decimalDivide(a: DecimalData, b: DecimalData, maxFractionDigits: number = DEFAULT_DIVISION_SCALE): DecimalData {\n\tif (decimalIsZero(b)) {\n\t\tthrow ErrorFactory.internal(\"DECIMAL_DIVISION_BY_ZERO\", \"decimalDivide was called with a zero divisor\", {});\n\t}\n\t// a/b at result scale s is round( a.coef * 10^(s + b.scale) / (b.coef * 10^a.scale) ).\n\tconst s = maxFractionDigits;\n\tconst numerator = a.coef * pow10(s + b.scale);\n\tconst denominator = b.coef * pow10(a.scale);\n\tconst negative = (numerator < 0n) !== (denominator < 0n);\n\tconst num = numerator < 0n ? -numerator : numerator;\n\tconst den = denominator < 0n ? -denominator : denominator;\n\tlet q = num / den;\n\tconst r = num % den;\n\tif (r * 2n >= den) q += 1n;\n\treturn { coef: negative ? -q : q, scale: s };\n}\n\n/** Three-way comparison: -1, 0 or 1. */\nexport function decimalCompare(a: DecimalData, b: DecimalData): -1 | 0 | 1 {\n\tconst { ca, cb } = align(a, b);\n\tif (ca < cb) return -1;\n\tif (ca > cb) return 1;\n\treturn 0;\n}\n\n/**\n * The exact decimal as a plain string, with no rounding and no grouping.\n *\n * Used both to hand a lossless value to `Number()` (which then rounds to the\n * nearest double once, correctly) and as the basis for fixed-precision display.\n */\nexport function decimalToString(a: DecimalData): string {\n\tconst negative = a.coef < 0n;\n\tlet digits = (negative ? -a.coef : a.coef).toString();\n\tif (a.scale === 0) return negative ? `-${digits}` : digits;\n\tif (digits.length <= a.scale) digits = digits.padStart(a.scale + 1, \"0\");\n\tconst cut = digits.length - a.scale;\n\tconst whole = digits.slice(0, cut);\n\tconst frac = digits.slice(cut);\n\treturn `${negative ? \"-\" : \"\"}${whole}.${frac}`;\n}\n\n/**\n * The nearest double to the exact value.\n *\n * Goes through {@link decimalToString} so the value is rounded to a double\n * exactly once, from its full decimal form, rather than accumulating error\n * through a `Number(coef) / Number(10^scale)` division.\n */\nexport function decimalToNumber(a: DecimalData): number {\n\treturn Number(decimalToString(a));\n}\n\n/**\n * Render with exactly `fractionDigits` decimal places, rounded half away from\n * zero.\n *\n * This is the money-display path, and it is where the exact representation pays\n * off visibly: `$1.005` shows as `1.01` and `$2.675` as `2.68`, where\n * `(1.005).toFixed(2)` and `(2.675).toFixed(2)` answer `1.00` and `2.67`\n * because the double handed to `toFixed` is already a hair below the value the\n * user typed. No thousands grouping, matching the existing `toFixed`-based\n * currency formatter this replaces.\n */\nexport function decimalToFixed(a: DecimalData, fractionDigits: number): string {\n\tconst rounded = decimalRound(a, fractionDigits);\n\tconst negative = rounded.coef < 0n && rounded.coef !== 0n;\n\tlet digits = (rounded.coef < 0n ? -rounded.coef : rounded.coef).toString();\n\tif (fractionDigits === 0) return negative ? `-${digits}` : digits;\n\tif (digits.length <= fractionDigits) digits = digits.padStart(fractionDigits + 1, \"0\");\n\tconst cut = digits.length - fractionDigits;\n\tconst whole = digits.slice(0, cut);\n\tconst frac = digits.slice(cut);\n\treturn `${negative ? \"-\" : \"\"}${whole}.${frac}`;\n}\n","/**\n * Currency symbol/word → ISO 4217 code aliases, and the reverse table used\n * for display formatting (see `format/FormatEngine.ts`'s `formatUom()`).\n *\n * Single source of truth for BOTH directions so the same ambiguity\n * decisions (documented inline below) aren't made twice, inconsistently,\n * in two different files.\n */\n\n/**\n * Currency SYMBOLS (non-alphanumeric characters), safe to recognize as\n * bare lexer tokens with zero risk of colliding with a variable name,\n * since `:name = expr` variable names can never be symbol characters.\n * `CurrencySymbolParselet.ts` consumes these directly.\n *\n * `¥`/`₱`/`peso` ambiguity note: the PESO SIGN (₱) is, per Unicode, the\n * Philippine peso specifically, but the WORD \"peso\" (see\n * `CURRENCY_WORD_ALIASES` below) defaults to the Mexican peso, the most\n * globally recognized \"peso\" in English financial writing. This is a\n * deliberate inconsistency between the symbol and the word for the same\n * general concept, same reasoning as `¥` (JPY) vs \"yuan\" (CNY) below\n * document rather than silently guess, and a user wanting the other one\n * can always type the ISO code directly (\"PHP\"/\"CNY\").\n */\nexport const CURRENCY_SYMBOL_ALIASES: Record<string, string> = {\n \"$\": \"USD\",\n \"£\": \"GBP\",\n \"€\": \"EUR\",\n // ¥ is genuinely ambiguous between JPY and CNY in real-world usage, JPY\n // is the conventional default (matches Numi/most calculator apps' own\n // choice); a user wanting CNY specifically can still type \"CNY\" directly.\n \"¥\": \"JPY\",\n \"₽\": \"RUB\",\n \"₩\": \"KRW\",\n \"₹\": \"INR\",\n \"₺\": \"TRY\",\n \"₴\": \"UAH\",\n \"₪\": \"ILS\",\n \"₫\": \"VND\",\n \"₦\": \"NGN\",\n \"₱\": \"PHP\",\n};\n\n/**\n * Currency WORD forms (singular/plural, all lowercase. This codebase's\n * unit table is strictly case-sensitive with no aliasing, so \"Euro\"/\"EURO\"\n * are deliberately NOT recognized, matching every other word-unit here).\n * Registered as `UNIT` tokens (see `lexer/units.ts`) rather than bare\n * keywords: a bare keyword can never be a `:variableName` (this codebase's\n * tested, intentional policy. See `VariableParselet.ts`'s doc comment)\n * but `:dollar = 5` etc. must keep working, and UNIT-typed tokens ARE\n * accepted as variable names (e.g. \":b = 5\" already works for the \"b\" bits\n * unit), so these ride the same safe mechanism `workday`/`workdays` used.\n *\n * Deliberately NOT included: \"pound\"/\"pounds\", already a MASS unit in\n * `lexer/units.ts` (450g, matching \"lb\"). Remapping it to GBP would be a\n * real, silent regression for anyone using \"5 pounds\" to mean weight; GBP\n * stays reachable via the £ symbol or the \"GBP\" code, same as before.\n *\n * Deliberately NOT included: \"dinar\", used by ~10 countries (Kuwaiti\n * Bahraini, Jordanian, Iraqi, Algerian, ... dinars) with wildly different\n * values (a Kuwaiti dinar is worth roughly 1000x an Algerian one), no\n * single default is defensible the way ¥→JPY or peso→MXN are. Type the\n * ISO code directly (KWD/BHD/JOD/...).\n *\n * Ambiguous-but-resolved cases, and why:\n * - \"peso\"/\"pesos\" → MXN (Mexican peso is the most globally recognized\n * \"peso\" in English financial writing). See the ₱ symbol note above\n * for why this deliberately differs from the ₱ SYMBOL's PHP mapping.\n * - \"franc\"/\"francs\" → CHF (Swiss franc; also used by several African\n * currencies, CHF is the overwhelmingly dominant \"franc\" in English use).\n * - \"krona\"/\"kronor\" → SEK (Swedish); \"krone\"/\"kroner\" → NOK (Norwegian)\n * Danish also uses \"krone\" (DKK) with the identical spelling as\n * Norwegian; NOK was picked arbitrarily as the more commonly-referenced\n * of the two in English text. Type \"DKK\" directly for Danish krone.\n * - \"riyal\"/\"riyals\"/\"rial\"/\"rials\" → SAR (Saudi riyal), both spellings\n * also refer to Qatari/Omani riyals and the Iranian rial; SAR is the\n * most commonly referenced in English. Type \"QAR\"/\"OMR\"/\"IRR\" directly\n * for the others.\n */\nexport const CURRENCY_WORD_ALIASES: Record<string, string> = {\n dollar: \"USD\", dollars: \"USD\",\n euro: \"EUR\", euros: \"EUR\",\n yen: \"JPY\",\n ruble: \"RUB\", rubles: \"RUB\", rouble: \"RUB\", roubles: \"RUB\",\n won: \"KRW\",\n rupee: \"INR\", rupees: \"INR\",\n yuan: \"CNY\", renminbi: \"CNY\",\n franc: \"CHF\", francs: \"CHF\",\n rand: \"ZAR\",\n krona: \"SEK\", kronor: \"SEK\",\n krone: \"NOK\", kroner: \"NOK\",\n real: \"BRL\", reais: \"BRL\",\n peso: \"MXN\", pesos: \"MXN\",\n shekel: \"ILS\", shekels: \"ILS\",\n lira: \"TRY\",\n hryvnia: \"UAH\", hryvnias: \"UAH\",\n zloty: \"PLN\", zlotys: \"PLN\",\n forint: \"HUF\",\n koruna: \"CZK\",\n dirham: \"AED\", dirhams: \"AED\",\n riyal: \"SAR\", riyals: \"SAR\", rial: \"SAR\", rials: \"SAR\",\n ringgit: \"MYR\",\n rupiah: \"IDR\",\n baht: \"THB\",\n dong: \"VND\",\n naira: \"NGN\",\n};\n\n/**\n * Resolve a raw lexed unit/symbol string to its canonical ISO 4217 code\n * e.g. `\"euro\"` -> `\"EUR\"`, `\"$\"` -> `\"USD\"`, `\"USD\"` -> `\"USD\"` (already\n * canonical, returned unchanged). Returns `undefined` if `text` isn't a\n * recognized currency alias at all (distinct from \"already canonical\"\n * callers should fall back to the original text in that case).\n */\nexport function resolveCurrencyAlias(text: string): string | undefined {\n return CURRENCY_SYMBOL_ALIASES[text] ?? CURRENCY_WORD_ALIASES[text.toLowerCase()];\n}\n\n/** How a currency's amount and symbol are conventionally arranged for display. */\nexport interface CurrencyDisplayInfo {\n /** The symbol/abbreviation to render, e.g. \"$\", \"kr\", \"R$\". */\n readonly symbol: string;\n /** Whether the symbol comes before or after the formatted amount. */\n readonly position: \"prefix\" | \"suffix\";\n /** Whether a space separates the symbol from the amount. */\n readonly spaced: boolean;\n}\n\n/**\n * Display convention per ISO code, for currencies with a widely-recognized\n * symbol/abbreviation and an unambiguous placement convention. NOT\n * exhaustive, any code absent here (most of the ~150 codes\n * `CurrencyExchange.isCurrency()` recognizes) falls back to the existing\n * \"amount CODE\" format (e.g. \"100.00 AED\") in `FormatEngine.formatUom()`,\n * exactly as before this table existed. Extend as needed, same pattern as\n * this session's other \"not exhaustive, additive\" tables (city timezones,\n * ingredient densities).\n *\n * Several currencies share the same symbol (USD/AUD/CAD/NZD/HKD/SGD/MXN\n * all conventionally use \"$\" locally). This is safe here because OUTPUT\n * formatting always starts from an already-resolved, unambiguous ISO code\n * (`value.unit`), unlike INPUT parsing where a bare \"$\" genuinely is\n * ambiguous (see `CURRENCY_SYMBOL_ALIASES`'s USD default above).\n */\nexport const CURRENCY_DISPLAY: Record<string, CurrencyDisplayInfo> = {\n USD: { symbol: \"$\", position: \"prefix\", spaced: false },\n AUD: { symbol: \"$\", position: \"prefix\", spaced: false },\n CAD: { symbol: \"$\", position: \"prefix\", spaced: false },\n NZD: { symbol: \"$\", position: \"prefix\", spaced: false },\n HKD: { symbol: \"$\", position: \"prefix\", spaced: false },\n SGD: { symbol: \"$\", position: \"prefix\", spaced: false },\n MXN: { symbol: \"$\", position: \"prefix\", spaced: false },\n GBP: { symbol: \"£\", position: \"prefix\", spaced: false },\n // English-language convention (€100.00), many EU locales instead suffix\n // with a space (\"100,00 €\"); this engine's default locale is \"en\", so\n // the English convention was chosen. A locale-aware override would be a\n // reasonable future extension, not attempted here.\n EUR: { symbol: \"€\", position: \"prefix\", spaced: false },\n JPY: { symbol: \"¥\", position: \"prefix\", spaced: false },\n CNY: { symbol: \"¥\", position: \"prefix\", spaced: false },\n KRW: { symbol: \"₩\", position: \"prefix\", spaced: false },\n INR: { symbol: \"₹\", position: \"prefix\", spaced: false },\n // Russian convention places the ruble sign AFTER the amount, with a space.\n RUB: { symbol: \"₽\", position: \"suffix\", spaced: true },\n TRY: { symbol: \"₺\", position: \"prefix\", spaced: false },\n UAH: { symbol: \"₴\", position: \"suffix\", spaced: true },\n ILS: { symbol: \"₪\", position: \"prefix\", spaced: false },\n // Vietnamese convention: no space, symbol after the amount.\n VND: { symbol: \"₫\", position: \"suffix\", spaced: false },\n NGN: { symbol: \"₦\", position: \"prefix\", spaced: false },\n PHP: { symbol: \"₱\", position: \"prefix\", spaced: false },\n BRL: { symbol: \"R$\", position: \"prefix\", spaced: false },\n ZAR: { symbol: \"R\", position: \"prefix\", spaced: false },\n // Scandinavian convention: amount then \"kr\", space-separated.\n SEK: { symbol: \"kr\", position: \"suffix\", spaced: true },\n NOK: { symbol: \"kr\", position: \"suffix\", spaced: true },\n DKK: { symbol: \"kr\", position: \"suffix\", spaced: true },\n PLN: { symbol: \"zł\", position: \"suffix\", spaced: true },\n CHF: { symbol: \"Fr\", position: \"suffix\", spaced: true },\n HUF: { symbol: \"Ft\", position: \"suffix\", spaced: true },\n CZK: { symbol: \"Kč\", position: \"suffix\", spaced: true },\n};\n"]}
1
+ {"version":3,"sources":["../src/symbolic/Rational.ts","../src/symbolic/Complex.ts","../src/symbolic/SymbolicNode.ts","../src/symbolic/Polynomial.ts","../src/symbolic/Gcd.ts","../src/symbolic/Radicals.ts","../src/symbolic/Simplify.ts","../src/symbolic/SymbolicFormat.ts","../src/vm/MatrixOps.ts","../src/decimal/Decimal.ts","../src/uom/CurrencyAliases.ts"],"names":["RATIONAL_ZERO","RATIONAL_ONE","RATIONAL_MINUS_ONE","RATIONAL_MAX_BITS","MAX_MAGNITUDE","bigintPow","base","exponent","result","factor","remaining","gcd","a","b","x","y","remainder","guardMagnitude","d","ErrorFactory","normalize","numerator","denominator","divisor","rational","DECIMAL_FORM","rationalFromNumber","value","parts","sign","integerDigits","fractionDigits","exponentDigits","rationalToNumber","r","direct","rationalAdd","rationalSub","rationalMul","rationalDiv","rationalNeg","rationalPow","positive","rationalCompare","left","right","isRationalZero","isRationalOne","isRationalMinusOne","isRationalInteger","MAX_DECIMAL_DIGITS","MAX_FRACTION_COMPONENT","formatRational","twos","fives","terminates","decimals","scaled","digits","whole","fraction","COMPLEX_ZERO","COMPLEX_ONE","COMPLEX_I","complex","re","im","isComplexZero","z","complexAdd","complexSub","complexMul","complexDiv","complexNeg","complexConjugate","complexNormSquared","complexPow","complexEquals","formatComplex","magnitude","imaginary","exactComplexSqrt","modulus","exactRationalSqrt","two","realPart","imaginaryPart","exactBigintSqrt","previous","current","SYMBOLIC_MAX_NODES","constNode","varNode","name","powNode","callNode","args","symbolicKey","node","nodesEqual","other","arg","i","nodeCount","limit","pending","total","freeVariables","names","collectVariables","into","substitute","variable","replacement","complexNode","EXPAND_MAX_POW_EXPONENT","POLYNOMIAL_MAX_TERMS","POLYNOMIAL_MAX_DEGREE","monomialToKey","monomial","monomialFromKey","key","caret","monomialDegree","build","terms","kept","coeff","constantPolynomial","polyAdd","existing","polySub","polyScale","polyMul","leftKey","leftCoeff","leftMonomial","rightKey","rightCoeff","combined","polyPow","p","next","k","polyDegree","highest","degree","polyUnivariateVar","polyCoefficients","coefficients","toPolynomial","allowDistribution","operand","compareMonomials","vars","degreeDifference","difference","monomialToNode","termToNode","fromPolynomial","keys","firstPositive","expandSymbolic","polynomial","trim","last","isZeroPolynomial","polynomialDivide","dividend","divisorDegree","leading","quotient","offset","monic","trimmed","coefficient","coefficientGcd","polynomialGcd","sharedVariable","coefficientsToPolynomial","power","cancelRational","gcdCoefficients","reducedNumerator","reducedDenominator","cancelSymbolic","reduced","divideOutConstant","original","constant","squareFreePart","derivative","shared","exactIntegerSqrt","exactIntegerCbrt","negative","low","high","middle","cube","surdNode","radicand","extracted","square","scale","root","signedSurdNode","flattenSum","negated","out","depth","MAX_SIMPLIFY_DEPTH","collectTerms","flat","order","coeffByName","term","termNodes","collectSum","rationalFloor","truncated","MAX_FOLDED_FACTORIAL","foldCall","first","rootN","rootD","simplifySymbolic","depthOnEntry","walkDepth","simplifyNode","simplified","simplifyNodeAt","asComplex","foldComplexBinary","kind","foldComplexCall","foldedAdd","foldedSub","foldedMul","foldedDiv","cancelled","product","folded","complexFolded","tryExtractCoeffVar","tryExtractCoeffPow","isAtomic","formatCoefficient","text","MAX_FORMAT_DEPTH","ELIDED","formatFactor","formatSum","coeffVar","coeffPow","inner","needsBrackets","collectDisplayTerms","isNegative","negativeReal","negativeImaginary","formatSymbolic","thrown","index","matIndex","m","matAt","row","col","inBounds","sameShape","isSquare","entryToSymbolic","entry","symbolicToEntry","matrixEntryToValue","cell","boolValue","symbolicValue","numberValue","rowMajorToColumnMajor","rows","cols","rowMajorData","data","c","columnMajorToRowMajor","matrixMultiply","l","lIsScalar","rIsScalar","useSymbolic","scalarOperand","matrixOperand","scalarNode","v","matrixValue","scalar","errorValue","resultRows","resultCols","checkedArray","acc","sum","matrixPower","n","identity","accumulated","squared","doubled","matrixCompare","cmp","transpose","toWorkingRows","EXACT_DETERMINANT_DIMENSION_LIMIT","toIntegerRows","integerDeterminant","candidate","swapped","j","numericDeterminant","integers","det","pivotRow","maxAbs","tmp","symbolicDeterminant","pivot","determinant","numericInverse","SYMBOLIC_INVERSE_DIMENSION_LIMIT","symbolicInverse","inverse","tooLarge","length","maxElements","collectionToValues","faulted","faultedOperand","DEFAULT_DIVISION_SCALE","POW10","pow10","makeDecimal","coef","decimalFromInteger","decimalFromNumberIfExact","decimalFromLiteral","s","dot","intPart","fracPart","align","decimalAdd","ca","cb","decimalSubtract","decimalMultiply","decimalNegate","decimalIsZero","roundCoefToScale","targetScale","q","decimalRound","decimalDivide","maxFractionDigits","num","den","decimalCompare","decimalTo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,IAAA,CAAM,QAAA,CAAU,SAAU,MAAA,CAAQ,IAAK,CAAA,CACtD,GAAA,CAAK,CAAE,MAAA,CAAQ,IAAA,CAAM,QAAA,CAAU,QAAA,CAAU,OAAQ,IAAK,CAAA,CACtD,GAAA,CAAK,CAAE,MAAA,CAAQ,SAAA,CAAM,QAAA,CAAU,QAAA,CAAU,OAAQ,IAAK,CAAA,CACtD,GAAA,CAAK,CAAE,MAAA,CAAQ,IAAA,CAAM,QAAA,CAAU,QAAA,CAAU,OAAQ,IAAK,CAAA,CACtD,GAAA,CAAK,CAAE,MAAA,CAAQ,IAAA,CAAM,QAAA,CAAU,QAAA,CAAU,OAAQ,IAAK,CAAA,CACtD,GAAA,CAAK,CAAE,OAAQ,SAAA,CAAM,QAAA,CAAU,QAAA,CAAU,MAAA,CAAQ,IAAK,CACxD","file":"chunk-75XDS65A.cjs","sourcesContent":["/**\n * Exact rational arithmetic over `bigint`, the coefficient type for every\n * part of the symbolic algebra system.\n *\n * A computer-algebra system cannot work in IEEE doubles. Factoring\n * `x^2 - x/3 - 2/3` needs `1/3` to stay `1/3` rather than becoming\n * `0.3333333333333333`, and the rational-root theorem tests candidate roots\n * by exact division, where a rounding error is indistinguishable from a\n * genuine root. Every coefficient in `SymbolicNode`, `Polynomial`, `Factor`\n * and `Solve` is a Rational for that reason.\n *\n * Values are always normalized on construction (`d > 0n`, `gcd(|n|, d) === 1n`,\n * zero is exactly `0n/1n`), so structural equality on the `{n, d}` pair is\n * mathematical equality, and the pair can be used directly as a cache key.\n *\n * A Rational holds two `bigint`s. Structured clone, which is what the\n * playground's `postMessage` uses to ship a `SymbolicNode` to the VM trace\n * view, handles bigint correctly. `JSON.stringify` does not: it throws\n * `TypeError: Do not know how to serialize a BigInt`. Do not introduce a JSON\n * round-trip anywhere a Rational can reach.\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * An exact rational number.\n *\n * Always normalized, see this module's own doc comment for the invariant.\n * Construct via {@link rational} or {@link rationalFromNumber} rather than as\n * an object literal, which would bypass normalization.\n */\nexport interface Rational {\n\t/** Signed numerator. Carries the sign of the whole value. */\n\treadonly n: bigint;\n\t/** Denominator, always strictly positive. */\n\treadonly d: bigint;\n}\n\n/** The rational `0`. */\nexport const RATIONAL_ZERO: Rational = { n: 0n, d: 1n };\n\n/** The rational `1`. */\nexport const RATIONAL_ONE: Rational = { n: 1n, d: 1n };\n\n/** The rational `-1`. */\nexport const RATIONAL_MINUS_ONE: Rational = { n: -1n, d: 1n };\n\n/**\n * Magnitude ceiling, in bits, on either component of a Rational.\n *\n * Repeated exact elimination (a symbolic matrix inverse, synthetic division\n * down a long factor chain) multiplies denominators together, so an unbounded\n * Rational can grow until bigint arithmetic itself becomes the bottleneck.\n * 4096 bits is far beyond any coefficient a human writes, while still bounding\n * a single multiply to microseconds. Follows the precedent set by\n * `vm/MatrixOps.ts`'s own `SYMBOLIC_INVERSE_DIMENSION_LIMIT`: a named\n * constant with a stated reason rather than an arbitrary inline number.\n */\nexport const RATIONAL_MAX_BITS = 4096;\n\n/** Precomputed `2 ** RATIONAL_MAX_BITS`, so the guard is one comparison rather than a `toString(2)` walk. */\nconst MAX_MAGNITUDE = 1n << BigInt(RATIONAL_MAX_BITS);\n\n/**\n * Bigint exponentiation by repeated squaring.\n *\n * Written out rather than using `**`, deliberately. The test tsconfig targets\n * ES6, where TypeScript lowers `a ** b` to `Math.pow(a, b)`, and `Math.pow`\n * throws `TypeError: Cannot convert a BigInt value to a number`. So `10n ** 3n`\n * compiles fine and passes a typecheck, then fails only at runtime under the\n * test target. Do not reintroduce `**` on bigints anywhere in this module.\n */\nfunction bigintPow(base: bigint, exponent: bigint): bigint {\n\tlet result = 1n;\n\tlet factor = base;\n\tlet remaining = exponent;\n\twhile (remaining > 0n) {\n\t\tif (remaining % 2n === 1n) result *= factor;\n\t\tfactor *= factor;\n\t\tremaining /= 2n;\n\t}\n\treturn result;\n}\n\n/** Euclid's algorithm on absolute values. Returns `0n` only when both inputs are zero. */\nfunction gcd(a: bigint, b: bigint): bigint {\n\tlet x = a < 0n ? -a : a;\n\tlet y = b < 0n ? -b : b;\n\twhile (y !== 0n) {\n\t\tconst remainder = x % y;\n\t\tx = y;\n\t\ty = remainder;\n\t}\n\treturn x;\n}\n\n/** Raises {@link RATIONAL_MAX_BITS} as an error rather than letting bigint growth run away silently. */\nfunction guardMagnitude(n: bigint, d: bigint): void {\n\tconst magnitude = n < 0n ? -n : n;\n\tif (magnitude >= MAX_MAGNITUDE || d >= MAX_MAGNITUDE) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_RATIONAL_OVERFLOW\",\n\t\t\t`This calculation produced a fraction too large to represent exactly (over ${RATIONAL_MAX_BITS} bits).`,\n\t\t\t{ limitBits: RATIONAL_MAX_BITS },\n\t\t);\n\t}\n}\n\n/**\n * Reduces a numerator/denominator pair to the normalized form this module\n * guarantees everywhere.\n *\n * @param n - Numerator, may be negative.\n * @param d - Denominator, may be negative, must not be zero.\n * @returns The normalized rational.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` when `d` is zero,\n * `SYMBOLIC_RATIONAL_OVERFLOW` past {@link RATIONAL_MAX_BITS}.\n */\nfunction normalize(n: bigint, d: bigint): Rational {\n\tif (d === 0n) {\n\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Division by zero in a symbolic expression.\");\n\t}\n\tif (n === 0n) return RATIONAL_ZERO;\n\n\t// Carry the sign on the numerator so `d > 0n` always holds, which is what\n\t// lets rationalCompare() cross-multiply without tracking sign flips.\n\tlet numerator = d < 0n ? -n : n;\n\tlet denominator = d < 0n ? -d : d;\n\n\tconst divisor = gcd(numerator, denominator);\n\tnumerator /= divisor;\n\tdenominator /= divisor;\n\n\tguardMagnitude(numerator, denominator);\n\treturn { n: numerator, d: denominator };\n}\n\n/**\n * Builds a normalized rational from bigint components.\n *\n * @param numerator - The numerator.\n * @param denominator - The denominator, defaulting to `1n`.\n * @returns The normalized rational.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` when `denominator` is zero.\n */\nexport function rational(numerator: bigint, denominator: bigint = 1n): Rational {\n\treturn normalize(numerator, denominator);\n}\n\n/** Matches every form `Number.prototype.toString` produces for a finite value, including the `e±n` variants used outside `[1e-6, 1e21)`. */\nconst DECIMAL_FORM = /^(-?)(\\d+)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;\n\n/**\n * Converts a JavaScript number to its exact rational value **as written**,\n * via the decimal string form rather than the IEEE expansion.\n *\n * This distinction is the single sharpest edge in this module. The double\n * nearest to `0.1` is exactly `3602879701896397 / 36028797018963968`, which is\n * mathematically correct and useless to display or factor with. Going through\n * `String(0.1)`, which is `\"0.1\"`, yields `1/10`: the number the user actually\n * typed. `Number.prototype.toString` is specified to emit the shortest decimal\n * that round-trips, so this is well defined rather than a heuristic.\n *\n * @param value - Any finite number.\n * @returns The exact rational for that number's decimal representation.\n * @throws {EngineError} `SYMBOLIC_NONFINITE_OPERAND` for `NaN` or `±Infinity`,\n * neither of which has a rational image.\n */\nexport function rationalFromNumber(value: number): Rational {\n\tif (!Number.isFinite(value)) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_NONFINITE_OPERAND\",\n\t\t\t`\"${String(value)}\" has no exact value, so it cannot appear in a symbolic expression.`,\n\t\t\t{ value: String(value) },\n\t\t);\n\t}\n\tif (Number.isInteger(value)) return normalize(BigInt(value), 1n);\n\n\tconst parts = DECIMAL_FORM.exec(String(value));\n\tif (parts === null) {\n\t\tthrow ErrorFactory.internal(\n\t\t\t\"INTERNAL_RATIONAL_PARSE\",\n\t\t\t`Internal error: could not read \"${String(value)}\" as a decimal number.`,\n\t\t\t{ value: String(value) },\n\t\t);\n\t}\n\n\tconst [, sign, integerDigits, fractionDigits = \"\", exponentDigits] = parts;\n\tlet numerator = BigInt(integerDigits + fractionDigits);\n\tlet denominator = bigintPow(10n, BigInt(fractionDigits.length));\n\n\tconst exponent = exponentDigits === undefined ? 0 : Number(exponentDigits);\n\tif (exponent > 0) numerator *= bigintPow(10n, BigInt(exponent));\n\telse if (exponent < 0) denominator *= bigintPow(10n, BigInt(-exponent));\n\n\treturn normalize(sign === \"-\" ? -numerator : numerator, denominator);\n}\n\n/**\n * Approximates a rational as a double, for the boundary back into ordinary\n * numeric Values and matrix cells.\n *\n * @param r - The rational.\n * @returns The nearest double, or `±Infinity` when the value genuinely\n * exceeds double range.\n */\nexport function rationalToNumber(r: Rational): number {\n\tif (r.d === 1n) return Number(r.n);\n\n\tconst direct = Number(r.n) / Number(r.d);\n\tif (!Number.isNaN(direct)) return direct;\n\n\t// Both components individually overflow a double, so the naive division is\n\t// Infinity/Infinity. Dividing in bigint space with 64 guard bits first\n\t// keeps the ratio, and scaling back by a power of two is exact in binary\n\t// floating point.\n\tconst GUARD_BITS = 64n;\n\treturn Number((r.n << GUARD_BITS) / r.d) / 2 ** 64;\n}\n\n/**\n * Exact addition.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a + b`, normalized.\n */\nexport function rationalAdd(a: Rational, b: Rational): Rational {\n\treturn normalize(a.n * b.d + b.n * a.d, a.d * b.d);\n}\n\n/**\n * Exact subtraction.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a - b`, normalized.\n */\nexport function rationalSub(a: Rational, b: Rational): Rational {\n\treturn normalize(a.n * b.d - b.n * a.d, a.d * b.d);\n}\n\n/**\n * Exact multiplication.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a * b`, normalized.\n */\nexport function rationalMul(a: Rational, b: Rational): Rational {\n\treturn normalize(a.n * b.n, a.d * b.d);\n}\n\n/**\n * Exact division.\n *\n * @param a - Dividend.\n * @param b - Divisor.\n * @returns `a / b`, normalized.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` when `b` is zero.\n */\nexport function rationalDiv(a: Rational, b: Rational): Rational {\n\tif (b.n === 0n) {\n\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Division by zero in a symbolic expression.\");\n\t}\n\treturn normalize(a.n * b.d, a.d * b.n);\n}\n\n/**\n * Exact negation.\n *\n * @param r - The rational to negate.\n * @returns `-r`. Already normalized, since negating cannot change the gcd.\n */\nexport function rationalNeg(r: Rational): Rational {\n\treturn r.n === 0n ? RATIONAL_ZERO : { n: -r.n, d: r.d };\n}\n\n/**\n * Exact integer power, including negative exponents (which invert the base).\n *\n * @param base - The base.\n * @param exponent - Integer exponent, may be negative.\n * @returns `base ** exponent`, normalized.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` for a zero base raised to a\n * negative exponent.\n */\nexport function rationalPow(base: Rational, exponent: bigint): Rational {\n\tif (exponent === 0n) return RATIONAL_ONE;\n\tif (exponent < 0n) {\n\t\tif (base.n === 0n) {\n\t\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Zero raised to a negative power is undefined.\");\n\t\t}\n\t\tconst positive = -exponent;\n\t\treturn normalize(bigintPow(base.d, positive), bigintPow(base.n, positive));\n\t}\n\treturn normalize(bigintPow(base.n, exponent), bigintPow(base.d, exponent));\n}\n\n/**\n * Three-way comparison.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `-1` when `a < b`, `0` when equal, `1` when `a > b`.\n */\nexport function rationalCompare(a: Rational, b: Rational): -1 | 0 | 1 {\n\t// Both denominators are positive by the normalization invariant, so\n\t// cross-multiplying cannot flip the inequality.\n\tconst left = a.n * b.d;\n\tconst right = b.n * a.d;\n\tif (left < right) return -1;\n\tif (left > right) return 1;\n\treturn 0;\n}\n\n/**\n * Whether a rational is exactly zero.\n *\n * The reason this exists rather than a `=== 0` on a double: a pivot that is\n * structurally zero can arrive as `5.551e-17` in floating point, so\n * `vm/MatrixOps.ts` used to treat a singular symbolic matrix as invertible.\n * With exact coefficients the test is decisive.\n *\n * @param r - The rational.\n * @returns True when `r` is zero.\n */\nexport function isRationalZero(r: Rational): boolean {\n\treturn r.n === 0n;\n}\n\n/**\n * Whether a rational is exactly one.\n *\n * @param r - The rational.\n * @returns True when `r` is one.\n */\nexport function isRationalOne(r: Rational): boolean {\n\treturn r.n === 1n && r.d === 1n;\n}\n\n/**\n * Whether a rational is exactly negative one.\n *\n * @param r - The rational.\n * @returns True when `r` is minus one.\n */\nexport function isRationalMinusOne(r: Rational): boolean {\n\treturn r.n === -1n && r.d === 1n;\n}\n\n/**\n * Whether a rational is a whole number.\n *\n * @param r - The rational.\n * @returns True when the denominator is one, which after normalization is the\n * only way a rational can be integral.\n */\nexport function isRationalInteger(r: Rational): boolean {\n\treturn r.d === 1n;\n}\n\n/**\n * Longest exact decimal this module will render in full.\n *\n * Ten digits matches what the previous double-based formatter produced, so\n * display width does not regress.\n */\nconst MAX_DECIMAL_DIGITS = 10;\n\n/**\n * Largest component either side of a fraction may have and still be shown as\n * one.\n *\n * This is what stops an exact conversion from being unreadable. `sqrt(2)`\n * evaluates numerically to `1.4142135623730951`, whose exact rational value is\n * `14142135623730951/10000000000000000`: correct, and useless on screen. A\n * fraction is only clearer than a decimal when its parts are small enough to\n * recognise, so past this bound the rounded decimal wins.\n */\nconst MAX_FRACTION_COMPONENT = 1_000_000n;\n\n/**\n * Renders a rational for display.\n *\n * A whole number prints as digits (`2`). A fraction whose denominator divides\n * a power of ten prints as its exact decimal (`2.5`), since that is how a user\n * wrote it and how they expect to read it back. Anything else prints as\n * `n/d` (`1/3`), which is exact where a decimal would have to lie.\n *\n * @param r - The rational to render.\n * @returns The display string, with a leading minus for negative values.\n */\nexport function formatRational(r: Rational): string {\n\tif (r.d === 1n) return String(r.n);\n\n\t// A fraction terminates in base ten exactly when its denominator's only\n\t// prime factors are 2 and 5. Strip those and see what is left.\n\tlet remaining = r.d;\n\tlet twos = 0;\n\tlet fives = 0;\n\twhile (remaining % 2n === 0n) {\n\t\tremaining /= 2n;\n\t\ttwos++;\n\t}\n\twhile (remaining % 5n === 0n) {\n\t\tremaining /= 5n;\n\t\tfives++;\n\t}\n\n\tconst terminates = remaining === 1n;\n\tconst decimals = Math.max(twos, fives);\n\tif (!terminates || decimals > MAX_DECIMAL_DIGITS) {\n\t\tconst magnitude = r.n < 0n ? -r.n : r.n;\n\t\tif (magnitude <= MAX_FRACTION_COMPONENT && r.d <= MAX_FRACTION_COMPONENT) return `${r.n}/${r.d}`;\n\t\t// Too large to read as a fraction, so fall back to the same rounded\n\t\t// decimal the previous double-based formatter produced.\n\t\treturn String(Math.round(rationalToNumber(r) * 1e10) / 1e10);\n\t}\n\n\tconst scaled = (r.n < 0n ? -r.n : r.n) * bigintPow(10n, BigInt(decimals)) / r.d;\n\tconst digits = String(scaled).padStart(decimals + 1, \"0\");\n\tconst whole = digits.slice(0, digits.length - decimals);\n\tconst fraction = digits.slice(digits.length - decimals).replace(/0+$/, \"\");\n\tconst sign = r.n < 0n ? \"-\" : \"\";\n\treturn fraction.length === 0 ? `${sign}${whole}` : `${sign}${whole}.${fraction}`;\n}\n","/**\n * Exact complex arithmetic over the Gaussian rationals.\n *\n * Both components are {@link Rational}, so this is exact in the same sense the\n * rest of the system is: `(1+2i)/(3-4i)` has an exact answer and gets it,\n * rather than a pair of doubles that are nearly right. That matters most where\n * a complex value has to be recognised as zero, which is how a cubic's\n * *casus irreducibilis* is detected and how a conjugate pair cancels.\n *\n * ## Why the number tower stops here\n *\n * Real values stay {@link Rational} throughout. A complex value only appears\n * when something genuinely produces one: a negative discriminant, a square root\n * of a negative number, or an explicit `i`. That keeps every real-only path\n * paying nothing for complex support, and it keeps `factor` and `solve` working\n * over the rationals by default, which is what a CAS is expected to do.\n *\n * A complex whose imaginary part is zero is collapsed back to a real constant\n * at the boundary, so `(1+i)*(1-i)` reads as `2` rather than `2+0i`.\n */\n\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalZero,\n\tisRationalOne,\n\tformatRational,\n} from \"@solve-js/symbolic/Rational\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * An exact complex number, `re + im * i`, with both parts rational.\n *\n * Construct through {@link complex} rather than as an object literal, so the\n * real-collapse convention below stays consistent.\n */\nexport interface Complex {\n\t/** Real part. */\n\treadonly re: Rational;\n\t/** Imaginary part. Zero means this value is really a real number. */\n\treadonly im: Rational;\n}\n\n/** The complex zero. */\nexport const COMPLEX_ZERO: Complex = { re: RATIONAL_ZERO, im: RATIONAL_ZERO };\n\n/** The complex one. */\nexport const COMPLEX_ONE: Complex = { re: RATIONAL_ONE, im: RATIONAL_ZERO };\n\n/** The imaginary unit. */\nexport const COMPLEX_I: Complex = { re: RATIONAL_ZERO, im: RATIONAL_ONE };\n\n/**\n * Builds a complex number from its two parts.\n *\n * @param re - Real part.\n * @param im - Imaginary part, defaulting to zero.\n * @returns The complex value.\n */\nexport function complex(re: Rational, im: Rational = RATIONAL_ZERO): Complex {\n\treturn { re, im };\n}\n\n/**\n * Whether a complex value is really a real one.\n *\n * @param z - The value to test.\n * @returns True when the imaginary part is exactly zero. Exact, which is the\n * point: in floating point a conjugate pair's imaginary parts cancel to\n * something near zero but rarely to zero, so a real answer would keep an\n * imaginary trace forever.\n */\nexport function isReal(z: Complex): boolean {\n\treturn isRationalZero(z.im);\n}\n\n/**\n * Whether a complex value is exactly zero.\n *\n * @param z - The value to test.\n * @returns True when both parts are zero.\n */\nexport function isComplexZero(z: Complex): boolean {\n\treturn isRationalZero(z.re) && isRationalZero(z.im);\n}\n\n/**\n * Whether a complex value is exactly one.\n *\n * @param z - The value to test.\n * @returns True when it equals one.\n */\nexport function isComplexOne(z: Complex): boolean {\n\treturn isRationalOne(z.re) && isRationalZero(z.im);\n}\n\n/**\n * Exact addition.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a + b`.\n */\nexport function complexAdd(a: Complex, b: Complex): Complex {\n\treturn { re: rationalAdd(a.re, b.re), im: rationalAdd(a.im, b.im) };\n}\n\n/**\n * Exact subtraction.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a - b`.\n */\nexport function complexSub(a: Complex, b: Complex): Complex {\n\treturn { re: rationalSub(a.re, b.re), im: rationalSub(a.im, b.im) };\n}\n\n/**\n * Exact multiplication.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns `a * b`, by the usual `(ac - bd) + (ad + bc)i`.\n */\nexport function complexMul(a: Complex, b: Complex): Complex {\n\treturn {\n\t\tre: rationalSub(rationalMul(a.re, b.re), rationalMul(a.im, b.im)),\n\t\tim: rationalAdd(rationalMul(a.re, b.im), rationalMul(a.im, b.re)),\n\t};\n}\n\n/**\n * Exact division, by multiplying through by the conjugate.\n *\n * @param a - Dividend.\n * @param b - Divisor.\n * @returns `a / b`.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` when `b` is zero.\n */\nexport function complexDiv(a: Complex, b: Complex): Complex {\n\tif (isComplexZero(b)) {\n\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Division by zero in a complex expression.\");\n\t}\n\t// |b|^2, which is real and non-zero, so the two component divisions are exact.\n\tconst denominator = rationalAdd(rationalMul(b.re, b.re), rationalMul(b.im, b.im));\n\treturn {\n\t\tre: rationalDiv(rationalAdd(rationalMul(a.re, b.re), rationalMul(a.im, b.im)), denominator),\n\t\tim: rationalDiv(rationalSub(rationalMul(a.im, b.re), rationalMul(a.re, b.im)), denominator),\n\t};\n}\n\n/**\n * Exact negation.\n *\n * @param z - The value to negate.\n * @returns `-z`.\n */\nexport function complexNeg(z: Complex): Complex {\n\treturn { re: rationalNeg(z.re), im: rationalNeg(z.im) };\n}\n\n/**\n * The complex conjugate.\n *\n * @param z - The value.\n * @returns `z` with the sign of its imaginary part flipped.\n */\nexport function complexConjugate(z: Complex): Complex {\n\treturn { re: z.re, im: rationalNeg(z.im) };\n}\n\n/**\n * The squared modulus, which stays exact where the modulus itself would not.\n *\n * @param z - The value.\n * @returns `re^2 + im^2`, a rational. The modulus is its square root, which is\n * usually irrational, so callers wanting a magnitude should take the root of\n * this rather than expect one here.\n */\nexport function complexNormSquared(z: Complex): Rational {\n\treturn rationalAdd(rationalMul(z.re, z.re), rationalMul(z.im, z.im));\n}\n\n/**\n * Exact integer power, by repeated squaring.\n *\n * @param base - The base.\n * @param exponent - Integer exponent, which may be negative.\n * @returns `base ** exponent`.\n * @throws {EngineError} `SYMBOLIC_DIVISION_BY_ZERO` for a zero base raised to a\n * negative power.\n */\nexport function complexPow(base: Complex, exponent: bigint): Complex {\n\tif (exponent === 0n) return COMPLEX_ONE;\n\tif (exponent < 0n) {\n\t\tif (isComplexZero(base)) {\n\t\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DIVISION_BY_ZERO\", \"Zero raised to a negative power is undefined.\");\n\t\t}\n\t\treturn complexDiv(COMPLEX_ONE, complexPow(base, -exponent));\n\t}\n\tlet result = COMPLEX_ONE;\n\tlet factor = base;\n\tlet remaining = exponent;\n\twhile (remaining > 0n) {\n\t\tif (remaining % 2n === 1n) result = complexMul(result, factor);\n\t\tfactor = complexMul(factor, factor);\n\t\tremaining /= 2n;\n\t}\n\treturn result;\n}\n\n/**\n * Structural equality.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns True when both parts match. Exact, so this is mathematical equality\n * rather than a tolerance comparison.\n */\nexport function complexEquals(a: Complex, b: Complex): boolean {\n\treturn a.re.n === b.re.n && a.re.d === b.re.d && a.im.n === b.im.n && a.im.d === b.im.d;\n}\n\n/**\n * Renders a complex number the way it is written.\n *\n * `3i` rather than `0+3i`, `2-i` rather than `2+-1i`, and a bare real when the\n * imaginary part has vanished.\n *\n * @param z - The value to render.\n * @returns The display string.\n */\nexport function formatComplex(z: Complex): string {\n\tif (isRationalZero(z.im)) return formatRational(z.re);\n\n\tconst magnitude = z.im.n < 0n ? rationalNeg(z.im) : z.im;\n\t// A unit coefficient is written as a bare `i`, the way a person writes it.\n\tconst imaginary = isRationalOne(magnitude) ? \"i\" : `${formatRational(magnitude)}i`;\n\n\tif (isRationalZero(z.re)) return z.im.n < 0n ? `-${imaginary}` : imaginary;\n\treturn z.im.n < 0n ? `${formatRational(z.re)}-${imaginary}` : `${formatRational(z.re)}+${imaginary}`;\n}\n\n/**\n * The exact square roots of a complex number, when both are Gaussian rational.\n *\n * A square root is only exact here when the result stays in the Gaussian\n * rationals, which needs `|z|` and then the two components each to be rational\n * squares. `sqrt(-4)` is exactly `2i`; `sqrt(i)` is not rational and comes back\n * `null` so the caller can leave it symbolic rather than approximate it.\n *\n * @param z - The value to take the root of.\n * @returns The principal root, or `null` when it is not a Gaussian rational.\n */\nexport function exactComplexSqrt(z: Complex): Complex | null {\n\tif (isComplexZero(z)) return COMPLEX_ZERO;\n\n\t// |z| must be rational for either component to be.\n\tconst modulus = exactRationalSqrt(complexNormSquared(z));\n\tif (modulus === null) return null;\n\n\t// The standard half-angle construction: re' = sqrt((|z| + re)/2).\n\tconst two: Rational = { n: 2n, d: 1n };\n\tconst realPart = exactRationalSqrt(rationalDiv(rationalAdd(modulus, z.re), two));\n\tif (realPart === null) return null;\n\n\tif (isRationalZero(realPart)) {\n\t\t// z is a negative real, so the root is purely imaginary.\n\t\tconst imaginaryPart = exactRationalSqrt(rationalDiv(rationalSub(modulus, z.re), two));\n\t\treturn imaginaryPart === null ? null : { re: RATIONAL_ZERO, im: imaginaryPart };\n\t}\n\n\tconst imaginaryPart = rationalDiv(z.im, rationalMul(two, realPart));\n\treturn { re: realPart, im: imaginaryPart };\n}\n\n/** Exact square root of a non-negative rational, or `null` when it is irrational. */\nfunction exactRationalSqrt(value: Rational): Rational | null {\n\tif (value.n < 0n) return null;\n\tconst numerator = exactBigintSqrt(value.n);\n\tconst denominator = exactBigintSqrt(value.d);\n\treturn numerator === null || denominator === null ? null : { n: numerator, d: denominator };\n}\n\n/** Exact integer square root, or `null` when `value` is not a perfect square. */\nfunction exactBigintSqrt(value: bigint): bigint | null {\n\tif (value < 0n) return null;\n\tif (value < 2n) return value;\n\tlet previous = value;\n\tlet current = (value + 1n) / 2n;\n\twhile (current < previous) {\n\t\tprevious = current;\n\t\tcurrent = (previous + value / previous) / 2n;\n\t}\n\treturn previous * previous === value ? previous : null;\n}\n","/**\n * The symbolic expression tree: an algebraic formula over free variables,\n * rather than a concrete number.\n *\n * This is the data type the whole symbolic algebra system manipulates. It is\n * deliberately a plain discriminated union of immutable object literals, not a\n * class hierarchy, so a node can cross the worker boundary by structured clone\n * (see `diagnostics/events.ts`, which carries these in its VM trace payload)\n * and so pattern matching in the simplifier stays exhaustive under the\n * compiler's own checking.\n *\n * Two variants exist here that the original bounded simplifier did not have,\n * and they are what unlocks the rest of the system:\n *\n * - `pow` gives exponentiation a representation. Without it `x^2` had nowhere\n * to go, and `OpCode.EXP` fell through to `Math.pow(0, 2)` because\n * `Value.toNumber()` reports `0` for a symbolic operand, so `x^2 + 3x + 2`\n * silently evaluated to `3x+2`. Polynomials, derivatives and roots all need it.\n * - `call` gives function application a representation, so `sqrt(x)` and\n * `sin(x)` carry through a symbolic expression instead of collapsing to\n * `sqrt(0)`.\n *\n * Coefficients are exact rationals, never doubles. See `Rational.ts` for why.\n */\n\nimport type { Rational } from \"@solve-js/symbolic/Rational\";\nimport { rationalFromNumber } from \"@solve-js/symbolic/Rational\";\nimport type { Complex } from \"@solve-js/symbolic/Complex\";\nimport { complexEquals } from \"@solve-js/symbolic/Complex\";\n\n/**\n * A symbolic (algebraic) expression tree.\n *\n * Build nodes through the constructor functions in this module rather than as\n * object literals, so constants normalize consistently.\n */\nexport type SymbolicNode =\n\t| { kind: \"const\"; value: Rational }\n\t| { kind: \"complex\"; value: Complex }\n\t| { kind: \"var\"; name: string }\n\t| { kind: \"add\"; left: SymbolicNode; right: SymbolicNode }\n\t| { kind: \"sub\"; left: SymbolicNode; right: SymbolicNode }\n\t| { kind: \"mul\"; left: SymbolicNode; right: SymbolicNode }\n\t| { kind: \"div\"; left: SymbolicNode; right: SymbolicNode }\n\t| { kind: \"neg\"; operand: SymbolicNode }\n\t| { kind: \"pow\"; base: SymbolicNode; exponent: SymbolicNode }\n\t| { kind: \"call\"; name: string; args: readonly SymbolicNode[] };\n\n/**\n * Ceiling on the size of a tree the simplifier will accept.\n *\n * Simplification itself never grows a tree (see `Simplify.ts`'s stated\n * invariant), but a tree can arrive already large from repeated symbolic\n * matrix elimination, and every rule walks it. Ten thousand nodes is orders of\n * magnitude beyond any hand-written expression while still bounding a single\n * simplify to milliseconds.\n */\nexport const SYMBOLIC_MAX_NODES = 10_000;\n\n/**\n * A literal number in a symbolic expression.\n *\n * Accepts a plain `number` as well as a {@link Rational} so that the many\n * existing call sites reading a numeric Value can pass it straight through;\n * the number is converted by its decimal form, so `constNode(0.1)` is exactly\n * one tenth.\n *\n * @param value - The number, as a double or an exact rational.\n * @returns A constant node the simplifier can fold.\n */\nexport function constNode(value: number | Rational): SymbolicNode {\n\treturn { kind: \"const\", value: typeof value === \"number\" ? rationalFromNumber(value) : value };\n}\n\n/**\n * An unresolved name in a symbolic expression.\n *\n * @param name - The variable name.\n * @returns A variable node, which the simplifier carries through rather than\n * evaluating.\n */\nexport function varNode(name: string): SymbolicNode {\n\treturn { kind: \"var\", name };\n}\n\n/**\n * An exponentiation in a symbolic expression.\n *\n * @param base - The base expression.\n * @param exponent - The exponent expression, which does not have to be constant.\n * @returns A power node.\n */\nexport function powNode(base: SymbolicNode, exponent: SymbolicNode): SymbolicNode {\n\treturn { kind: \"pow\", base, exponent };\n}\n\n/**\n * A function application in a symbolic expression.\n *\n * @param name - The function name, matching the builtin naming in\n * `vm/SymbolicOps.ts`'s own index table so the two surfaces agree.\n * @param args - The argument expressions.\n * @returns A call node.\n */\nexport function callNode(name: string, args: readonly SymbolicNode[]): SymbolicNode {\n\treturn { kind: \"call\", name, args };\n}\n\n/**\n * A stable structural key for a tree.\n *\n * Two trees produce the same key exactly when they are structurally identical,\n * so this serves both as the equality test and as a `Map` key for memoizing\n * simplification. Prefix form (`\"+(*(2,x),6)\"`) rather than a hash, because a\n * hash would need collision handling to be sound and these strings stay short\n * for the expressions that actually occur.\n *\n * @param node - The tree to key.\n * @returns The structural key.\n */\nexport function symbolicKey(node: SymbolicNode): string {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\t\treturn `${node.value.n}/${node.value.d}`;\n\t\tcase \"complex\":\n\t\t\treturn `C(${node.value.re.n}/${node.value.re.d},${node.value.im.n}/${node.value.im.d})`;\n\t\tcase \"var\":\n\t\t\treturn `v:${node.name}`;\n\t\tcase \"neg\":\n\t\t\treturn `-(${symbolicKey(node.operand)})`;\n\t\tcase \"pow\":\n\t\t\treturn `^(${symbolicKey(node.base)},${symbolicKey(node.exponent)})`;\n\t\tcase \"call\":\n\t\t\treturn `${node.name}(${node.args.map(symbolicKey).join(\",\")})`;\n\t\tcase \"add\":\n\t\t\treturn `+(${symbolicKey(node.left)},${symbolicKey(node.right)})`;\n\t\tcase \"sub\":\n\t\t\treturn `-(${symbolicKey(node.left)},${symbolicKey(node.right)})`;\n\t\tcase \"mul\":\n\t\t\treturn `*(${symbolicKey(node.left)},${symbolicKey(node.right)})`;\n\t\tcase \"div\":\n\t\t\treturn `/(${symbolicKey(node.left)},${symbolicKey(node.right)})`;\n\t}\n}\n\n/**\n * Structural equality between two trees.\n *\n * @param a - Left tree.\n * @param b - Right tree.\n * @returns True when the two are structurally identical. Note this is\n * structural, not mathematical: `x+1` and `1+x` are different trees.\n */\nexport function nodesEqual(a: SymbolicNode, b: SymbolicNode): boolean {\n\tif (a.kind !== b.kind) return false;\n\tswitch (a.kind) {\n\t\tcase \"const\": {\n\t\t\tconst other = b as typeof a;\n\t\t\treturn a.value.n === other.value.n && a.value.d === other.value.d;\n\t\t}\n\t\tcase \"complex\":\n\t\t\treturn complexEquals(a.value, (b as typeof a).value);\n\t\tcase \"var\":\n\t\t\treturn a.name === (b as typeof a).name;\n\t\tcase \"neg\":\n\t\t\treturn nodesEqual(a.operand, (b as typeof a).operand);\n\t\tcase \"pow\": {\n\t\t\tconst other = b as typeof a;\n\t\t\treturn nodesEqual(a.base, other.base) && nodesEqual(a.exponent, other.exponent);\n\t\t}\n\t\tcase \"call\": {\n\t\t\tconst other = b as typeof a;\n\t\t\tif (a.name !== other.name || a.args.length !== other.args.length) return false;\n\t\t\treturn a.args.every((arg, i) => nodesEqual(arg, other.args[i]));\n\t\t}\n\t\tcase \"add\":\n\t\tcase \"sub\":\n\t\tcase \"mul\":\n\t\tcase \"div\": {\n\t\t\tconst other = b as typeof a;\n\t\t\treturn nodesEqual(a.left, other.left) && nodesEqual(a.right, other.right);\n\t\t}\n\t}\n}\n\n/**\n * Counts the nodes in a tree.\n *\n * Used by the simplifier's own limit check, and by the property test enforcing\n * that no simplification rule ever grows a tree.\n *\n * @param node - The tree to measure.\n * @returns The total node count, including `node` itself.\n */\nexport function nodeCount(node: SymbolicNode, limit = Number.POSITIVE_INFINITY): number {\n\t// Iterative rather than recursive, and deliberately so. A deeply nested tree\n\t// (a long `a+b+c+...` chain builds one nested `add` per term) would overflow\n\t// the native call stack before a recursive walk could finish, which made the\n\t// SYMBOLIC_NODE_LIMIT_EXCEEDED guard unreachable in exactly the case it\n\t// exists for: the caller crashed instead of being told the tree was too big.\n\t//\n\t// `limit` lets the walk stop as soon as the answer can no longer matter,\n\t// so the size guard costs O(limit) rather than O(tree).\n\tconst pending: SymbolicNode[] = [node];\n\tlet total = 0;\n\twhile (pending.length > 0) {\n\t\tconst current = pending.pop()!;\n\t\ttotal++;\n\t\tif (total > limit) return total;\n\t\tswitch (current.kind) {\n\t\t\tcase \"const\":\n\t\t\tcase \"complex\":\n\t\t\tcase \"var\":\n\t\t\t\tbreak;\n\t\t\tcase \"neg\":\n\t\t\t\tpending.push(current.operand);\n\t\t\t\tbreak;\n\t\t\tcase \"pow\":\n\t\t\t\tpending.push(current.base, current.exponent);\n\t\t\t\tbreak;\n\t\t\tcase \"call\":\n\t\t\t\tfor (const arg of current.args) pending.push(arg);\n\t\t\t\tbreak;\n\t\t\tcase \"add\":\n\t\t\tcase \"sub\":\n\t\t\tcase \"mul\":\n\t\t\tcase \"div\":\n\t\t\t\tpending.push(current.left, current.right);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn total;\n}\n\n/**\n * Every variable name appearing anywhere in a tree.\n *\n * @param node - The tree to scan.\n * @returns The set of free variable names. Iteration order is first\n * appearance, which callers needing determinism should sort rather than rely on.\n */\nexport function freeVariables(node: SymbolicNode): ReadonlySet<string> {\n\tconst names = new Set<string>();\n\tcollectVariables(node, names);\n\treturn names;\n}\n\n/** Recursive worker for {@link freeVariables}, kept separate so the public entry point allocates one set rather than one per level. */\nfunction collectVariables(node: SymbolicNode, into: Set<string>): void {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\tcase \"complex\":\n\t\t\treturn;\n\t\tcase \"var\":\n\t\t\tinto.add(node.name);\n\t\t\treturn;\n\t\tcase \"neg\":\n\t\t\tcollectVariables(node.operand, into);\n\t\t\treturn;\n\t\tcase \"pow\":\n\t\t\tcollectVariables(node.base, into);\n\t\t\tcollectVariables(node.exponent, into);\n\t\t\treturn;\n\t\tcase \"call\":\n\t\t\tfor (const arg of node.args) collectVariables(arg, into);\n\t\t\treturn;\n\t\tcase \"add\":\n\t\tcase \"sub\":\n\t\tcase \"mul\":\n\t\tcase \"div\":\n\t\t\tcollectVariables(node.left, into);\n\t\t\tcollectVariables(node.right, into);\n\t}\n}\n\n/**\n * Replaces every occurrence of a variable with an expression.\n *\n * @param node - The tree to rewrite.\n * @param variable - The variable name to replace.\n * @param replacement - What to put in its place.\n * @returns A new tree. The input is not modified.\n */\nexport function substitute(node: SymbolicNode, variable: string, replacement: SymbolicNode): SymbolicNode {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\tcase \"complex\":\n\t\t\treturn node;\n\t\tcase \"var\":\n\t\t\treturn node.name === variable ? replacement : node;\n\t\tcase \"neg\":\n\t\t\treturn { kind: \"neg\", operand: substitute(node.operand, variable, replacement) };\n\t\tcase \"pow\":\n\t\t\treturn {\n\t\t\t\tkind: \"pow\",\n\t\t\t\tbase: substitute(node.base, variable, replacement),\n\t\t\t\texponent: substitute(node.exponent, variable, replacement),\n\t\t\t};\n\t\tcase \"call\":\n\t\t\treturn { kind: \"call\", name: node.name, args: node.args.map(arg => substitute(arg, variable, replacement)) };\n\t\tcase \"add\":\n\t\tcase \"sub\":\n\t\tcase \"mul\":\n\t\tcase \"div\":\n\t\t\treturn {\n\t\t\t\tkind: node.kind,\n\t\t\t\tleft: substitute(node.left, variable, replacement),\n\t\t\t\tright: substitute(node.right, variable, replacement),\n\t\t\t};\n\t}\n}\n\n/**\n * A complex literal in a symbolic expression.\n *\n * Collapses to an ordinary real constant when the imaginary part is zero, so\n * `(1+i)*(1-i)` reads as `2` rather than `2+0i`. That collapse is why callers\n * should build complex values through here rather than as an object literal.\n *\n * @param value - The exact complex value.\n * @returns A complex node, or a `const` node when the value is really real.\n */\nexport function complexNode(value: Complex): SymbolicNode {\n\tif (value.im.n === 0n) return { kind: \"const\", value: value.re };\n\treturn { kind: \"complex\", value };\n}\n","/**\n * A canonical sparse multivariate polynomial over the rationals, and the\n * conversion both ways between it and a {@link SymbolicNode} tree.\n *\n * The tree is the right representation for arbitrary expressions but the wrong\n * one for algebra: `2*b + 3*b` and `5*b` are different trees for the same\n * value, so deciding they are equal means pattern matching on shape. A\n * polynomial keyed by monomial gives one canonical form per value, which is\n * what makes expansion, term collection through a product, factoring and root\n * finding possible at all.\n *\n * ## Not every expression is a polynomial, and that is the point\n *\n * {@link toPolynomial} returns `null` rather than guessing whenever the input\n * falls outside the representation: a non-constant denominator, a non-integer\n * or symbolic exponent, or any function call. **Bias every ambiguous case\n * toward `null`.** A wrong polynomial is far worse than no polynomial, because\n * the caller silently gets an answer for a different expression.\n *\n * That null return is also load-bearing for existing behaviour. `vx/sx-tx` is a\n * rational function, not a polynomial, so it converts to `null` and keeps the\n * tree simplifier's own handling, which is what preserves the shipped symbolic\n * matrix inverse output.\n *\n * Nothing here is reachable from `simplifySymbolic`'s `mul` or `div` cases, and\n * `expandSymbolic` is never called by the simplifier at all. See `Simplify.ts`\n * for the invariant.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalZero,\n\tisRationalOne,\n\tRATIONAL_MINUS_ONE,\n\tisRationalInteger,\n} from \"@solve-js/symbolic/Rational\";\n\n/**\n * The canonical text form of one monomial.\n *\n * Variables appear in sorted order joined by `*`, an exponent of one is\n * written bare, and the constant term is the empty string. `\"x^2*y\"` is the\n * key for `x squared times y`. Sorting is what makes the key canonical, so\n * `y*x^2` and `x^2*y` cannot produce two different entries for one term.\n */\nexport type MonomialKey = string;\n\n/**\n * A polynomial as a sum of monomial terms with rational coefficients.\n *\n * Build one with {@link toPolynomial} rather than by hand, so the invariants\n * hold: no term ever carries a zero coefficient, and {@link Polynomial.vars} is\n * sorted.\n */\nexport interface Polynomial {\n\t/** Non-zero terms only. A zero polynomial has an empty map. */\n\treadonly terms: ReadonlyMap<MonomialKey, Rational>;\n\t/** Every variable appearing in any term, sorted, so output order is deterministic. */\n\treadonly vars: readonly string[];\n}\n\n/**\n * Largest exponent {@link toPolynomial} will multiply out.\n *\n * `(x+y)^n` has `n+1` terms in one variable but grows combinatorially in\n * several, so this bounds the work before it starts rather than after.\n */\nexport const EXPAND_MAX_POW_EXPONENT = 32;\n\n/**\n * Largest number of distinct terms a polynomial may carry.\n *\n * Multiplying two dense multivariate polynomials multiplies their term counts,\n * so this is the ceiling that stops a product chain from exhausting memory.\n */\nexport const POLYNOMIAL_MAX_TERMS = 2_000;\n\n/**\n * Largest total degree any single term may reach.\n *\n * Degree grows additively under multiplication and multiplicatively under\n * exponentiation, so an unbounded chain of either escapes quickly.\n */\nexport const POLYNOMIAL_MAX_DEGREE = 64;\n\n/** A monomial as a variable-to-exponent map. Exponents are always positive integers; a variable with exponent zero is removed. */\nexport type Monomial = Map<string, number>;\n\n/**\n * Serializes a monomial to its canonical {@link MonomialKey}.\n *\n * @param monomial - The exponent map.\n * @returns The key, with variables in sorted order and an exponent of one left\n * implicit, so `{x: 2, y: 1}` becomes `\"x^2*y\"`.\n */\nexport function monomialToKey(monomial: Monomial): MonomialKey {\n\tconst names = [...monomial.keys()].sort();\n\treturn names.map(name => (monomial.get(name) === 1 ? name : `${name}^${monomial.get(name)}`)).join(\"*\");\n}\n\n/**\n * Parses a canonical {@link MonomialKey} back into a variable-to-exponent map.\n *\n * @param key - The key to parse. The empty key is the constant monomial.\n * @returns The exponent map.\n */\nexport function monomialFromKey(key: MonomialKey): Monomial {\n\tconst monomial: Monomial = new Map();\n\tif (key === \"\") return monomial;\n\tfor (const factor of key.split(\"*\")) {\n\t\tconst caret = factor.indexOf(\"^\");\n\t\tif (caret === -1) monomial.set(factor, 1);\n\t\telse monomial.set(factor.slice(0, caret), Number(factor.slice(caret + 1)));\n\t}\n\treturn monomial;\n}\n\n/** Total degree of a monomial, the sum of its exponents. */\nfunction monomialDegree(key: MonomialKey): number {\n\tlet total = 0;\n\tfor (const exponent of monomialFromKey(key).values()) total += exponent;\n\treturn total;\n}\n\n/** Assembles a Polynomial from a term map, dropping zero coefficients and deriving the sorted variable list. */\nfunction build(terms: Map<MonomialKey, Rational>): Polynomial | null {\n\tconst kept = new Map<MonomialKey, Rational>();\n\tconst names = new Set<string>();\n\tfor (const [key, coeff] of terms) {\n\t\tif (isRationalZero(coeff)) continue;\n\t\tif (monomialDegree(key) > POLYNOMIAL_MAX_DEGREE) return null;\n\t\tkept.set(key, coeff);\n\t\tfor (const name of monomialFromKey(key).keys()) names.add(name);\n\t}\n\tif (kept.size > POLYNOMIAL_MAX_TERMS) return null;\n\treturn { terms: kept, vars: [...names].sort() };\n}\n\n/** The polynomial equal to a single rational constant. */\nfunction constantPolynomial(value: Rational): Polynomial {\n\treturn isRationalZero(value)\n\t\t? { terms: new Map(), vars: [] }\n\t\t: { terms: new Map([[\"\", value]]), vars: [] };\n}\n\n/**\n * Adds two polynomials.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns The sum, or `null` when a safety limit would be exceeded.\n */\nexport function polyAdd(a: Polynomial, b: Polynomial): Polynomial | null {\n\tconst terms = new Map(a.terms);\n\tfor (const [key, coeff] of b.terms) {\n\t\tconst existing = terms.get(key);\n\t\tterms.set(key, existing === undefined ? coeff : rationalAdd(existing, coeff));\n\t}\n\treturn build(terms);\n}\n\n/**\n * Subtracts one polynomial from another.\n *\n * @param a - Minuend.\n * @param b - Subtrahend.\n * @returns The difference, or `null` when a safety limit would be exceeded.\n */\nexport function polySub(a: Polynomial, b: Polynomial): Polynomial | null {\n\treturn polyAdd(a, polyScale(b, RATIONAL_MINUS_ONE));\n}\n\n/**\n * Multiplies two polynomials, distributing every term pair.\n *\n * @param a - Left operand.\n * @param b - Right operand.\n * @returns The product, or `null` when a safety limit would be exceeded.\n */\nexport function polyMul(a: Polynomial, b: Polynomial): Polynomial | null {\n\t// The term count of a product is bounded by the product of the term counts,\n\t// so check before doing the work rather than after allocating it.\n\tif (a.terms.size * b.terms.size > POLYNOMIAL_MAX_TERMS) return null;\n\n\tconst terms = new Map<MonomialKey, Rational>();\n\tfor (const [leftKey, leftCoeff] of a.terms) {\n\t\tconst leftMonomial = monomialFromKey(leftKey);\n\t\tfor (const [rightKey, rightCoeff] of b.terms) {\n\t\t\tconst combined: Monomial = new Map(leftMonomial);\n\t\t\tfor (const [name, exponent] of monomialFromKey(rightKey)) {\n\t\t\t\tcombined.set(name, (combined.get(name) ?? 0) + exponent);\n\t\t\t}\n\t\t\tconst key = monomialToKey(combined);\n\t\t\tconst coeff = rationalMul(leftCoeff, rightCoeff);\n\t\t\tconst existing = terms.get(key);\n\t\t\tterms.set(key, existing === undefined ? coeff : rationalAdd(existing, coeff));\n\t\t}\n\t}\n\treturn build(terms);\n}\n\n/**\n * Raises a polynomial to a non-negative integer power by repeated multiplication.\n *\n * @param p - The base polynomial.\n * @param exponent - A non-negative integer exponent.\n * @returns The power, or `null` for a negative exponent, one past\n * {@link EXPAND_MAX_POW_EXPONENT}, or a safety-limit breach.\n */\nexport function polyPow(p: Polynomial, exponent: number): Polynomial | null {\n\tif (exponent < 0 || !Number.isInteger(exponent) || exponent > EXPAND_MAX_POW_EXPONENT) return null;\n\tlet result = constantPolynomial(RATIONAL_ONE);\n\tfor (let i = 0; i < exponent; i++) {\n\t\tconst next = polyMul(result, p);\n\t\tif (next === null) return null;\n\t\tresult = next;\n\t}\n\treturn result;\n}\n\n/**\n * Multiplies every coefficient by a rational.\n *\n * @param p - The polynomial.\n * @param k - The scale factor. Scaling by zero yields the zero polynomial.\n * @returns The scaled polynomial.\n */\nexport function polyScale(p: Polynomial, k: Rational): Polynomial {\n\tif (isRationalZero(k)) return { terms: new Map(), vars: [] };\n\tconst terms = new Map<MonomialKey, Rational>();\n\tfor (const [key, coeff] of p.terms) terms.set(key, rationalMul(coeff, k));\n\treturn { terms, vars: p.vars };\n}\n\n/**\n * The degree of a polynomial.\n *\n * @param p - The polynomial.\n * @param variable - When given, the highest exponent of that variable alone.\n * Otherwise the highest total degree across all terms.\n * @returns The degree. A zero polynomial has degree zero.\n */\nexport function polyDegree(p: Polynomial, variable?: string): number {\n\tlet highest = 0;\n\tfor (const key of p.terms.keys()) {\n\t\tconst degree = variable === undefined ? monomialDegree(key) : (monomialFromKey(key).get(variable) ?? 0);\n\t\tif (degree > highest) highest = degree;\n\t}\n\treturn highest;\n}\n\n/**\n * The single variable of a univariate polynomial.\n *\n * @param p - The polynomial.\n * @returns That variable's name, or `null` when the polynomial is constant or\n * involves more than one variable.\n */\nexport function polyUnivariateVar(p: Polynomial): string | null {\n\treturn p.vars.length === 1 ? p.vars[0] : null;\n}\n\n/**\n * Dense ascending coefficients of a univariate polynomial.\n *\n * @param p - The polynomial, which must involve no variable other than `variable`.\n * @param variable - The variable to read powers of.\n * @returns `[c0, c1, ..., cn]` where index `i` is the coefficient of\n * `variable^i`, with explicit zeros for absent powers.\n */\nexport function polyCoefficients(p: Polynomial, variable: string): Rational[] {\n\tconst degree = polyDegree(p, variable);\n\tconst coefficients: Rational[] = new Array(degree + 1).fill(RATIONAL_ZERO);\n\tfor (const [key, coeff] of p.terms) {\n\t\tcoefficients[monomialFromKey(key).get(variable) ?? 0] = coeff;\n\t}\n\treturn coefficients;\n}\n\n/**\n * Converts an expression tree into canonical polynomial form.\n *\n * @param node - The tree to convert. It should already be simplified, though\n * this does not require it.\n * @returns The polynomial, or `null` when `node` is not a polynomial over the\n * rationals: a non-constant denominator, a non-integer or symbolic exponent,\n * any function call, or a safety-limit breach.\n */\nexport function toPolynomial(node: SymbolicNode, allowDistribution = true): Polynomial | null {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\t\treturn constantPolynomial(node.value);\n\t\tcase \"var\":\n\t\t\treturn { terms: new Map([[node.name, RATIONAL_ONE]]), vars: [node.name] };\n\t\tcase \"neg\": {\n\t\t\tconst operand = toPolynomial(node.operand, allowDistribution);\n\t\t\treturn operand === null ? null : polyScale(operand, RATIONAL_MINUS_ONE);\n\t\t}\n\t\tcase \"add\": {\n\t\t\tconst left = toPolynomial(node.left, allowDistribution);\n\t\t\tconst right = left === null ? null : toPolynomial(node.right, allowDistribution);\n\t\t\treturn left === null || right === null ? null : polyAdd(left, right);\n\t\t}\n\t\tcase \"sub\": {\n\t\t\tconst left = toPolynomial(node.left, allowDistribution);\n\t\t\tconst right = left === null ? null : toPolynomial(node.right, allowDistribution);\n\t\t\treturn left === null || right === null ? null : polySub(left, right);\n\t\t}\n\t\tcase \"mul\": {\n\t\t\tconst left = toPolynomial(node.left, allowDistribution);\n\t\t\tconst right = left === null ? null : toPolynomial(node.right, allowDistribution);\n\t\t\tif (left === null || right === null) return null;\n\t\t\t// Multiplying into a multi-term sum is expansion, and the simplifier\n\t\t\t// is not allowed to do that (see `Simplify.ts`), so it converts with\n\t\t\t// distribution disabled and gets `null` here, leaving `(x+1)*(x+2)`\n\t\t\t// as the user wrote it.\n\t\t\t//\n\t\t\t// Refusing only when BOTH sides are sums is not enough. Distributing\n\t\t\t// a single factor over `(x-4)` copies that factor into both terms,\n\t\t\t// and distributing a bare constant over a three-term sum grows the\n\t\t\t// tree as well. So in this mode a product converts only when both\n\t\t\t// sides are single terms, which is exactly what collecting `2b + 3b`\n\t\t\t// into `5b` needs and nothing beyond it.\n\t\t\tif (!allowDistribution && (left.terms.size > 1 || right.terms.size > 1)) return null;\n\t\t\treturn polyMul(left, right);\n\t\t}\n\t\tcase \"div\": {\n\t\t\t// Only a genuinely constant, non-zero denominator is divisible here.\n\t\t\t// Anything else is a rational function, which this representation\n\t\t\t// cannot express, so it must come back null rather than be approximated.\n\t\t\tconst right = toPolynomial(node.right, allowDistribution);\n\t\t\tif (right === null || right.vars.length > 0) return null;\n\t\t\tconst divisor = right.terms.get(\"\") ?? RATIONAL_ZERO;\n\t\t\tif (isRationalZero(divisor)) return null;\n\t\t\tconst left = toPolynomial(node.left, allowDistribution);\n\t\t\treturn left === null ? null : polyScale(left, rationalDiv(RATIONAL_ONE, divisor));\n\t\t}\n\t\tcase \"pow\": {\n\t\t\tif (node.exponent.kind !== \"const\" || !isRationalInteger(node.exponent.value)) return null;\n\t\t\tconst exponent = Number(node.exponent.value.n);\n\t\t\tconst base = toPolynomial(node.base, allowDistribution);\n\t\t\tif (base === null) return null;\n\t\t\t// Raising a sum to a power is expansion too, for the same reason.\n\t\t\tif (!allowDistribution && base.terms.size > 1) return null;\n\t\t\treturn polyPow(base, exponent);\n\t\t}\n\t\tcase \"complex\":\n\t\t\t// Coefficients here are rational by construction, so a complex literal\n\t\t\t// puts the expression outside this representation. Returning null is what\n\t\t\t// keeps factor and solve working over the rationals by default.\n\t\t\treturn null;\n\t\tcase \"call\":\n\t\t\t// A function of an unknown is never a polynomial in it.\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Orders two monomials for display, highest first, by graded lexicographic\n * order: total degree, then the exponent of each variable in turn.\n *\n * This is what makes `(x+y)^2` read as `x^2+2x*y+y^2` rather than\n * `2x*y+x^2+y^2`. Sorting the key strings instead would order by character\n * code, where `*` (42) sorts before `^` (94), putting the cross term first.\n * Comparing exponent vectors is both conventional and independent of how a key\n * happens to be spelled.\n *\n * @param a - The first monomial key.\n * @param b - The second.\n * @param vars - The variable names, in sorted order, which fixes the tie-break.\n * @returns Negative when `a` sorts first, positive when `b` does, zero when\n * they are the same monomial.\n */\nexport function compareMonomials(a: MonomialKey, b: MonomialKey, vars: readonly string[]): number {\n\tconst degreeDifference = monomialDegree(b) - monomialDegree(a);\n\tif (degreeDifference !== 0) return degreeDifference;\n\n\tconst left = monomialFromKey(a);\n\tconst right = monomialFromKey(b);\n\tfor (const name of vars) {\n\t\tconst difference = (right.get(name) ?? 0) - (left.get(name) ?? 0);\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn 0;\n}\n\n/** Builds the node for one monomial, `x^2*y`, as a left-leaning product of powers. */\nfunction monomialToNode(key: MonomialKey): SymbolicNode {\n\tconst monomial = monomialFromKey(key);\n\tconst names = [...monomial.keys()].sort();\n\tlet result: SymbolicNode | null = null;\n\tfor (const name of names) {\n\t\tconst exponent = monomial.get(name)!;\n\t\tconst factor = exponent === 1 ? varNode(name) : powNode(varNode(name), constNode({ n: BigInt(exponent), d: 1n }));\n\t\tresult = result === null ? factor : { kind: \"mul\", left: result, right: factor };\n\t}\n\treturn result ?? constNode(RATIONAL_ONE);\n}\n\n/** Builds the node for one term, folding the coefficient in and wrapping a negative one in `neg` so the formatter renders `x-3` rather than `x+-3`. */\nfunction termToNode(key: MonomialKey, coeff: Rational): SymbolicNode {\n\tif (key === \"\") return constNode(coeff);\n\n\tconst magnitude = coeff.n < 0n ? rationalNeg(coeff) : coeff;\n\tconst monomial = monomialToNode(key);\n\tconst positive = isRationalOne(magnitude)\n\t\t? monomial\n\t\t: { kind: \"mul\" as const, left: constNode(magnitude), right: monomial };\n\treturn coeff.n < 0n ? { kind: \"neg\", operand: positive } : positive;\n}\n\n/**\n * Converts a polynomial back into an expression tree.\n *\n * Terms come out in descending total degree, then lexicographically by\n * monomial key, so `x^2+3x+2` reads the way it is conventionally written and\n * two equal polynomials always render identically.\n *\n * @param p - The polynomial to render.\n * @returns The tree. A zero polynomial becomes the constant `0`.\n */\nexport function fromPolynomial(p: Polynomial): SymbolicNode {\n\tconst keys = [...p.terms.keys()].sort((a, b) => compareMonomials(a, b, p.vars));\n\tif (keys.length === 0) return constNode(RATIONAL_ZERO);\n\n\t// Lead with a positive term when the polynomial has one, so `5 - y` comes\n\t// back as `5-y` rather than `-y+5`. Two reasons, and the second is the one\n\t// that matters. It reads the way a person writes it. And it keeps the tree\n\t// from growing: a leading negative needs a `neg` wrapper where the original\n\t// had a `sub`, which broke `Simplify.ts`'s promise never to grow a tree, by\n\t// one node for every additive level. The rule is deterministic and depends\n\t// only on the polynomial, so two equal polynomials still render identically.\n\tif (p.terms.get(keys[0])!.n < 0n) {\n\t\tconst firstPositive = keys.findIndex(key => p.terms.get(key)!.n > 0n);\n\t\tif (firstPositive > 0) keys.unshift(...keys.splice(firstPositive, 1));\n\t}\n\n\tlet result = termToNode(keys[0], p.terms.get(keys[0])!);\n\tfor (let i = 1; i < keys.length; i++) {\n\t\tconst coeff = p.terms.get(keys[i])!;\n\t\t// A negative term becomes a subtraction rather than an addition of a\n\t\t// negation. That is one node smaller, which matters: `Simplify.ts`\n\t\t// promises never to grow a tree, and routing `x - y` through here as\n\t\t// `x + (-y)` broke exactly that promise by a node every time.\n\t\tif (coeff.n < 0n) {\n\t\t\tresult = { kind: \"sub\", left: result, right: termToNode(keys[i], rationalNeg(coeff)) };\n\t\t} else {\n\t\t\tresult = { kind: \"add\", left: result, right: termToNode(keys[i], coeff) };\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * Multiplies out every product and power in an expression.\n *\n * Never called from `simplifySymbolic`, which is forbidden from growing a\n * tree. This is the explicitly-invoked counterpart.\n *\n * @param node - The expression to expand.\n * @returns The expanded expression, or `node` unchanged when it is not a\n * polynomial. `expand(sin(x))` is `sin(x)` rather than an error, since there is\n * nothing to expand but nothing wrong either.\n */\nexport function expandSymbolic(node: SymbolicNode): SymbolicNode {\n\tconst polynomial = toPolynomial(node);\n\treturn polynomial === null ? node : fromPolynomial(polynomial);\n}\n","/**\n * Polynomial division and greatest common divisors over the rationals.\n *\n * This is the piece the rest of the rational-function machinery stands on.\n * Cancelling `(x^2-1)/(x-1)` to `x+1`, splitting a fraction into partial\n * fractions, and integrating a rational function all reduce to \"divide these\n * two polynomials and find what they share\".\n *\n * Everything here is univariate. Multivariate GCD is a genuinely harder problem\n * (the usual approaches are modular or use Kronecker substitution), and the\n * univariate case covers what cancellation, partial fractions and rational\n * integration actually need. {@link polynomialGcd} declines rather than guessing\n * when handed more than one variable.\n *\n * Coefficients are exact, which matters more here than almost anywhere else in\n * the system: the Euclidean algorithm decides at every step whether a remainder\n * is zero, and in floating point that question has no reliable answer.\n */\n\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\tisRationalZero,\n\tisRationalOne,\n} from \"@solve-js/symbolic/Rational\";\nimport {\n\ttype Polynomial,\n\ttoPolynomial,\n\tfromPolynomial,\n\tpolyDegree,\n\tpolyUnivariateVar,\n\tpolyCoefficients,\n} from \"@solve-js/symbolic/Polynomial\";\nimport type { SymbolicNode } from \"@solve-js/symbolic/SymbolicNode\";\n\n/** A polynomial as dense coefficients, index `i` holding the coefficient of `x^i`. */\nexport type Coefficients = readonly Rational[];\n\n/** Drops trailing zero coefficients, so the degree is always the real one. */\nfunction trim(coefficients: Rational[]): Rational[] {\n\tlet last = coefficients.length - 1;\n\twhile (last >= 0 && isRationalZero(coefficients[last])) last--;\n\treturn coefficients.slice(0, last + 1);\n}\n\n/**\n * Whether a coefficient list is the zero polynomial.\n *\n * @param coefficients - Ascending coefficients.\n * @returns True when every coefficient is zero.\n */\nexport function isZeroPolynomial(coefficients: Coefficients): boolean {\n\treturn coefficients.every(isRationalZero);\n}\n\n/**\n * Divides one polynomial by another, exactly.\n *\n * @param dividend - Ascending coefficients of the numerator.\n * @param divisor - Ascending coefficients of the denominator, which must not be\n * the zero polynomial.\n * @returns The quotient and remainder, both ascending, satisfying\n * `dividend = divisor * quotient + remainder` with the remainder of lower\n * degree than the divisor.\n * @throws {Error} When the divisor is zero, which is a caller error rather than\n * a user-facing condition.\n */\nexport function polynomialDivide(\n\tdividend: Coefficients,\n\tdivisor: Coefficients,\n): { quotient: Rational[]; remainder: Rational[] } {\n\tconst numerator = trim([...dividend]);\n\tconst denominator = trim([...divisor]);\n\tif (denominator.length === 0) throw new Error(\"polynomialDivide: division by the zero polynomial\");\n\n\tconst divisorDegree = denominator.length - 1;\n\tconst leading = denominator[divisorDegree];\n\tconst remainder = [...numerator];\n\tconst quotient: Rational[] = new Array(Math.max(0, numerator.length - divisorDegree)).fill(RATIONAL_ZERO);\n\n\tfor (let degree = remainder.length - 1; degree >= divisorDegree; degree--) {\n\t\tif (isRationalZero(remainder[degree])) continue;\n\t\tconst factor = rationalDiv(remainder[degree], leading);\n\t\tconst offset = degree - divisorDegree;\n\t\tquotient[offset] = factor;\n\t\tfor (let i = 0; i <= divisorDegree; i++) {\n\t\t\tremainder[offset + i] = rationalSub(remainder[offset + i], rationalMul(factor, denominator[i]));\n\t\t}\n\t}\n\n\treturn { quotient: trim(quotient), remainder: trim(remainder) };\n}\n\n/** Scales a coefficient list so its leading coefficient is one, which makes the GCD canonical. */\nfunction monic(coefficients: Rational[]): Rational[] {\n\tconst trimmed = trim(coefficients);\n\tif (trimmed.length === 0) return trimmed;\n\tconst leading = trimmed[trimmed.length - 1];\n\tif (isRationalOne(leading)) return trimmed;\n\treturn trimmed.map(coefficient => rationalDiv(coefficient, leading));\n}\n\n/**\n * The greatest common divisor of two coefficient lists, by Euclid's algorithm.\n *\n * @param a - Ascending coefficients.\n * @param b - Ascending coefficients.\n * @returns The monic GCD. Two polynomials sharing no factor give `[1]`, and the\n * GCD of zero with anything is that other polynomial.\n */\nexport function coefficientGcd(a: Coefficients, b: Coefficients): Rational[] {\n\tlet left = trim([...a]);\n\tlet right = trim([...b]);\n\n\twhile (right.length > 0) {\n\t\tconst { remainder } = polynomialDivide(left, right);\n\t\tleft = right;\n\t\tright = remainder;\n\t}\n\treturn monic(left);\n}\n\n/**\n * The greatest common divisor of two polynomials.\n *\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns The monic GCD, or `null` when either polynomial involves more than\n * one variable, which this does not attempt.\n */\nexport function polynomialGcd(a: Polynomial, b: Polynomial): Polynomial | null {\n\tconst variable = sharedVariable(a, b);\n\tif (variable === undefined) return null;\n\n\t// A constant shares no polynomial factor with anything, so the GCD is one.\n\tif (variable === null) return toPolynomial({ kind: \"const\", value: RATIONAL_ONE });\n\n\tconst gcd = coefficientGcd(polyCoefficients(a, variable), polyCoefficients(b, variable));\n\treturn coefficientsToPolynomial(gcd, variable);\n}\n\n/**\n * The one variable two polynomials are written in.\n *\n * @returns The variable name, `null` when both are constants, or `undefined`\n * when they involve more than one variable between them and so are outside what\n * this module handles.\n */\nfunction sharedVariable(a: Polynomial, b: Polynomial): string | null | undefined {\n\tconst names = new Set([...a.vars, ...b.vars]);\n\tif (names.size === 0) return null;\n\tif (names.size > 1) return undefined;\n\treturn [...names][0];\n}\n\n/** Rebuilds a Polynomial from ascending coefficients in one variable. */\nfunction coefficientsToPolynomial(coefficients: Coefficients, variable: string): Polynomial {\n\tconst terms = new Map<string, Rational>();\n\tcoefficients.forEach((coefficient, power) => {\n\t\tif (isRationalZero(coefficient)) return;\n\t\tterms.set(power === 0 ? \"\" : power === 1 ? variable : `${variable}^${power}`, coefficient);\n\t});\n\treturn { terms, vars: terms.size > 0 && coefficients.length > 1 ? [variable] : [] };\n}\n\n/**\n * Reduces a fraction of two polynomials to lowest terms.\n *\n * @param numerator - The numerator.\n * @param denominator - The denominator.\n * @returns The reduced pair, or `null` when the two are outside what\n * {@link polynomialGcd} handles or share no factor worth cancelling.\n */\nexport function cancelRational(\n\tnumerator: Polynomial,\n\tdenominator: Polynomial,\n): { numerator: Polynomial; denominator: Polynomial } | null {\n\tconst gcd = polynomialGcd(numerator, denominator);\n\tif (gcd === null) return null;\n\t// A constant GCD means there is nothing to cancel, and reporting that as\n\t// \"no change\" rather than rebuilding an identical pair keeps the caller from\n\t// looping.\n\tif (polyDegree(gcd) === 0) return null;\n\n\tconst variable = polyUnivariateVar(gcd);\n\tif (variable === null) return null;\n\n\tconst gcdCoefficients = polyCoefficients(gcd, variable);\n\tconst reducedNumerator = polynomialDivide(polyCoefficients(numerator, variable), gcdCoefficients);\n\tconst reducedDenominator = polynomialDivide(polyCoefficients(denominator, variable), gcdCoefficients);\n\n\treturn {\n\t\tnumerator: coefficientsToPolynomial(reducedNumerator.quotient, variable),\n\t\tdenominator: coefficientsToPolynomial(reducedDenominator.quotient, variable),\n\t};\n}\n\n/**\n * Cancels the common factors of a quotient of two expressions.\n *\n * This is the explicit counterpart to the simplifier's own narrow cancellation:\n * it multiplies out both sides, divides by their greatest common divisor, and\n * rebuilds. `(x^2-1)/(x-1)` becomes `x+1`.\n *\n * @param node - The expression to reduce.\n * @returns The reduced expression, or `node` unchanged when it is not a\n * quotient of polynomials in one variable, or when there is nothing to cancel.\n */\nexport function cancelSymbolic(node: SymbolicNode): SymbolicNode {\n\tif (node.kind !== \"div\") return node;\n\n\tconst numerator = toPolynomial(node.left);\n\tconst denominator = toPolynomial(node.right);\n\tif (numerator === null || denominator === null) return node;\n\n\tconst reduced = cancelRational(numerator, denominator);\n\tif (reduced === null) return node;\n\n\t// The constant is only divided through as the last step of a cancellation\n\t// that already happened. Doing it unconditionally would rewrite `x/3` as\n\t// `1/3x`, which is the same number and a worse way to write it.\n\treturn divideOutConstant(reduced.numerator, reduced.denominator, node);\n}\n\n/**\n * Rebuilds a reduced fraction, folding a constant denominator into the\n * numerator.\n *\n * The polynomial GCD is monic, so it never carries a numeric factor away with\n * it: `(2x^2+4x)/(2x)` cancels to `(2x+4)/2` and stops. Dividing through by a\n * leftover constant denominator finishes the job and gives `x+2`.\n *\n * @param numerator - The reduced numerator.\n * @param denominator - The reduced denominator.\n * @param original - Returned unchanged when nothing improved, so the caller can\n * detect \"no progress\" by identity.\n * @returns The rebuilt expression.\n */\nfunction divideOutConstant(numerator: Polynomial, denominator: Polynomial, original: SymbolicNode): SymbolicNode {\n\tif (polyDegree(denominator) === 0) {\n\t\tconst constant = denominator.terms.get(\"\") ?? RATIONAL_ONE;\n\t\tif (isRationalZero(constant)) return original;\n\t\tconst scaled = new Map<string, Rational>();\n\t\tfor (const [key, coefficient] of numerator.terms) scaled.set(key, rationalDiv(coefficient, constant));\n\t\treturn fromPolynomial({ terms: scaled, vars: numerator.vars });\n\t}\n\treturn { kind: \"div\", left: fromPolynomial(numerator), right: fromPolynomial(denominator) };\n}\n\n/**\n * The square-free part of a polynomial, and the multiplicities it came from.\n *\n * A polynomial shares a factor with its own derivative exactly where that factor\n * is repeated, so `gcd(p, p')` isolates the repeats. This is what lets a\n * factorization report `(x-1)^2` rather than two identical factors, and it is\n * the first step of most serious factoring algorithms.\n *\n * @param coefficients - Ascending coefficients.\n * @returns The square-free part, ascending and monic.\n */\nexport function squareFreePart(coefficients: Coefficients): Rational[] {\n\tconst trimmed = trim([...coefficients]);\n\tif (trimmed.length <= 1) return monic(trimmed);\n\n\tconst derivative: Rational[] = [];\n\tfor (let power = 1; power < trimmed.length; power++) {\n\t\tderivative.push(rationalMul(trimmed[power], { n: BigInt(power), d: 1n }));\n\t}\n\n\tconst shared = coefficientGcd(trimmed, derivative);\n\tif (shared.length <= 1) return monic(trimmed);\n\treturn monic(polynomialDivide(trimmed, shared).quotient);\n}\n\n/**\n * Evaluates ascending coefficients at a rational point, by Horner's method.\n *\n * @param coefficients - Ascending coefficients.\n * @param x - The point.\n * @returns The value there.\n */\nexport function evaluateCoefficients(coefficients: Coefficients, x: Rational): Rational {\n\tlet total = RATIONAL_ZERO;\n\tfor (let i = coefficients.length - 1; i >= 0; i--) {\n\t\ttotal = rationalAdd(rationalMul(total, x), coefficients[i]);\n\t}\n\treturn total;\n}\n","/**\n * Exact integer roots, and the surd forms built on them.\n *\n * Two questions are asked constantly once a solver starts producing radicals:\n * \"is this a perfect power?\", which decides whether an answer is rational or\n * irrational, and \"how do I write this root so a person can read it?\". Both\n * answers live here so the quadratic, cubic and quartic paths give the same\n * shape rather than each inventing one.\n *\n * The reduction matters more than it looks. `sqrt(8)` and `2*sqrt(2)` are the\n * same number, but a solver that emits the first leaves the user to finish the\n * work, and two roots of the same equation can end up written in visibly\n * different styles depending on which one happened to cancel.\n */\n\nimport { type SymbolicNode, constNode } from \"@solve-js/symbolic/SymbolicNode\";\nimport { type Rational, rational } from \"@solve-js/symbolic/Rational\";\n\n/**\n * The exact integer square root, or `null` when the input is not a perfect\n * square.\n *\n * This is the predicate that keeps `sqrt(2)` unfolded. Newton's method on\n * integers, so it stays exact at any size.\n *\n * @param value - A non-negative integer. Negative input gives `null`, since it\n * has no integer square root.\n * @returns The root, or `null`.\n */\nexport function exactIntegerSqrt(value: bigint): bigint | null {\n\tif (value < 0n) return null;\n\tif (value < 2n) return value;\n\tlet previous = value;\n\tlet current = (value + 1n) / 2n;\n\twhile (current < previous) {\n\t\tprevious = current;\n\t\tcurrent = (previous + value / previous) / 2n;\n\t}\n\treturn previous * previous === value ? previous : null;\n}\n\n/**\n * The exact integer cube root, or `null` when the input is not a perfect cube.\n *\n * Unlike the square root this accepts negatives, because every real number has\n * a real cube root and `cbrt(-8)` is exactly `-2`.\n *\n * @param value - Any integer.\n * @returns The root, or `null`.\n */\nexport function exactIntegerCbrt(value: bigint): bigint | null {\n\tconst negative = value < 0n;\n\tconst magnitude = negative ? -value : value;\n\tif (magnitude < 2n) return negative ? -magnitude : magnitude;\n\n\tlet low = 1n;\n\tlet high = magnitude;\n\twhile (low <= high) {\n\t\tconst middle = (low + high) / 2n;\n\t\tconst cube = middle * middle * middle;\n\t\tif (cube === magnitude) return negative ? -middle : middle;\n\t\tif (cube < magnitude) low = middle + 1n;\n\t\telse high = middle - 1n;\n\t}\n\treturn null;\n}\n\n/**\n * The exact square root of a rational, or `null` when it is irrational.\n *\n * Both the numerator and the denominator have to be perfect squares, since the\n * root of a reduced fraction is taken componentwise.\n *\n * @param value - A non-negative rational.\n * @returns The exact root, or `null`.\n */\nexport function exactRationalSqrt(value: Rational): Rational | null {\n\tconst numerator = exactIntegerSqrt(value.n);\n\tconst denominator = exactIntegerSqrt(value.d);\n\treturn numerator === null || denominator === null ? null : { n: numerator, d: denominator };\n}\n\n/**\n * The square root of a non-negative rational, in lowest surd form.\n *\n * `sqrt(8)` comes back as `2*sqrt(2)`, and a perfect square comes back as a\n * plain constant. Written as a `sqrt` call rather than a power of one half so it\n * reads the way it is normally written, and so the simplifier's own exact\n * folding collapses it when the radicand turns out to be a perfect square after\n * all.\n *\n * `sqrt(n/d)` is computed as `sqrt(n*d)/d`, which keeps the extraction of square\n * factors entirely in integers.\n *\n * @param value - A non-negative rational.\n * @returns The root as an expression, or as a constant when it is rational.\n */\nexport function surdNode(value: Rational): SymbolicNode {\n\tconst radicand = value.n * value.d;\n\n\t// Pull out the largest square factor by trial division.\n\tlet extracted = 1n;\n\tlet remaining = radicand;\n\tfor (let factor = 2n; factor * factor <= remaining; factor++) {\n\t\tconst square = factor * factor;\n\t\twhile (remaining % square === 0n) {\n\t\t\tremaining /= square;\n\t\t\textracted *= factor;\n\t\t}\n\t}\n\n\t// Built through `rational` rather than as a literal: the extracted factor\n\t// comes from `n*d` and so can share a factor with `d`, and an unreduced pair\n\t// would surface as a coefficient written `6/108`.\n\tconst scale = rational(extracted, value.d);\n\tif (remaining === 1n) return constNode(scale);\n\n\tconst root: SymbolicNode = { kind: \"call\", name: \"sqrt\", args: [constNode({ n: remaining, d: 1n })] };\n\treturn scale.n === 1n && scale.d === 1n ? root : { kind: \"mul\", left: constNode(scale), right: root };\n}\n\n/**\n * The square root of a rational of either sign, as a real surd or an imaginary\n * one.\n *\n * @param value - Any rational.\n * @returns `sqrt(value)` for a non-negative input, and `sqrt(-value)*i` for a\n * negative one. The simplifier's own complex handling produces the same shape,\n * so the two agree.\n */\nexport function signedSurdNode(value: Rational): SymbolicNode {\n\tif (value.n >= 0n) return surdNode(value);\n\treturn { kind: \"call\", name: \"sqrt\", args: [constNode(value)] };\n}\n\n/**\n * The cube root of a rational, exact when the input is a perfect cube.\n *\n * @param value - Any rational.\n * @returns A constant when the root is rational, and a `cbrt` call otherwise.\n */\nexport function cbrtNode(value: Rational): SymbolicNode {\n\tconst numerator = exactIntegerCbrt(value.n);\n\tconst denominator = exactIntegerCbrt(value.d);\n\tif (numerator !== null && denominator !== null) return constNode({ n: numerator, d: denominator });\n\treturn { kind: \"call\", name: \"cbrt\", args: [constNode(value)] };\n}\n","/**\n * Bounded, bottom-up simplification of a {@link SymbolicNode}.\n *\n * ## The invariant that governs this module\n *\n * **`simplifySymbolic` never expands and never factors.** `expandSymbolic()`,\n * `factorSymbolic()` and `toPolynomial()` are separate, explicitly-invoked\n * entry points and are never reachable from here.\n *\n * Concretely, and as enforced by the property test in\n * `__tests__/symbolic/Simplify.spec.ts`:\n *\n * 1. **No distribution.** `(x+1)*(x+2)` and `2*(x+y+1)` come back exactly as\n * written. This is what \"never expands\" means, and it is enforced at the\n * source: {@link collectSum} converts to polynomial form with distribution\n * disabled, so a product only converts when both sides are single terms.\n * That is precisely what collecting `2b + 3b` into `5b` needs, and nothing\n * beyond it.\n * 2. **Idempotent.** Simplifying a result again changes nothing.\n * 3. **Bounded size.** Node count never grows by more than one, and the single\n * permitted node has one cause: an all-negative sum has no positive term to\n * lead with, so canonical order needs a `neg` where the input had a negative\n * constant. It cannot compound, because the result is idempotent.\n *\n * These rules are load-bearing. `vm/VMConversion.ts`'s `binaryOp()` calls this\n * once per symbolic arithmetic operation, so a rule that genuinely grew the\n * tree would compound across a long chain. And rule 1 keeps `pow` safe:\n * `simplify(x^2)` stays `x^2` rather than becoming `x*x`, so a polynomial keeps\n * the compact shape the rest of the system reads.\n *\n * ## What it does\n *\n * - Constant folding over exact rationals, including `pow` with an integer\n * exponent and a small set of functions with exact rational images.\n * - Additive and multiplicative identities (`x+0`, `x*1`, `x*0`, `x/1`, `--x`,\n * `x^1`, `x^0`).\n * - Flatten-and-collect of like terms across a top-level sum: a chain of\n * `+`/`-`/unary `-` over bare constants and bare variable names, so\n * `1+2+b+3+b` becomes `2b+6`. A `mul`/`div` node is not flattened through.\n * - One narrow exception to that last point: `div` cancels a single common\n * factor when the denominator is structurally identical to one whole factor\n * of a top-level product (`sx*tx/sx` becomes `tx`). This exists for\n * triangular-matrix symbolic inverses and is not a general polynomial\n * division capability.\n *\n * Function folding is deliberately conservative. `sqrt(4)` folds to `2`\n * because four is a perfect square; **`sqrt(2)` does not fold**, because it has\n * no rational value and inventing `1.4142135624` here is how a system that\n * advertises exact arithmetic starts lying.\n *\n * See `vm/VMConversion.ts`'s `binaryOp()` for where this plugs into the\n * ordinary arithmetic opcodes, and `SymbolicFormat.ts` for display.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tnodesEqual,\n\tnodeCount,\n\tSYMBOLIC_MAX_NODES,\n\tcomplexNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\tRATIONAL_MINUS_ONE,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\trationalPow,\n\tisRationalZero,\n\tisRationalOne,\n\tisRationalMinusOne,\n\tisRationalInteger,\n} from \"@solve-js/symbolic/Rational\";\nimport { toPolynomial, fromPolynomial } from \"@solve-js/symbolic/Polynomial\";\nimport { cancelSymbolic } from \"@solve-js/symbolic/Gcd\";\nimport { exactIntegerSqrt, exactIntegerCbrt } from \"@solve-js/symbolic/Radicals\";\nimport {\n\ttype Complex,\n\tcomplex,\n\tcomplexAdd,\n\tcomplexSub,\n\tcomplexMul,\n\tcomplexDiv,\n\tcomplexNeg,\n\tcomplexPow,\n\tcomplexConjugate,\n\tcomplexNormSquared,\n\texactComplexSqrt,\n\tisComplexZero,\n\tCOMPLEX_I,\n} from \"@solve-js/symbolic/Complex\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n// ── Flatten-and-collect (top-level sums only) ──────────────────────────────\n\ninterface FlatTerm {\n\tcoeff: Rational;\n\t/** `null` means this term is the accumulated constant. */\n\tname: string | null;\n}\n\n/**\n * Recursively unrolls an `add`/`sub`/`neg` chain into a flat list of signed\n * terms. Returns `false` (callers discard `out` on a `false` return) the moment\n * it meets anything that is not a constant, a bare variable, or another\n * additive node, since collecting terms through a product is out of scope here.\n */\nfunction flattenSum(node: SymbolicNode, negated: boolean, out: FlatTerm[], depth = 0): boolean {\n\t// A second walk of its own, so the depth guard on `simplifyNode` does not\n\t// cover it: this one is entered at whatever depth the simplifier reached\n\t// and then descends the whole remaining chain, which for `a+(b+(c+...))`\n\t// is as deep as the tree. `false` is the answer this function already gives\n\t// for anything it cannot flatten, and the caller already knows what to do\n\t// with it, so the guard needs no new outcome.\n\tif (depth >= MAX_SIMPLIFY_DEPTH) return false;\n\tswitch (node.kind) {\n\t\tcase \"add\":\n\t\t\treturn flattenSum(node.left, negated, out, depth + 1) && flattenSum(node.right, negated, out, depth + 1);\n\t\tcase \"sub\":\n\t\t\treturn flattenSum(node.left, negated, out, depth + 1) && flattenSum(node.right, !negated, out, depth + 1);\n\t\tcase \"neg\":\n\t\t\treturn flattenSum(node.operand, !negated, out, depth + 1);\n\t\tcase \"const\":\n\t\t\tout.push({ coeff: negated ? rationalNeg(node.value) : node.value, name: null });\n\t\t\treturn true;\n\t\tcase \"var\":\n\t\t\tout.push({ coeff: negated ? RATIONAL_MINUS_ONE : RATIONAL_ONE, name: node.name });\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/**\n * Collects like terms in a fully-flattenable `add`/`sub` chain, so\n * `1+2+b+3+b` becomes `2b+6`: variable terms first in first-seen order, then\n * the combined constant last, with a zero-coefficient term dropped entirely to\n * match the `x+0 -> x` identity. Returns `node` unchanged when it is not fully\n * flattenable, which is what keeps a rational-function shape such as\n * `vx/sx-tx` intact.\n */\nfunction collectTerms(node: SymbolicNode): SymbolicNode {\n\tconst flat: FlatTerm[] = [];\n\tif (!flattenSum(node, false, flat)) return node;\n\n\tconst order: string[] = [];\n\tconst coeffByName = new Map<string, Rational>();\n\tlet constant = RATIONAL_ZERO;\n\tfor (const term of flat) {\n\t\tif (term.name === null) {\n\t\t\tconstant = rationalAdd(constant, term.coeff);\n\t\t\tcontinue;\n\t\t}\n\t\tconst existing = coeffByName.get(term.name);\n\t\tif (existing === undefined) {\n\t\t\torder.push(term.name);\n\t\t\tcoeffByName.set(term.name, term.coeff);\n\t\t} else {\n\t\t\tcoeffByName.set(term.name, rationalAdd(existing, term.coeff));\n\t\t}\n\t}\n\n\tconst termNodes: SymbolicNode[] = [];\n\tfor (const name of order) {\n\t\tconst coeff = coeffByName.get(name)!;\n\t\tif (isRationalZero(coeff)) continue;\n\t\tif (isRationalOne(coeff)) termNodes.push(varNode(name));\n\t\telse if (isRationalMinusOne(coeff)) termNodes.push({ kind: \"neg\", operand: varNode(name) });\n\t\telse termNodes.push({ kind: \"mul\", left: constNode(coeff), right: varNode(name) });\n\t}\n\n\tif (termNodes.length === 0) return constNode(constant);\n\n\tlet result = termNodes[0];\n\tfor (let i = 1; i < termNodes.length; i++) {\n\t\tresult = { kind: \"add\", left: result, right: termNodes[i] };\n\t}\n\tif (!isRationalZero(constant)) {\n\t\tresult = { kind: \"add\", left: result, right: constNode(constant) };\n\t}\n\treturn result;\n}\n\n/**\n * Collects a sum, preferring the canonical polynomial form and falling back to\n * the tree-level {@link collectTerms} when the expression is not a polynomial.\n *\n * The two-step shape is what lets like terms combine through a product\n * (`2b + 3b` becomes `5b`, which the tree walk alone cannot do, since it stops\n * at the first `mul`) without disturbing anything the polynomial form cannot\n * represent. `vx/sx - tx` is a rational function, so `toPolynomial` reports\n * `null` and the original handling runs untouched. That fallback is what keeps\n * symbolic matrix inverses rendering as they always have.\n *\n * Only `add` and `sub` route through here. The `mul` and `div` cases keep their\n * own rules verbatim, including the reciprocal canonicalization and the\n * single-common-factor cancellation, because the polynomial form can express\n * neither.\n *\n * This does not violate the module's no-growth invariant: a polynomial is a\n * collected sum, so the round trip only ever merges terms.\n */\nfunction collectSum(node: SymbolicNode): SymbolicNode {\n\t// Distribution disabled: collecting like terms must never multiply out a\n\t// product of sums, which would be expansion by another name.\n\tconst polynomial = toPolynomial(node, false);\n\tif (polynomial !== null) return fromPolynomial(polynomial);\n\treturn collectTerms(node);\n}\n\n// ── Exact function folding ──────────────────────────────────────────────────\n\n/** Greatest integer not exceeding `r`. Bigint division truncates toward zero, so a negative non-integer needs one more step down. */\nfunction rationalFloor(r: Rational): bigint {\n\tconst truncated = r.n / r.d;\n\treturn r.n < 0n && truncated * r.d !== r.n ? truncated - 1n : truncated;\n}\n\n/** Largest factorial this will fold. Beyond this the exact result is enormous and the caller almost certainly wants the numeric builtin instead. */\nconst MAX_FOLDED_FACTORIAL = 500n;\n\n/**\n * Folds a function application whose arguments are all constant, but **only**\n * when the exact result is rational.\n *\n * Returning `null` leaves the call symbolic, which is always the safe answer.\n * Adding a function here that has an irrational result for some rational input\n * would make the simplifier produce a confidently wrong value.\n */\nfunction foldCall(name: string, args: readonly Rational[]): Rational | null {\n\tconst first = args[0];\n\tswitch (name) {\n\t\tcase \"abs\":\n\t\t\treturn args.length === 1 ? (first.n < 0n ? rationalNeg(first) : first) : null;\n\t\tcase \"sign\":\n\t\t\tif (args.length !== 1) return null;\n\t\t\treturn first.n === 0n ? RATIONAL_ZERO : { n: first.n < 0n ? -1n : 1n, d: 1n };\n\t\tcase \"floor\":\n\t\t\treturn args.length === 1 ? { n: rationalFloor(first), d: 1n } : null;\n\t\tcase \"ceil\":\n\t\t\treturn args.length === 1 ? { n: -rationalFloor(rationalNeg(first)), d: 1n } : null;\n\t\tcase \"trunc\":\n\t\t\treturn args.length === 1 ? { n: first.n / first.d, d: 1n } : null;\n\t\tcase \"round\":\n\t\t\t// Matches Math.round: halfway cases go toward positive infinity.\n\t\t\treturn args.length === 1 ? { n: rationalFloor(rationalAdd(first, { n: 1n, d: 2n })), d: 1n } : null;\n\t\tcase \"sqrt\": {\n\t\t\tif (args.length !== 1 || first.n < 0n) return null;\n\t\t\tconst rootN = exactIntegerSqrt(first.n);\n\t\t\tconst rootD = exactIntegerSqrt(first.d);\n\t\t\treturn rootN === null || rootD === null ? null : { n: rootN, d: rootD };\n\t\t}\n\t\tcase \"cbrt\": {\n\t\t\t// Unlike the square root this accepts a negative: every real number has\n\t\t\t// a real cube root, so `cbrt(-8)` is exactly `-2`. Cardano's formula\n\t\t\t// leans on this, which is how a cubic whose closed form happens to be\n\t\t\t// rational still comes back as a plain number.\n\t\t\tif (args.length !== 1) return null;\n\t\t\tconst rootN = exactIntegerCbrt(first.n);\n\t\t\tconst rootD = exactIntegerCbrt(first.d);\n\t\t\treturn rootN === null || rootD === null ? null : { n: rootN, d: rootD };\n\t\t}\n\t\t// Exact values at the points where these functions are rational. Every\n\t\t// entry is exact, not rounded, which is what lets a Taylor series about\n\t\t// the origin come out with exact coefficients. Deliberately narrow:\n\t\t// `sin(1)` and `log(2)` are irrational and must stay symbolic.\n\t\tcase \"sin\":\n\t\tcase \"tan\":\n\t\tcase \"asin\":\n\t\tcase \"atan\":\n\t\tcase \"sinh\":\n\t\tcase \"tanh\":\n\t\t\treturn args.length === 1 && isRationalZero(first) ? RATIONAL_ZERO : null;\n\t\tcase \"cos\":\n\t\tcase \"exp\":\n\t\tcase \"cosh\":\n\t\t\treturn args.length === 1 && isRationalZero(first) ? RATIONAL_ONE : null;\n\t\tcase \"log\":\n\t\t\treturn args.length === 1 && isRationalOne(first) ? RATIONAL_ZERO : null;\n\t\tcase \"acos\":\n\t\t\t// acos(1) = 0 is the only rational value; acos(0) is pi/2, which is not.\n\t\t\treturn args.length === 1 && isRationalOne(first) ? RATIONAL_ZERO : null;\n\t\tcase \"fact\": {\n\t\t\tif (args.length !== 1 || !isRationalInteger(first) || first.n < 0n || first.n > MAX_FOLDED_FACTORIAL) return null;\n\t\t\tlet total = 1n;\n\t\t\tfor (let i = 2n; i <= first.n; i++) total *= i;\n\t\t\treturn { n: total, d: 1n };\n\t\t}\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n// ── simplify ────────────────────────────────────────────────────────────────\n\n/**\n * Simplifies a symbolic expression bottom-up under this module's stated\n * invariant.\n *\n * Always terminates and is idempotent in structural terms, so it is safe to\n * call repeatedly (once per `binaryOp()`, for instance) without accumulating\n * tree depth across a long chain of operations.\n *\n * @param node - The tree to simplify.\n * @returns The simplified tree, which is never larger than the input.\n * @throws {EngineError} `SYMBOLIC_NODE_LIMIT_EXCEEDED` when the input exceeds\n * {@link SYMBOLIC_MAX_NODES}.\n */\nexport function simplifySymbolic(node: SymbolicNode): SymbolicNode {\n\t// The limit is passed through so the walk stops as soon as it is exceeded.\n\t// Without it a tree far past the ceiling would be counted in full before\n\t// being rejected, which is the opposite of what a guard is for.\n\tif (nodeCount(node, SYMBOLIC_MAX_NODES) > SYMBOLIC_MAX_NODES) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_NODE_LIMIT_EXCEEDED\",\n\t\t\t`This symbolic expression is too large to simplify (over ${SYMBOLIC_MAX_NODES} terms).`,\n\t\t\t{ limit: SYMBOLIC_MAX_NODES },\n\t\t);\n\t}\n\t// Restored rather than zeroed, because this function is genuinely reentrant\n\t// (`vm/MatrixOps.ts` simplifies each cell of a symbolic product from inside\n\t// a walk that is already in progress), so a nested call has to add to the\n\t// enclosing depth rather than forget it. The `finally` is what makes a\n\t// throw from deep inside, a rational overflow for instance, unable to leave\n\t// the counter high and the simplifier quietly switched off for the rest of\n\t// the process, which is the one failure mode a guard must not have.\n\tconst depthOnEntry = walkDepth;\n\ttry {\n\t\treturn simplifyNode(node);\n\t} finally {\n\t\twalkDepth = depthOnEntry;\n\t}\n}\n\n/**\n * How deep the simplifier will walk before leaving a subtree alone.\n *\n * `SYMBOLIC_MAX_NODES` bounds a tree's SIZE, and size and depth come apart\n * completely for a chain, where a thousand nodes is a thousand levels. The\n * recursive walk below runs out of native stack at around four thousand levels,\n * which is well inside the ten thousand nodes the size guard admits, so there\n * was a whole band of trees the engine called legal and then died on with a raw\n * \"Maximum call stack size exceeded\" that no host can tell from a bug in its\n * own code. `SymbolicNode.ts`'s `nodeCount()` was made iterative for exactly\n * this reason; that made the size guard reachable without making the functions\n * it guards able to walk what it admits.\n *\n * A quarter of the measured native limit, because these functions are called\n * from inside the VM's dispatch loop, which has already spent stack of its own.\n *\n * Past it the subtree is returned as it came in. Simplification is an\n * improvement to a tree, never a requirement of one, so an unsimplified branch\n * is still exactly the expression the user wrote; the alternative, an error, is\n * worse for a document whose deep line is otherwise perfectly answerable.\n */\nconst MAX_SIMPLIFY_DEPTH = 900;\n\n/** How deep the walk currently is. Module state; see {@link simplifySymbolic} for how it is kept honest. */\nlet walkDepth = 0;\n\n/**\n * Depth-bounded wrapper around the real worker.\n *\n * Every recursive call in {@link simplifyNodeAt} goes through here, so one\n * increment per level is all the bookkeeping the guard needs. The decrement is\n * deliberately not in a `finally`: a throw skips it, and the `finally` in\n * {@link simplifySymbolic} restores the whole counter at the point the throw is\n * caught, which is cheaper per node and exactly as correct.\n */\nfunction simplifyNode(node: SymbolicNode): SymbolicNode {\n\tif (walkDepth >= MAX_SIMPLIFY_DEPTH) return node;\n\twalkDepth++;\n\tconst simplified = simplifyNodeAt(node);\n\twalkDepth--;\n\treturn simplified;\n}\n\n/**\n * Reads a numeric atom as a complex value, so the arithmetic cases can treat a\n * real constant and a complex one uniformly.\n *\n * Returns `null` for anything that is not a literal number, which is what keeps\n * the real fast paths below from being disturbed.\n */\nfunction asComplex(node: SymbolicNode): Complex | null {\n\tif (node.kind === \"complex\") return node.value;\n\tif (node.kind === \"const\") return complex(node.value);\n\treturn null;\n}\n\n/**\n * Folds an arithmetic node whose operands are both literal numbers and at least\n * one of which is complex.\n *\n * Returns `null` when the node is not that shape, leaving every real-only path\n * exactly as it was: a pair of rational constants never reaches this, so\n * ordinary arithmetic pays nothing for complex support.\n */\nfunction foldComplexBinary(kind: \"add\" | \"sub\" | \"mul\" | \"div\", left: SymbolicNode, right: SymbolicNode): SymbolicNode | null {\n\tif (left.kind !== \"complex\" && right.kind !== \"complex\") return null;\n\tconst a = asComplex(left);\n\tconst b = asComplex(right);\n\tif (a === null || b === null) return null;\n\tswitch (kind) {\n\t\tcase \"add\": return complexNode(complexAdd(a, b));\n\t\tcase \"sub\": return complexNode(complexSub(a, b));\n\t\tcase \"mul\": return complexNode(complexMul(a, b));\n\t\tcase \"div\": return isComplexZero(b) ? null : complexNode(complexDiv(a, b));\n\t}\n}\n\n/**\n * Folds a function whose exact answer is complex.\n *\n * The only entries are the ones whose real-domain versions have a genuine hole:\n * `sqrt` and `abs` of a negative, and the accessors that take a complex value\n * apart. `sqrt(-4)` is exactly `2i`, which the real-only table above had to\n * decline. Anything whose complex value is irrational, `sqrt(i)` for instance,\n * still comes back `null` and stays symbolic.\n *\n * @returns The folded node, or `null` to leave the call alone.\n */\nfunction foldComplexCall(name: string, args: readonly SymbolicNode[]): SymbolicNode | null {\n\tif (args.length !== 1) return null;\n\tconst value = asComplex(args[0]);\n\tif (value === null) return null;\n\n\tswitch (name) {\n\t\tcase \"sqrt\": {\n\t\t\tconst root = exactComplexSqrt(value);\n\t\t\tif (root !== null) return complexNode(root);\n\t\t\t// A negative real whose magnitude has no rational root is still worth\n\t\t\t// rewriting: `sqrt(-2)` is `sqrt(2)*i`, which pulls the imaginary unit\n\t\t\t// out where the rest of the system can work with it, instead of\n\t\t\t// leaving a square root of a negative number sitting in the tree.\n\t\t\tif (isRationalZero(value.im) && value.re.n < 0n) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"mul\",\n\t\t\t\t\tleft: { kind: \"call\", name: \"sqrt\", args: [constNode(rationalNeg(value.re))] },\n\t\t\t\t\tright: complexNode(COMPLEX_I),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\tcase \"conj\":\n\t\t\treturn complexNode(complexConjugate(value));\n\t\tcase \"re\":\n\t\t\treturn constNode(value.re);\n\t\tcase \"im\":\n\t\t\treturn constNode(value.im);\n\t\tcase \"abs\": {\n\t\t\t// |z| is the square root of a rational, so it is only exact when that\n\t\t\t// root is. The real-only table already handles a real argument.\n\t\t\tif (isRationalZero(value.im)) return null;\n\t\t\tconst modulus = exactComplexSqrt(complex(complexNormSquared(value)));\n\t\t\treturn modulus === null || !isRationalZero(modulus.im) ? null : constNode(modulus.re);\n\t\t}\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/** Recursive worker for {@link simplifySymbolic}, past the one-time size guard and under the depth guard in {@link simplifyNode}. */\nfunction simplifyNodeAt(node: SymbolicNode): SymbolicNode {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\tcase \"complex\":\n\t\tcase \"var\":\n\t\t\treturn node;\n\n\t\tcase \"neg\": {\n\t\t\tconst operand = simplifyNode(node.operand);\n\t\t\tif (operand.kind === \"const\") return constNode(rationalNeg(operand.value));\n\t\t\tif (operand.kind === \"complex\") return complexNode(complexNeg(operand.value));\n\t\t\tif (operand.kind === \"neg\") return operand.operand;\n\t\t\treturn { kind: \"neg\", operand };\n\t\t}\n\n\t\tcase \"add\": {\n\t\t\tconst left = simplifyNode(node.left);\n\t\t\tconst right = simplifyNode(node.right);\n\t\t\tif (left.kind === \"const\" && right.kind === \"const\") return constNode(rationalAdd(left.value, right.value));\n\t\t\tconst foldedAdd = foldComplexBinary(\"add\", left, right);\n\t\t\tif (foldedAdd !== null) return foldedAdd;\n\t\t\tif (left.kind === \"const\" && isRationalZero(left.value)) return right;\n\t\t\tif (right.kind === \"const\" && isRationalZero(right.value)) return left;\n\t\t\treturn collectSum({ kind: \"add\", left, right });\n\t\t}\n\n\t\tcase \"sub\": {\n\t\t\tconst left = simplifyNode(node.left);\n\t\t\tconst right = simplifyNode(node.right);\n\t\t\tif (left.kind === \"const\" && right.kind === \"const\") return constNode(rationalSub(left.value, right.value));\n\t\t\tconst foldedSub = foldComplexBinary(\"sub\", left, right);\n\t\t\tif (foldedSub !== null) return foldedSub;\n\t\t\tif (right.kind === \"const\" && isRationalZero(right.value)) return left;\n\t\t\tif (left.kind === \"const\" && isRationalZero(left.value)) return simplifyNode({ kind: \"neg\", operand: right });\n\t\t\treturn collectSum({ kind: \"sub\", left, right });\n\t\t}\n\n\t\tcase \"mul\": {\n\t\t\tconst left = simplifyNode(node.left);\n\t\t\tconst right = simplifyNode(node.right);\n\t\t\tif (left.kind === \"const\" && right.kind === \"const\") return constNode(rationalMul(left.value, right.value));\n\t\t\tconst foldedMul = foldComplexBinary(\"mul\", left, right);\n\t\t\tif (foldedMul !== null) return foldedMul;\n\t\t\tif ((left.kind === \"const\" && isRationalZero(left.value)) || (right.kind === \"const\" && isRationalZero(right.value))) {\n\t\t\t\treturn constNode(RATIONAL_ZERO);\n\t\t\t}\n\t\t\tif (left.kind === \"const\" && isRationalOne(left.value)) return right;\n\t\t\tif (right.kind === \"const\" && isRationalOne(right.value)) return left;\n\t\t\tif (left.kind === \"const\" && isRationalMinusOne(left.value)) return simplifyNode({ kind: \"neg\", operand: right });\n\t\t\tif (right.kind === \"const\" && isRationalMinusOne(right.value)) return simplifyNode({ kind: \"neg\", operand: left });\n\t\t\t// Gather adjacent constant factors: c1*(c2*rest) -> (c1*c2)*rest, and\n\t\t\t// the mirrored shape. Differentiation builds exactly these, so without\n\t\t\t// this the second derivative of x^3 stays as 3*(2*x) rather than 6x.\n\t\t\t// This removes a node rather than adding one, so the module's\n\t\t\t// no-growth invariant still holds.\n\t\t\tif (left.kind === \"const\" && right.kind === \"mul\" && right.left.kind === \"const\") {\n\t\t\t\treturn simplifyNode({ kind: \"mul\", left: constNode(rationalMul(left.value, right.left.value)), right: right.right });\n\t\t\t}\n\t\t\tif (right.kind === \"const\" && left.kind === \"mul\" && left.left.kind === \"const\") {\n\t\t\t\treturn simplifyNode({ kind: \"mul\", left: constNode(rationalMul(right.value, left.left.value)), right: left.right });\n\t\t\t}\n\t\t\t// Canonicalize a reciprocal factor into division: (1/a)*b -> b/a,\n\t\t\t// a*(1/b) -> a/b. A narrow display-canonicalization rule, needed\n\t\t\t// because matrix multiply builds cells as mul(entry, entry) in\n\t\t\t// encounter order, so a symbolic inverse's `1/sx` entry times a `vx`\n\t\t\t// cell produces `(1/sx)*vx` rather than the spec's own `vx/sx`,\n\t\t\t// mathematically identical but a different tree shape. Not a general\n\t\t\t// reciprocal-detection rule: it fires only when a factor is literally\n\t\t\t// `1/x`, never an arbitrary fraction.\n\t\t\tif (left.kind === \"div\" && left.left.kind === \"const\" && isRationalOne(left.left.value)) {\n\t\t\t\treturn simplifyNode({ kind: \"div\", left: right, right: left.right });\n\t\t\t}\n\t\t\tif (right.kind === \"div\" && right.left.kind === \"const\" && isRationalOne(right.left.value)) {\n\t\t\t\treturn simplifyNode({ kind: \"div\", left, right: right.right });\n\t\t\t}\n\t\t\treturn { kind: \"mul\", left, right };\n\t\t}\n\n\t\tcase \"div\": {\n\t\t\tconst left = simplifyNode(node.left);\n\t\t\tconst right = simplifyNode(node.right);\n\t\t\t// A constant denominator of zero is left unfolded rather than folded\n\t\t\t// or thrown. The previous double-based simplifier folded `1/0` to\n\t\t\t// `Infinity`; a Rational has no such value, and throwing from inside\n\t\t\t// a bottom-up walk would fail the whole line over a subexpression the\n\t\t\t// user may never see. Leaving `1/0` intact reports the situation\n\t\t\t// honestly and lets the caller decide.\n\t\t\tif (left.kind === \"const\" && right.kind === \"const\" && !isRationalZero(right.value)) {\n\t\t\t\treturn constNode(rationalDiv(left.value, right.value));\n\t\t\t}\n\t\t\tconst foldedDiv = foldComplexBinary(\"div\", left, right);\n\t\t\tif (foldedDiv !== null) return foldedDiv;\n\t\t\tif (right.kind === \"const\" && isRationalOne(right.value)) return left;\n\t\t\tif (left.kind === \"const\" && isRationalZero(left.value)) return constNode(RATIONAL_ZERO);\n\t\t\t// Cancel a single common factor: (a*b)/a -> b, (a*b)/b -> a. A narrow,\n\t\t\t// disclosed exception to \"never collects through mul/div\", needed for\n\t\t\t// the symbolic triangular-matrix-inverse case (`sx*tx/sx -> tx`). It\n\t\t\t// fires only when the denominator is structurally identical to one\n\t\t\t// whole factor of a top-level product, never a partial or nested match.\n\t\t\tif (left.kind === \"mul\") {\n\t\t\t\tif (nodesEqual(left.left, right)) return left.right;\n\t\t\t\tif (nodesEqual(left.right, right)) return left.left;\n\t\t\t}\n\t\t\t// Cancel a genuine common polynomial factor, so `(x^2-1)/(x-1)` reduces\n\t\t\t// to `x+1`. This is contraction rather than expansion: the result is\n\t\t\t// always smaller, so the no-growth invariant holds. A rational function\n\t\t\t// in more than one variable, `vx/sx`, has no univariate gcd and comes\n\t\t\t// back untouched.\n\t\t\tconst cancelled = cancelSymbolic({ kind: \"div\", left, right });\n\t\t\tif (cancelled.kind !== \"div\" || cancelled.left !== left || cancelled.right !== right) {\n\t\t\t\treturn simplifyNode(cancelled);\n\t\t\t}\n\t\t\t// The same cancellation through a leading minus: -(a*b)/a -> -b.\n\t\t\t// Without this the rule is asymmetric, and a quadratic's two surd\n\t\t\t// roots render differently from each other: `sqrt(2)` for the one\n\t\t\t// that cancelled and `-2*sqrt(2)/2` for the one that did not.\n\t\t\tif (left.kind === \"neg\" && left.operand.kind === \"mul\") {\n\t\t\t\tconst product = left.operand;\n\t\t\t\tif (nodesEqual(product.left, right)) return simplifyNode({ kind: \"neg\", operand: product.right });\n\t\t\t\tif (nodesEqual(product.right, right)) return simplifyNode({ kind: \"neg\", operand: product.left });\n\t\t\t}\n\t\t\treturn { kind: \"div\", left, right };\n\t\t}\n\n\t\tcase \"pow\": {\n\t\t\tconst base = simplifyNode(node.base);\n\t\t\tconst exponent = simplifyNode(node.exponent);\n\n\t\t\tif (exponent.kind === \"const\") {\n\t\t\t\tif (isRationalZero(exponent.value)) return constNode(RATIONAL_ONE);\n\t\t\t\tif (isRationalOne(exponent.value)) return base;\n\t\t\t\tif (base.kind === \"const\" && isRationalInteger(exponent.value)) {\n\t\t\t\t\treturn constNode(rationalPow(base.value, exponent.value.n));\n\t\t\t\t}\n\t\t\t\tif (base.kind === \"complex\" && isRationalInteger(exponent.value)) {\n\t\t\t\t\treturn complexNode(complexPow(base.value, exponent.value.n));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (base.kind === \"const\" && isRationalOne(base.value)) return constNode(RATIONAL_ONE);\n\t\t\t// 0^x is zero only for a positive exponent. 0^0 is one (handled\n\t\t\t// above) and 0^-1 is a division by zero, so neither may reach here.\n\t\t\tif (base.kind === \"const\" && isRationalZero(base.value) && exponent.kind === \"const\" && exponent.value.n > 0n) {\n\t\t\t\treturn constNode(RATIONAL_ZERO);\n\t\t\t}\n\t\t\t// (a^b)^c -> a^(b*c) is unsound in general (it loses a branch for a\n\t\t\t// negative base with fractional exponents), so it is allowed only\n\t\t\t// when both exponents are integers, where it always holds.\n\t\t\tif (\n\t\t\t\tbase.kind === \"pow\" &&\n\t\t\t\tbase.exponent.kind === \"const\" &&\n\t\t\t\texponent.kind === \"const\" &&\n\t\t\t\tisRationalInteger(base.exponent.value) &&\n\t\t\t\tisRationalInteger(exponent.value)\n\t\t\t) {\n\t\t\t\treturn simplifyNode({\n\t\t\t\t\tkind: \"pow\",\n\t\t\t\t\tbase: base.base,\n\t\t\t\t\texponent: constNode(rationalMul(base.exponent.value, exponent.value)),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { kind: \"pow\", base, exponent };\n\t\t}\n\n\t\tcase \"call\": {\n\t\t\tconst args = node.args.map(simplifyNode);\n\t\t\tif (args.every(arg => arg.kind === \"const\")) {\n\t\t\t\tconst folded = foldCall(node.name, args.map(arg => (arg as { kind: \"const\"; value: Rational }).value));\n\t\t\t\tif (folded !== null) return constNode(folded);\n\t\t\t}\n\t\t\tconst complexFolded = foldComplexCall(node.name, args);\n\t\t\tif (complexFolded !== null) return complexFolded;\n\t\t\treturn { kind: \"call\", name: node.name, args };\n\t\t}\n\t}\n}\n","/**\n * Rendering a {@link SymbolicNode} as display text.\n *\n * The conventions here match how the expressions are written rather than how\n * the tree is shaped: a coefficient juxtaposes its variable with no operator\n * (`2b`, not `2*b`), sums join with the correct sign (`2b+6` and `x-3`, never\n * `2b+-6`), and parentheses appear only where precedence genuinely needs them.\n *\n * This module does not simplify. Call `simplifySymbolic()` first for a\n * canonical, minimal rendering.\n */\n\nimport type { SymbolicNode } from \"@solve-js/symbolic/SymbolicNode\";\nimport { type Rational, formatRational } from \"@solve-js/symbolic/Rational\";\nimport { formatComplex } from \"@solve-js/symbolic/Complex\";\n\n/** Extracts `{coeff, name}` from a `const*var` or `var*const` shape, or `null` when `node` is not one. */\nfunction tryExtractCoeffVar(node: SymbolicNode & { kind: \"mul\" }): { coeff: Rational; name: string } | null {\n\tif (node.left.kind === \"const\" && node.right.kind === \"var\") return { coeff: node.left.value, name: node.right.name };\n\tif (node.right.kind === \"const\" && node.left.kind === \"var\") return { coeff: node.right.value, name: node.left.name };\n\treturn null;\n}\n\n/** Extracts `{coeff, power}` from a `const*pow` or `pow*const` shape, so `2x^2` renders without an asterisk. */\nfunction tryExtractCoeffPow(node: SymbolicNode & { kind: \"mul\" }): { coeff: Rational; power: SymbolicNode } | null {\n\tif (node.left.kind === \"const\" && node.right.kind === \"pow\") return { coeff: node.left.value, power: node.right };\n\tif (node.right.kind === \"const\" && node.left.kind === \"pow\") return { coeff: node.right.value, power: node.left };\n\treturn null;\n}\n\n/** Whether a node renders as a single indivisible token, so an exponent can follow it without parentheses. */\nfunction isAtomic(node: SymbolicNode): boolean {\n\tif (node.kind === \"var\" || node.kind === \"call\") return true;\n\t// A negative constant needs brackets under an exponent: `-2^2` parses as\n\t// `-(2^2)`, which is a different value from `(-2)^2`.\n\treturn node.kind === \"const\" && node.value.n >= 0n;\n}\n\n/** Renders `coeff` immediately followed by `text`, collapsing the 1 and -1 cases the way a person writes them. */\nfunction formatCoefficient(coeff: Rational, text: string): string {\n\tif (coeff.n === 1n && coeff.d === 1n) return text;\n\tif (coeff.n === -1n && coeff.d === 1n) return `-${text}`;\n\treturn `${formatRational(coeff)}${text}`;\n}\n\n/**\n * How deep the printer will walk before eliding the rest.\n *\n * This walk and {@link collectDisplayTerms} call each other down the tree with\n * nothing counting the levels, so the native stack was the only bound on\n * either, and it is reached at about 1,170 levels (measured, three frames per\n * level). `SYMBOLIC_MAX_NODES` admits ten thousand nodes, and for a chain size\n * and depth are the same number, so there was a wide band of trees the engine\n * called legal and could not print. What came out of that band was a raw\n * `RangeError` reading \"Maximum call stack size exceeded\", from `formatValue()`\n * of all places, which is the one call a host makes to render an answer it has\n * already been given and therefore the one it is least likely to have wrapped\n * in a `try`.\n *\n * About half the measured limit rather than the quarter that would be\n * comfortable, because an expression five hundred levels deep must still print\n * in full (pinned in `__tests__/hardening/DenialOfServiceRecursionDepth.spec.ts`)\n * and a printer that elides what it can render is its own kind of wrong answer.\n * {@link formatSymbolic} therefore also catches the overflow itself, so the\n * margin being wrong somewhere with less stack to spare degrades the display\n * rather than escaping as a RangeError.\n *\n * Eliding rather than throwing, because the caller asked to display a value and\n * an ellipsis is a display. It is also honest in a way silent truncation would\n * not be: the marker says the text is not the whole tree.\n */\nconst MAX_FORMAT_DEPTH = 600;\n\n/** What stands in for the part of a tree too deep to print. */\nconst ELIDED = \"...\";\n\n/**\n * Formats a factor, wrapping a nested sum in parentheses, which is needed\n * whenever it appears inside a `mul`, `div`, `neg` or `pow`.\n */\nfunction formatFactor(node: SymbolicNode, depth: number): string {\n\tif (depth >= MAX_FORMAT_DEPTH) return ELIDED;\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\t\treturn formatRational(node.value);\n\t\tcase \"complex\":\n\t\t\t// Only a value with BOTH parts is a sum, and only a sum needs brackets\n\t\t\t// inside a product: `(2+3i)*x` but `sqrt(2)*i`. Bracketing every\n\t\t\t// complex would make the common imaginary-only case read as `(i)`.\n\t\t\treturn node.value.re.n !== 0n && node.value.im.n !== 0n\n\t\t\t\t? `(${formatComplex(node.value)})`\n\t\t\t\t: formatComplex(node.value);\n\t\tcase \"var\":\n\t\t\treturn node.name;\n\t\tcase \"add\":\n\t\tcase \"sub\":\n\t\t\t// Not `depth + 1`: this hands the SAME node to the sum printer, and\n\t\t\t// the counter has to measure tree levels rather than call frames, or\n\t\t\t// a five-hundred-level expression would be elided at two hundred and\n\t\t\t// fifty. Every other recursion below descends into a child, and\n\t\t\t// those do count.\n\t\t\treturn `(${formatSum(node, depth)})`;\n\t\tcase \"neg\":\n\t\t\treturn `-${formatFactor(node.operand, depth + 1)}`;\n\t\tcase \"call\":\n\t\t\t// Written as an arrow rather than passing `formatSum` to `map`\n\t\t\t// directly: `map` calls its callback with the index as a second\n\t\t\t// argument, which would arrive here as the depth.\n\t\t\treturn `${node.name}(${node.args.map(arg => formatSum(arg, depth + 1)).join(\", \")})`;\n\t\tcase \"pow\": {\n\t\t\tconst base = isAtomic(node.base) ? formatFactor(node.base, depth + 1) : `(${formatSum(node.base, depth + 1)})`;\n\t\t\t// An exponent that is itself compound needs brackets, since `x^n+1`\n\t\t\t// would otherwise read as `(x^n)+1`.\n\t\t\tconst exponent = isAtomic(node.exponent) ? formatFactor(node.exponent, depth + 1) : `(${formatSum(node.exponent, depth + 1)})`;\n\t\t\treturn `${base}^${exponent}`;\n\t\t}\n\t\tcase \"mul\": {\n\t\t\tconst coeffVar = tryExtractCoeffVar(node);\n\t\t\tif (coeffVar) return formatCoefficient(coeffVar.coeff, coeffVar.name);\n\t\t\tconst coeffPow = tryExtractCoeffPow(node);\n\t\t\tif (coeffPow) return formatCoefficient(coeffPow.coeff, formatFactor(coeffPow.power, depth + 1));\n\t\t\t// A coefficient on a longer monomial juxtaposes too, so `2*x*y`\n\t\t\t// renders `2x*y`, consistent with `2b` and `2x^2` above. Only the\n\t\t\t// leading coefficient collapses; the `*` between distinct variables\n\t\t\t// stays, matching how the rest of the engine writes products.\n\t\t\t//\n\t\t\t// The digit guard is not cosmetic. Juxtaposing onto text that itself\n\t\t\t// starts with a digit produces a different number: `3*(2*x)` would\n\t\t\t// render as `32x`, which reads as thirty-two x. Such a shape should\n\t\t\t// have been folded to `6x` by the simplifier, so this is a safety net\n\t\t\t// rather than the normal path, but a formatter must never be able to\n\t\t\t// print one value as another.\n\t\t\tif (node.left.kind === \"const\" && node.right.kind === \"mul\") {\n\t\t\t\tconst inner = formatFactor(node.right, depth + 1);\n\t\t\t\tif (!/^[\\d.]/.test(inner)) return formatCoefficient(node.left.value, inner);\n\t\t\t}\n\t\t\treturn `${formatFactor(node.left, depth + 1)}*${formatFactor(node.right, depth + 1)}`;\n\t\t}\n\t\tcase \"div\": {\n\t\t\t// A denominator that is itself a product or a quotient must be\n\t\t\t// bracketed. Without this, `1/(2*sqrt(x))` prints as `1/2*sqrt(x)`,\n\t\t\t// which reads back as `(1/2)*sqrt(x)`, a different number: at x=9 the\n\t\t\t// tree is 1/6 and the text says 1.5. `a/(b/c)` had the same problem,\n\t\t\t// printing `a/b/c`, which regroups left-to-right into `(a/b)/c`.\n\t\t\t// A sum or difference is already bracketed by formatFactor itself, and\n\t\t\t// a power binds tighter than division so `1/x^2` needs nothing.\n\t\t\tconst denominator = formatFactor(node.right, depth + 1);\n\t\t\tconst needsBrackets = node.right.kind === \"mul\" || node.right.kind === \"div\";\n\t\t\treturn `${formatFactor(node.left, depth + 1)}/${needsBrackets ? `(${denominator})` : denominator}`;\n\t\t}\n\t}\n}\n\n/**\n * Collects a possibly-unsimplified `add`/`sub`/`neg` chain into signed display\n * terms. Mirrors the simplifier's own `flattenSum` traversal, but tolerant:\n * a `mul`/`div`/`pow`/`call` subtree becomes one opaque signed term via\n * {@link formatFactor} rather than aborting the whole walk.\n */\nfunction collectDisplayTerms(node: SymbolicNode, negated: boolean, out: { negated: boolean; text: string }[], depth: number): void {\n\tif (depth >= MAX_FORMAT_DEPTH) {\n\t\tout.push({ negated, text: ELIDED });\n\t\treturn;\n\t}\n\tswitch (node.kind) {\n\t\tcase \"add\":\n\t\t\tcollectDisplayTerms(node.left, negated, out, depth + 1);\n\t\t\tcollectDisplayTerms(node.right, negated, out, depth + 1);\n\t\t\treturn;\n\t\tcase \"sub\":\n\t\t\tcollectDisplayTerms(node.left, negated, out, depth + 1);\n\t\t\tcollectDisplayTerms(node.right, !negated, out, depth + 1);\n\t\t\treturn;\n\t\tcase \"neg\":\n\t\t\tcollectDisplayTerms(node.operand, !negated, out, depth + 1);\n\t\t\treturn;\n\t\tcase \"const\": {\n\t\t\t// An embedded zero term contributes nothing to the display.\n\t\t\tif (node.value.n === 0n) return;\n\t\t\tconst isNegative = node.value.n < 0n;\n\t\t\tconst magnitude = isNegative ? { n: -node.value.n, d: node.value.d } : node.value;\n\t\t\tout.push({ negated: isNegative !== negated, text: formatRational(magnitude) });\n\t\t\treturn;\n\t\t}\n\t\tcase \"complex\": {\n\t\t\t// Split into two display terms so a complex at the top level joins the\n\t\t\t// surrounding sum naturally: `2+3i` and `-1-2i` rather than a single\n\t\t\t// bracketed blob. The bracketing in formatFactor is for when a complex\n\t\t\t// sits inside a product, where it genuinely needs it.\n\t\t\tconst { re, im } = node.value;\n\t\t\tif (re.n !== 0n) {\n\t\t\t\tconst negativeReal = re.n < 0n;\n\t\t\t\tout.push({ negated: negativeReal !== negated, text: formatRational(negativeReal ? { n: -re.n, d: re.d } : re) });\n\t\t\t}\n\t\t\tif (im.n !== 0n) {\n\t\t\t\tconst negativeImaginary = im.n < 0n;\n\t\t\t\tconst magnitude = negativeImaginary ? { n: -im.n, d: im.d } : im;\n\t\t\t\tconst text = magnitude.n === 1n && magnitude.d === 1n ? \"i\" : `${formatRational(magnitude)}i`;\n\t\t\t\tout.push({ negated: negativeImaginary !== negated, text });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tdefault: {\n\t\t\t// Same node, so same depth. See formatFactor's add/sub case.\n\t\t\tconst text = formatFactor(node, depth);\n\t\t\t// A product or quotient whose leading coefficient is negative renders\n\t\t\t// with the minus already inside it, and joining that to a sum with `+`\n\t\t\t// gives `0.5*log(x-1)+-0.5*log(x+1)`. Lifting the sign out turns it back\n\t\t\t// into the subtraction it is. Only these two kinds: for a `pow` a leading\n\t\t\t// minus belongs to the base rather than to the whole factor, so `-2^2`\n\t\t\t// must not become a subtracted `2^2`.\n\t\t\tconst liftsSign = (node.kind === \"mul\" || node.kind === \"div\") && text.startsWith(\"-\");\n\t\t\tif (liftsSign) out.push({ negated: !negated, text: text.slice(1) });\n\t\t\telse out.push({ negated, text });\n\t\t}\n\t}\n}\n\n/**\n * Renders a symbolic expression as display text.\n *\n * @param node - The tree to render.\n * @returns The display string. An expression whose terms all cancel renders as\n * `\"0\"` rather than as an empty string.\n */\nexport function formatSymbolic(node: SymbolicNode): string {\n\ttry {\n\t\treturn formatSum(node, 0);\n\t} catch (thrown) {\n\t\t// The depth guard above is what normally stops this, and this is the\n\t\t// backstop for it being set half a stack away from the native limit: a\n\t\t// caller that has already spent stack of its own can run out inside a\n\t\t// tree the guard would have allowed. A stack overflow is a RangeError\n\t\t// rather than an EngineError, so a host cannot tell it from a bug in its\n\t\t// own code, and it arrives through `formatValue()`, which is a request\n\t\t// to display an answer and has no business throwing. Nothing else is\n\t\t// swallowed: any other error is the caller's to see.\n\t\tif (thrown instanceof RangeError) return ELIDED;\n\t\tthrow thrown;\n\t}\n}\n\n/**\n * The body of {@link formatSymbolic}, carrying how deep the walk already is.\n *\n * Split out so the public entry point keeps its one-argument signature: it is\n * exported, and a second parameter on it would be filled in by anything that\n * passes it to `Array.prototype.map`.\n */\nfunction formatSum(node: SymbolicNode, depth: number): string {\n\tconst terms: { negated: boolean; text: string }[] = [];\n\tcollectDisplayTerms(node, false, terms, depth);\n\tif (terms.length === 0) return \"0\";\n\n\tlet out = \"\";\n\tterms.forEach((term, index) => {\n\t\tif (index === 0) out += term.negated ? `-${term.text}` : term.text;\n\t\telse out += term.negated ? `-${term.text}` : `+${term.text}`;\n\t});\n\treturn out;\n}\n","import { type MatrixData, type MatrixEntry, type RangeData, Value, ValueType, matrixValue, numberValue, boolValue, symbolicValue, errorValue, faultedOperand } from \"@solve-js/vm/Value\";\nimport { type SymbolicNode, constNode, simplifySymbolic, isRationalZero, rationalToNumber } from \"@solve-js/symbolic\";\nimport { checkedArray } from \"@solve-js/vm/AllocationBudget\";\n\n/**\n * Shared, pure helpers for reading/building {@link MatrixData}. Kept\n * separate from `VM.ts`'s opcode dispatch and `VMConversion.ts`'s\n * `binaryOp()` so every consumer (arithmetic, indexing, transpose/inverse,\n * map/reduce) reads/writes matrix storage through the same column-major\n * convention rather than each re-deriving the row/col math independently.\n */\n\n/** Column-major single-index read, `a[i]` in the spec's own notation. */\nexport function matIndex(m: MatrixData, index: number): MatrixEntry {\n\treturn m.data[index];\n}\n\n/** `[row, col]` read (both 0-based), via the column-major storage formula `row + col*rows`. */\nexport function matAt(m: MatrixData, row: number, col: number): MatrixEntry {\n\treturn m.data[row + col * m.rows];\n}\n\n/** Whether `[row, col]` is a valid cell for `m`. */\nexport function inBounds(m: MatrixData, row: number, col: number): boolean {\n\treturn row >= 0 && row < m.rows && col >= 0 && col < m.cols;\n}\n\n/**\n * Whether two matrices have identical dimensions.\n *\n * @param a - First matrix.\n * @param b - Second matrix.\n * @returns True when rows and columns both match, which is the precondition\n * for every element-wise operation.\n */\nexport function sameShape(a: MatrixData, b: MatrixData): boolean {\n\treturn a.rows === b.rows && a.cols === b.cols;\n}\n\n/**\n * Whether a matrix has as many rows as columns.\n *\n * @param m - The matrix.\n * @returns True when square. Determinant and inverse are defined only here.\n */\nexport function isSquare(m: MatrixData): boolean {\n\treturn m.rows === m.cols;\n}\n\n/** Converts a matrix cell into a SymbolicNode, its own tree if already symbolic, else a `const` node (boolean coerced to 0/1). */\nexport function entryToSymbolic(entry: MatrixEntry): SymbolicNode {\n\tif (typeof entry === \"object\" && entry !== null) return entry;\n\tif (typeof entry === \"boolean\") return constNode(entry ? 1 : 0);\n\treturn constNode(entry);\n}\n\n/** Collapses a simplified SymbolicNode back to a plain number when it's a pure constant, keeps matrix cells in their simplest representation rather than always carrying a wrapped tree. */\nexport function symbolicToEntry(node: SymbolicNode): MatrixEntry {\n\tconst simplified = simplifySymbolic(node);\n\t// Collapse to a plain number, never to the Rational itself. MatrixEntry is\n\t// `number | boolean | SymbolicNode`, and a leaked Rational would satisfy the\n\t// `typeof cell === \"object\"` test that FormatEngine.ts and Value.ts use to\n\t// recognise a symbolic cell, rendering as garbage rather than throwing.\n\treturn simplified.kind === \"const\" ? rationalToNumber(simplified.value) : simplified;\n}\n\n/** Converts a matrix cell into a real Value, Boolean/Symbolic preserved as-is, plain numbers wrapped via numberValue(). Used anywhere a cell needs to leave MatrixData and become an ordinary VM value (indexing, map/reduce collection iteration). */\nexport function matrixEntryToValue(cell: MatrixEntry): Value {\n\tif (typeof cell === \"boolean\") return boolValue(cell);\n\tif (typeof cell === \"object\" && cell !== null) return symbolicValue(cell);\n\treturn numberValue(cell);\n}\n\n/**\n * A matrix literal is naturally written and parsed row-major (`[1,2;3,4]`\n * reads row 0 then row 1), but {@link MatrixData.data} is stored\n * column-major (matching the spec's own `a[index]` semantics directly).\n * This is the one place that translation happens, every other consumer\n * of `MatrixData` just reads/writes column-major storage directly.\n */\nexport function rowMajorToColumnMajor(rows: number, cols: number, rowMajorData: readonly MatrixEntry[]): MatrixEntry[] {\n\tconst data = new Array<MatrixEntry>(rows * cols);\n\tfor (let r = 0; r < rows; r++) {\n\t\tfor (let c = 0; c < cols; c++) {\n\t\t\tdata[r + c * rows] = rowMajorData[r * cols + c];\n\t\t}\n\t}\n\treturn data;\n}\n\n/** Inverse of {@link rowMajorToColumnMajor}, used by display code, which reads back out row-by-row. */\nexport function columnMajorToRowMajor(m: MatrixData): MatrixEntry[] {\n\tconst data = new Array<MatrixEntry>(m.rows * m.cols);\n\tfor (let r = 0; r < m.rows; r++) {\n\t\tfor (let c = 0; c < m.cols; c++) {\n\t\t\tdata[r * m.cols + c] = matAt(m, r, c);\n\t\t}\n\t}\n\treturn data;\n}\n\n/**\n * `*` between two matrices, genuinely different from `+`/`-`/comparisons\n * which stay element-wise. Distinguishes three cases per the Calca spec:\n * a `1×1` operand (\"scalar\") broadcasts (multiplies every cell of the\n * other operand); otherwise, if the inner dimensions agree\n * (`l.cols === r.rows`), this is a real `(m×n)*(n×p)=(m×p)` matrix\n * product; anything else is a dimension mismatch. Called from VM.ts's MUL\n * case BEFORE falling through to the always-element-wise `binaryOp()`\n * `binaryOp()` itself never disambiguates multiplication this way.\n *\n * Symbolic-aware: when either operand `hasSymbolic`, every cell is\n * computed via `SymbolicNode` add/multiply + simplify instead of plain\n * `number` arithmetic, the ordinary numeric fast path only runs when\n * NEITHER operand carries any symbolic cell.\n *\n * The result array is asked for through `checkedArray()` rather than taken\n * with a bare `new Array`, because this is the one arithmetic result whose\n * size is the PRODUCT of two separately affordable operands, and the tally in\n * `vm/AllocationBudget.ts` cannot refuse an allocation that has already\n * happened. `OpCode.MUL` checks the same number before calling here, which is\n * a duplicate check and not a duplicate charge (`checkAllocation` refuses\n * without recording, deliberately). The check lives here as well because MUL\n * is not the only way in: `dot()` is this same multiplication reached through\n * `CALL_BUILTIN`, and `abs`, `det`, `inv` and `pow` reach it too, and every\n * one of those used to arrive at a bare `new Array(rows * cols)`. Four hundred\n * million cells through `dot()` aborted the process in 1.3 seconds while the\n * `*` spelling of the identical product was refused in 18 milliseconds.\n */\nexport function matrixMultiply(l: MatrixData, r: MatrixData): Value {\n\tconst lIsScalar = l.rows === 1 && l.cols === 1;\n\tconst rIsScalar = r.rows === 1 && r.cols === 1;\n\tconst useSymbolic = l.hasSymbolic || r.hasSymbolic;\n\n\tif (lIsScalar || rIsScalar) {\n\t\tconst [scalarOperand, matrixOperand] = lIsScalar ? [l, r] : [r, l];\n\t\tif (useSymbolic) {\n\t\t\tconst scalarNode = entryToSymbolic(scalarOperand.data[0]);\n\t\t\tconst result = matrixOperand.data.map(v => symbolicToEntry(simplifySymbolic({ kind: \"mul\", left: entryToSymbolic(v), right: scalarNode })));\n\t\t\treturn matrixValue(matrixOperand.rows, matrixOperand.cols, result);\n\t\t}\n\t\tconst scalar = scalarOperand.data[0] as number;\n\t\tconst result = matrixOperand.data.map(v => (v as number) * scalar);\n\t\treturn matrixValue(matrixOperand.rows, matrixOperand.cols, result);\n\t}\n\n\tif (l.cols !== r.rows) {\n\t\treturn errorValue(\n\t\t\t\"DIMENSION_MISMATCH\",\n\t\t\t`Cannot multiply a ${l.rows}x${l.cols} matrix by a ${r.rows}x${r.cols} matrix — inner dimensions must match (${l.cols} !== ${r.rows}).`,\n\t\t);\n\t}\n\n\tconst resultRows = l.rows;\n\tconst resultCols = r.cols;\n\tconst data = checkedArray<MatrixEntry>(resultRows * resultCols, \"matrix cells\");\n\tfor (let row = 0; row < resultRows; row++) {\n\t\tfor (let col = 0; col < resultCols; col++) {\n\t\t\tif (useSymbolic) {\n\t\t\t\tlet acc: SymbolicNode = constNode(0);\n\t\t\t\tfor (let k = 0; k < l.cols; k++) {\n\t\t\t\t\tconst term: SymbolicNode = { kind: \"mul\", left: entryToSymbolic(matAt(l, row, k)), right: entryToSymbolic(matAt(r, k, col)) };\n\t\t\t\t\tacc = simplifySymbolic({ kind: \"add\", left: acc, right: term });\n\t\t\t\t}\n\t\t\t\tdata[row + col * resultRows] = symbolicToEntry(acc);\n\t\t\t} else {\n\t\t\t\tlet sum = 0;\n\t\t\t\tfor (let k = 0; k < l.cols; k++) {\n\t\t\t\t\tsum += (matAt(l, row, k) as number) * (matAt(r, k, col) as number);\n\t\t\t\t}\n\t\t\t\tdata[row + col * resultRows] = sum;\n\t\t\t}\n\t\t}\n\t}\n\treturn matrixValue(resultRows, resultCols, data);\n}\n\n/**\n * `a^k` for a square matrix and a whole, non-negative `k`, by repeated\n * multiplication.\n *\n * Matrix power is repeated matrix multiplication, not the element-wise\n * `Math.pow` the `^` operator otherwise means, so this cannot go through\n * `binaryOp()`. `k = 0` is the identity, which is what makes the whole thing\n * consistent: `a^0 * a^n` is `a^n` for every n.\n *\n * Squaring rather than multiplying one factor at a time keeps `a^1000000`\n * to twenty multiplications instead of a million, so a large exponent is\n * slow arithmetic rather than a hung editor. Symbolic cells ride along for\n * free, since {@link matrixMultiply} already handles them.\n *\n * A non-square matrix, or an exponent that is negative or fractional, is\n * refused rather than answered: `a^-1` is spelled that way and is taken by\n * the parser's own caret-suffix rule (see `parser/PrecedenceParser.ts`), and\n * a fractional matrix power is a genuinely different problem (a matrix\n * square root need not exist, and need not be unique when it does).\n *\n * @param m - The base.\n * @param exponent - The power, which must be a non-negative integer.\n * @returns The resulting Matrix, or an error Value describing the refusal.\n */\nexport function matrixPower(m: MatrixData, exponent: number): Value {\n\tif (!isSquare(m)) {\n\t\treturn errorValue(\"MATRIX_POWER_REQUIRES_SQUARE_MATRIX\", `^: only a square matrix can be raised to a power (got ${m.rows}x${m.cols}).`);\n\t}\n\tif (!Number.isInteger(exponent) || exponent < 0) {\n\t\treturn errorValue(\n\t\t\t\"MATRIX_POWER_REQUIRES_WHOLE_EXPONENT\",\n\t\t\t`^: a matrix can only be raised to a whole number of 0 or more (got ${exponent}); \"^-1\" means the inverse and \"^T\" the transpose.`,\n\t\t);\n\t}\n\tconst n = m.rows;\n\tconst identity = new Array<MatrixEntry>(n * n).fill(0);\n\tfor (let i = 0; i < n; i++) identity[i + i * n] = 1;\n\tlet accumulated: MatrixData = { rows: n, cols: n, data: identity, hasSymbolic: false };\n\tlet squared = m;\n\tlet remaining = exponent;\n\twhile (remaining > 0) {\n\t\tif (remaining % 2 === 1) {\n\t\t\tconst product = matrixMultiply(accumulated, squared);\n\t\t\tif (product.type === ValueType.Error) return product;\n\t\t\taccumulated = product.value as MatrixData;\n\t\t}\n\t\tremaining = Math.floor(remaining / 2);\n\t\tif (remaining > 0) {\n\t\t\tconst doubled = matrixMultiply(squared, squared);\n\t\t\tif (doubled.type === ValueType.Error) return doubled;\n\t\t\tsquared = doubled.value as MatrixData;\n\t\t}\n\t}\n\t// Rebuilt through matrixValue() so the result carries a correctly\n\t// recomputed `hasSymbolic`, rather than the identity's own `false`.\n\treturn matrixValue(accumulated.rows, accumulated.cols, accumulated.data);\n}\n\n/**\n * Element-wise comparison, `[1,6;3,8] < [5,2;7,4] => [true,false;true,false]`.\n * Unlike arithmetic, comparison NEVER does matrix-vs-matrix \"real\" dispatch\n * (there's no such thing as a \"comparison product\"), always element-wise\n * same shape required, producing a Matrix of booleans.\n *\n * NOT symbolic-aware, comparing a free-variable formula's ordering has no\n * general meaning without knowing its value (is `sx < 5`? unknowable), and\n * no spec example compares two symbolic matrices, a disclosed, narrow gap\n * rather than attempted-and-wrong.\n */\nexport function matrixCompare(l: MatrixData, r: MatrixData, cmp: (a: number, b: number) => boolean): Value {\n\tif (!sameShape(l, r)) {\n\t\treturn errorValue(\n\t\t\t\"DIMENSION_MISMATCH\",\n\t\t\t`Cannot compare matrices of different shapes: ${l.rows}x${l.cols} and ${r.rows}x${r.cols}`,\n\t\t);\n\t}\n\tconst data: MatrixEntry[] = new Array(l.data.length);\n\tfor (let i = 0; i < l.data.length; i++) data[i] = cmp(l.data[i] as number, r.data[i] as number);\n\treturn matrixValue(l.rows, l.cols, data);\n}\n\n/** `a^T`, swaps rows/cols; cell `[r,c]` in the result is cell `[c,r]` in `m`. Cell-type-agnostic (just rearranges), so this needs no symbolic-aware variant. */\nexport function transpose(m: MatrixData): Value {\n\tconst data = new Array<MatrixEntry>(m.rows * m.cols);\n\tfor (let r = 0; r < m.cols; r++) {\n\t\tfor (let c = 0; c < m.rows; c++) {\n\t\t\tdata[r + c * m.cols] = matAt(m, c, r);\n\t\t}\n\t}\n\treturn matrixValue(m.cols, m.rows, data);\n}\n\n/**\n * Copies `m` into a plain row-major `number[][]` working copy for\n * elimination, {@link numericDeterminant}/{@link numericInverse} both\n * mutate their own copy in place rather than touching `m.data` (which\n * callers may still hold a reference to elsewhere).\n */\nfunction toWorkingRows(m: MatrixData): number[][] {\n\tconst rows: number[][] = [];\n\tfor (let r = 0; r < m.rows; r++) {\n\t\tconst row: number[] = [];\n\t\tfor (let c = 0; c < m.cols; c++) row.push(matAt(m, r, c) as number);\n\t\trows.push(row);\n\t}\n\treturn rows;\n}\n\n/**\n * Largest matrix {@link integerDeterminant} will attempt.\n *\n * Bareiss keeps every intermediate a minor of the original matrix, so the\n * bigints stay bounded by Hadamard's inequality rather than growing without\n * limit. What this bounds is the cubic loop itself, and it follows the\n * precedent of {@link SYMBOLIC_INVERSE_DIMENSION_LIMIT}: a named ceiling with\n * a stated reason rather than an arbitrary inline number. A larger matrix\n * still gets an answer, from the elimination below.\n */\nconst EXACT_DETERMINANT_DIMENSION_LIMIT = 12;\n\n/**\n * Every cell as an exact bigint, or `null` when the matrix is not wholly\n * integral.\n *\n * Booleans are excluded rather than coerced, so a matrix of comparison results\n * keeps whatever the elimination has always made of it.\n */\nfunction toIntegerRows(m: MatrixData): bigint[][] | null {\n\tif (m.rows > EXACT_DETERMINANT_DIMENSION_LIMIT) return null;\n\tconst rows: bigint[][] = [];\n\tfor (let r = 0; r < m.rows; r++) {\n\t\tconst row: bigint[] = [];\n\t\tfor (let c = 0; c < m.cols; c++) {\n\t\t\tconst cell = matAt(m, r, c);\n\t\t\tif (typeof cell !== \"number\" || !Number.isSafeInteger(cell)) return null;\n\t\t\trow.push(BigInt(cell));\n\t\t}\n\t\trows.push(row);\n\t}\n\treturn rows;\n}\n\n/**\n * The determinant of an integer matrix, exactly, by Bareiss's fraction-free\n * elimination.\n *\n * Ordinary elimination divides by the pivot at every step, and those divisions\n * are what leave `det([1,2,3;4,5,6;7,8,9])` reading `6.661338147750939e-16`\n * instead of the zero it is. The matrix is singular, and \"very nearly zero\" is\n * not a different answer from zero, it is the same answer with the reader left\n * to decide. Bareiss divides by the **previous** pivot instead, and that\n * division is exactly divisible as a theorem, so every intermediate stays a\n * whole number and a singular matrix comes out as an exact `0n`.\n *\n * @param rows - The matrix, row-major, which this mutates as its working copy.\n * @returns The determinant.\n */\nfunction integerDeterminant(rows: bigint[][]): bigint {\n\tconst n = rows.length;\n\tlet previous = 1n;\n\tlet sign = 1n;\n\n\tfor (let k = 0; k < n - 1; k++) {\n\t\tif (rows[k][k] === 0n) {\n\t\t\tlet candidate = -1;\n\t\t\tfor (let r = k + 1; r < n; r++) {\n\t\t\t\tif (rows[r][k] !== 0n) {\n\t\t\t\t\tcandidate = r;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// No pivot anywhere in the column means a zero column below k, so the\n\t\t\t// matrix is singular and its determinant is exactly zero.\n\t\t\tif (candidate === -1) return 0n;\n\t\t\tconst swapped = rows[k];\n\t\t\trows[k] = rows[candidate];\n\t\t\trows[candidate] = swapped;\n\t\t\tsign = -sign;\n\t\t}\n\t\tfor (let i = k + 1; i < n; i++) {\n\t\t\tfor (let j = k + 1; j < n; j++) {\n\t\t\t\trows[i][j] = (rows[i][j] * rows[k][k] - rows[i][k] * rows[k][j]) / previous;\n\t\t\t}\n\t\t}\n\t\tprevious = rows[k][k];\n\t}\n\treturn sign * rows[n - 1][n - 1];\n}\n\n/**\n * `|a|` / `det(a)`, exactly when every cell is a whole number, and otherwise by\n * Gaussian elimination with partial pivoting, reusing the elimination's own\n * running pivot product as the determinant (rather than a separate\n * cofactor-expansion implementation). A row swap flips the product's sign,\n * matching the standard determinant-under-row-swap identity. A zero pivot\n * column (no non-zero candidate at or below it) means the matrix is singular,\n * determinant 0, not an error, since 0 is the mathematically correct answer for\n * a singular matrix.\n *\n * The integer route is tried first because an integer matrix has an integer\n * determinant, and a method that cannot return one is answering a question\n * nobody asked. See {@link integerDeterminant}.\n */\nfunction numericDeterminant(m: MatrixData): Value {\n\tconst integers = toIntegerRows(m);\n\tif (integers !== null) return numberValue(Number(integerDeterminant(integers)));\n\n\tconst n = m.rows;\n\tconst a = toWorkingRows(m);\n\tlet det = 1;\n\tfor (let col = 0; col < n; col++) {\n\t\tlet pivotRow = col;\n\t\tlet maxAbs = Math.abs(a[col][col]);\n\t\tfor (let r = col + 1; r < n; r++) {\n\t\t\tif (Math.abs(a[r][col]) > maxAbs) { maxAbs = Math.abs(a[r][col]); pivotRow = r; }\n\t\t}\n\t\tif (maxAbs === 0) return numberValue(0);\n\t\tif (pivotRow !== col) {\n\t\t\tconst tmp = a[col]; a[col] = a[pivotRow]; a[pivotRow] = tmp;\n\t\t\tdet = -det;\n\t\t}\n\t\tdet *= a[col][col];\n\t\tfor (let r = col + 1; r < n; r++) {\n\t\t\tconst factor = a[r][col] / a[col][col];\n\t\t\tif (factor === 0) continue;\n\t\t\tfor (let c = col; c < n; c++) a[r][c] -= factor * a[col][c];\n\t\t}\n\t}\n\treturn numberValue(det);\n}\n\n/**\n * Symbolic determinant, SAME diagonal-first, NO-row-swap elimination\n * strategy as {@link symbolicInverse} (see its own doc comment for why:\n * row-swapping under free-variable pivots has no general \"is this bigger\"\n * ordering to search by). A pivot that simplifies to the exact constant\n * `0` yields determinant `0` (mathematically correct for a genuinely\n * singular structure); anything else, including a pivot that's an\n * unresolved formula which MIGHT be zero for some assignment, is treated\n * as non-zero and elimination proceeds. This is a disclosed limitation,\n * not full symbolic zero-detection (out of scope, \"not a general CAS\").\n */\nfunction symbolicDeterminant(m: MatrixData): Value {\n\tconst n = m.rows;\n\tconst a: SymbolicNode[][] = [];\n\tfor (let r = 0; r < n; r++) {\n\t\tconst row: SymbolicNode[] = [];\n\t\tfor (let c = 0; c < n; c++) row.push(entryToSymbolic(matAt(m, r, c)));\n\t\ta.push(row);\n\t}\n\tlet det: SymbolicNode = constNode(1);\n\tfor (let col = 0; col < n; col++) {\n\t\tconst pivot = simplifySymbolic(a[col][col]);\n\t\t// Exact, unlike the previous double comparison: a structurally-zero pivot\n\t\t// could arrive as 5.551e-17 and be treated as non-zero, so a singular\n\t\t// matrix reported a nonsense determinant instead of zero.\n\t\tif (pivot.kind === \"const\" && isRationalZero(pivot.value)) return numberValue(0);\n\t\tdet = simplifySymbolic({ kind: \"mul\", left: det, right: pivot });\n\t\tfor (let r = col + 1; r < n; r++) {\n\t\t\tconst factor = simplifySymbolic({ kind: \"div\", left: a[r][col], right: pivot });\n\t\t\tfor (let c = col; c < n; c++) {\n\t\t\t\ta[r][c] = simplifySymbolic({ kind: \"sub\", left: a[r][c], right: { kind: \"mul\", left: factor, right: a[col][c] } });\n\t\t\t}\n\t\t}\n\t}\n\treturn det.kind === \"const\" ? numberValue(rationalToNumber(det.value)) : symbolicValue(det);\n}\n\n/** `|a|` / `det(a)`, dispatches to the symbolic or plain-numeric implementation based on `m.hasSymbolic`. */\nexport function determinant(m: MatrixData): Value {\n\tif (!isSquare(m)) {\n\t\treturn errorValue(\"DETERMINANT_REQUIRES_SQUARE_MATRIX\", `det: matrix must be square (got ${m.rows}x${m.cols}).`);\n\t}\n\treturn m.hasSymbolic ? symbolicDeterminant(m) : numericDeterminant(m);\n}\n\n/**\n * `a^-1` / `inv(a)`, Gauss-Jordan elimination with partial pivoting on\n * the augmented `[A | I]` matrix, reducing the left half to the identity\n * while the right half becomes `A`'s inverse. Requires a square, non-\n * singular matrix, a near-zero pivot (below `1e-10`, guarding against\n * floating-point noise rather than requiring an exact zero) means the\n * matrix isn't invertible, reported as a clear error rather than\n * returning `Infinity`-poisoned cells.\n */\nfunction numericInverse(m: MatrixData): Value {\n\tconst n = m.rows;\n\tconst a = toWorkingRows(m);\n\tfor (let r = 0; r < n; r++) {\n\t\tfor (let c = 0; c < n; c++) a[r].push(c === r ? 1 : 0);\n\t}\n\tfor (let col = 0; col < n; col++) {\n\t\tlet pivotRow = col;\n\t\tlet maxAbs = Math.abs(a[col][col]);\n\t\tfor (let r = col + 1; r < n; r++) {\n\t\t\tif (Math.abs(a[r][col]) > maxAbs) { maxAbs = Math.abs(a[r][col]); pivotRow = r; }\n\t\t}\n\t\tif (maxAbs < 1e-10) {\n\t\t\treturn errorValue(\"SINGULAR_MATRIX\", `inv: a ${n}x${n} matrix with a zero (or near-zero) pivot column is not invertible.`);\n\t\t}\n\t\tif (pivotRow !== col) {\n\t\t\tconst tmp = a[col]; a[col] = a[pivotRow]; a[pivotRow] = tmp;\n\t\t}\n\t\tconst pivot = a[col][col];\n\t\tfor (let c = 0; c < 2 * n; c++) a[col][c] /= pivot;\n\t\tfor (let r = 0; r < n; r++) {\n\t\t\tif (r === col) continue;\n\t\t\tconst factor = a[r][col];\n\t\t\tif (factor === 0) continue;\n\t\t\tfor (let c = 0; c < 2 * n; c++) a[r][c] -= factor * a[col][c];\n\t\t}\n\t}\n\tconst data = new Array<MatrixEntry>(n * n);\n\tfor (let r = 0; r < n; r++) {\n\t\tfor (let c = 0; c < n; c++) data[r + c * n] = a[r][n + c];\n\t}\n\treturn matrixValue(n, n, data);\n}\n\n/** Matrices at or beyond this size are rejected for symbolic inversion. See {@link symbolicInverse}'s doc comment. */\nconst SYMBOLIC_INVERSE_DIMENSION_LIMIT = 9;\n\n/**\n * Symbolic Gauss-Jordan inverse, SAME [A|I] augmented-elimination shape\n * as {@link numericInverse}, but every cell is a `SymbolicNode` and every\n * arithmetic step (divide by pivot, multiply-and-subtract to eliminate a\n * column) goes through `simplifySymbolic()` instead of plain `number` ops.\n *\n * Deliberately uses a DIAGONAL-FIRST pivot strategy with NO row-swapping\n * a real, disclosed limitation: `numericInverse`'s partial-pivoting\n * searches for the numerically-largest candidate, but there's no general\n * \"is this free-variable formula bigger than that one\" ordering to search\n * by, so this always pivots on the diagonal entry as-is. A pivot that\n * simplifies to the exact constant `0` is reported as singular/unsolvable\n * via this strategy (a genuinely different structure, or one needing row\n * reordering the caller would have to do manually, produces this error)\n * this is sufficient for the spec's own already-triangular-friendly\n * example (`s`/`t`'s diagonal entries are never structurally zero).\n *\n * Capped at {@link SYMBOLIC_INVERSE_DIMENSION_LIMIT}, beyond this\n * expression trees from repeated symbolic elimination steps can grow\n * large enough to make the \"not a general CAS\" bounded simplifier\n * genuinely slow; the spec's own examples are all well under this size.\n */\nfunction symbolicInverse(m: MatrixData): Value {\n\tconst n = m.rows;\n\tif (n >= SYMBOLIC_INVERSE_DIMENSION_LIMIT) {\n\t\treturn errorValue(\n\t\t\t\"SYMBOLIC_INVERSE_DIMENSION_LIMIT\",\n\t\t\t`Symbolic matrix inversion is limited to matrices smaller than ${SYMBOLIC_INVERSE_DIMENSION_LIMIT}x${SYMBOLIC_INVERSE_DIMENSION_LIMIT} (got ${n}x${n}).`,\n\t\t);\n\t}\n\tconst a: SymbolicNode[][] = [];\n\tfor (let r = 0; r < n; r++) {\n\t\tconst row: SymbolicNode[] = [];\n\t\tfor (let c = 0; c < n; c++) row.push(entryToSymbolic(matAt(m, r, c)));\n\t\tfor (let c = 0; c < n; c++) row.push(constNode(c === r ? 1 : 0));\n\t\ta.push(row);\n\t}\n\tfor (let col = 0; col < n; col++) {\n\t\tconst pivot = simplifySymbolic(a[col][col]);\n\t\tif (pivot.kind === \"const\" && isRationalZero(pivot.value)) {\n\t\t\treturn errorValue(\n\t\t\t\t\"SYMBOLIC_SINGULAR_OR_UNSUPPORTED_PIVOT\",\n\t\t\t\t`Symbolic inverse: the pivot at row/col ${col} is exactly zero — this matrix's structure isn't invertible via this engine's diagonal-first symbolic elimination (no row-swapping); try reordering rows manually.`,\n\t\t\t);\n\t\t}\n\t\t// Eliminate first, divide the pivot row through afterwards, which is\n\t\t// the order {@link symbolicDeterminant} already uses and the reason it\n\t\t// answers 0 for a structurally singular matrix this used to invert.\n\t\t// Dividing first makes the factor the raw entry and the eliminated\n\t\t// cell `b - a*(b/a)`, and the simplifier does not cancel a division\n\t\t// buried under a multiplication, so the second pivot of `[a,b;a,b]`\n\t\t// arrived as `b-a*b/a` rather than as zero and the matrix was inverted\n\t\t// into cells containing `1/(b-a*b/a)`, a division by nothing. This\n\t\t// order divides before multiplying instead: the factor is `a/a`, which\n\t\t// does simplify to 1, leaving `b - b` and an exact zero pivot.\n\t\tfor (let r = 0; r < n; r++) {\n\t\t\tif (r === col) continue;\n\t\t\tconst factor = simplifySymbolic({ kind: \"div\", left: a[r][col], right: pivot });\n\t\t\tif (factor.kind === \"const\" && isRationalZero(factor.value)) continue;\n\t\t\tfor (let c = 0; c < 2 * n; c++) {\n\t\t\t\ta[r][c] = simplifySymbolic({ kind: \"sub\", left: a[r][c], right: { kind: \"mul\", left: factor, right: a[col][c] } });\n\t\t\t}\n\t\t}\n\t\tfor (let c = 0; c < 2 * n; c++) {\n\t\t\ta[col][c] = simplifySymbolic({ kind: \"div\", left: a[col][c], right: pivot });\n\t\t}\n\t}\n\tconst data = new Array<MatrixEntry>(n * n);\n\tfor (let r = 0; r < n; r++) {\n\t\tfor (let c = 0; c < n; c++) data[r + c * n] = symbolicToEntry(a[r][n + c]);\n\t}\n\treturn matrixValue(n, n, data);\n}\n\n/** `a^-1` / `inv(a)`, dispatches to the symbolic or plain-numeric implementation based on `m.hasSymbolic`. */\nexport function inverse(m: MatrixData): Value {\n\tif (!isSquare(m)) {\n\t\treturn errorValue(\"INVERSE_REQUIRES_SQUARE_MATRIX\", `inv: matrix must be square (got ${m.rows}x${m.cols}).`);\n\t}\n\treturn m.hasSymbolic ? symbolicInverse(m) : numericInverse(m);\n}\n\n/** The refusal {@link collectionToValues} answers with once a collection is bigger than the caller's ceiling. */\nfunction tooLarge(length: number, maxElements: number): Value {\n\treturn errorValue(\n\t\t\"COLLECTION_TOO_LARGE\",\n\t\t`This collection has ${length} elements, past the limit of ${maxElements} (see the engine's vm.maxCollectionSize setting).`,\n\t);\n}\n\n/**\n * Reads a `map`/`reduce` \"collection\" argument into a flat array of\n * per-cell Values, a Matrix's own cells (column-major order, matching\n * `MAT_INDEX1`'s reading convention) or a Range materialized into its\n * inclusive integer sequence (`0:3` -> `[0,1,2,3]`, matching `map(f,\n * 0:3)`'s spec example). Returns an error Value directly (not thrown) if\n * `v` is neither. Same \"propagate as a value, don't throw\" convention\n * `matrixMultiply`/`matrixCompare` above already use.\n *\n * `maxElements` bounds what a Range is allowed to become. It defaults to\n * unbounded so that a caller with no configured engine (a direct unit test\n * of this helper) behaves as before, every VM call site passes\n * `vm.getMaxCollectionSize()`.\n */\nexport function collectionToValues(v: Value, maxElements = Number.POSITIVE_INFINITY): Value[] | Value {\n\t// Pending as well as Error: neither is a collection, and a collection that\n\t// has not arrived is not an empty one. See `faultedOperand()` in vm/Value.ts.\n\tconst faulted = faultedOperand(v);\n\tif (faulted) return faulted;\n\tif (v.type === ValueType.Matrix) {\n\t\tconst m = v.value as MatrixData;\n\t\tif (m.data.length > maxElements) return tooLarge(m.data.length, maxElements);\n\t\treturn m.data.map(matrixEntryToValue);\n\t}\n\tif (v.type === ValueType.Range) {\n\t\tconst r = v.value as RangeData;\n\t\t// Counted before anything is allocated, not while allocating: the\n\t\t// expansion of `1:100000000` reaches the heap limit and aborts the\n\t\t// process, and an abort is not something a `try` can contain.\n\t\tconst length = r.max - r.min + 1;\n\t\tif (length > maxElements) return tooLarge(length, maxElements);\n\t\tconst out: Value[] = new Array<Value>(length);\n\t\tfor (let i = 0; i < length; i++) out[i] = numberValue(r.min + i);\n\t\treturn out;\n\t}\n\treturn errorValue(\n\t\t\"MAP_REDUCE_REQUIRES_COLLECTION\",\n\t\t`map/reduce requires a Matrix or Range collection (e.g. \"[1,2,3]\" or \"0:3\").`,\n\t);\n}\n","import { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * An exact base-ten number, held as an integer coefficient and a scale.\n *\n * The value is `coef * 10^(-scale)`, so `Decimal(30n, 2)` is exactly `0.30` and\n * `Decimal(1005n, 3)` is exactly `1.005`. `scale` is a non-negative integer\n * count of fractional digits, the sign lives on `coef`, and zero is\n * `Decimal(0n, s)` for any `s`.\n *\n * This is the representation money is carried in so that two prices a user\n * typed add and multiply without the binary-floating-point error a double\n * introduces (`0.1 + 0.2` is `0.30000000000000004` as a double, `0.30` here).\n * It is deliberately dependency-free: a bigint coefficient plus an integer\n * scale needs nothing the runtime does not already have, which keeps the\n * engine's single-runtime-dependency contract intact.\n */\nexport interface DecimalData {\n\t/** The integer coefficient, carrying the sign. */\n\treadonly coef: bigint;\n\t/** The number of fractional digits, a non-negative integer. */\n\treadonly scale: number;\n}\n\n/**\n * How division and display rounding break a tie.\n *\n * Half away from zero is the reading a person doing money by hand uses (a half\n * cent rounds up to the next cent, and a negative one rounds down to the next),\n * and it is what `Intl.NumberFormat` picks by default. It is the one mode this\n * module implements, named so the call sites read as decisions rather than\n * defaults.\n */\nexport type RoundingMode = \"halfAwayFromZero\";\n\n/**\n * How many fractional digits a non-terminating division keeps.\n *\n * `$10 / 3` has no exact decimal, so the quotient is rounded to this many\n * places. Twenty is far more than any currency displays and enough that the\n * double taken from it (via {@link decimalToNumber}) is the same one the\n * ordinary float division would have produced, so nothing downstream sees a\n * coarser answer than before.\n */\nexport const DEFAULT_DIVISION_SCALE = 20;\n\n/** Powers of ten, memoized, since scale alignment asks for the same few often. */\nconst POW10: bigint[] = [1n];\nfunction pow10(n: number): bigint {\n\tif (n < 0) {\n\t\tthrow ErrorFactory.internal(\"DECIMAL_NEGATIVE_POWER\", `pow10 needs a non-negative exponent, got ${n}`, { exponent: n });\n\t}\n\tfor (let i = POW10.length; i <= n; i++) POW10[i] = POW10[i - 1] * 10n;\n\treturn POW10[n];\n}\n\n/** Build a {@link DecimalData}, guarding the scale invariant in one place. */\nexport function makeDecimal(coef: bigint, scale: number): DecimalData {\n\tif (!Number.isInteger(scale) || scale < 0) {\n\t\tthrow ErrorFactory.internal(\"DECIMAL_INVALID_SCALE\", `A decimal scale must be a non-negative integer, got ${scale}`, { scale });\n\t}\n\treturn { coef, scale };\n}\n\n/** The exact decimal for a whole number. */\nexport function decimalFromInteger(n: bigint | number): DecimalData {\n\treturn { coef: typeof n === \"bigint\" ? n : BigInt(n), scale: 0 };\n}\n\n/**\n * The exact decimal a plain number stands for, or `null` when it has none.\n *\n * Only whole numbers convert: a whole-valued double is exactly the integer it\n * prints as, so lifting it is lossless. A fractional double (`0.1`, the result\n * of `sqrt(2)`) is NOT its printed decimal, it is the nearest double to it, so\n * there is no exact decimal to recover and this returns `null` rather than\n * inventing one. That null is the boundary that keeps float where float\n * belongs: a fractional double meeting money stays a double.\n */\nexport function decimalFromNumberIfExact(n: number): DecimalData | null {\n\tif (!Number.isFinite(n) || !Number.isInteger(n)) return null;\n\treturn decimalFromInteger(BigInt(n));\n}\n\n/**\n * Parse a normalized dot-decimal literal (`\"0.10\"`, `\"1.005\"`, `\"1234.5\"`).\n *\n * The input is what the parser has already reduced a number literal to: any\n * thousands grouping stripped and the locale's decimal separator rewritten as\n * a single `\".\"`. That is why this does not consult a locale, and why it is\n * exact where {@link decimalFromNumberIfExact} is not: the digits are read\n * straight into the coefficient without ever passing through a double.\n *\n * @throws A parsing `INVALID_DECIMAL_LITERAL` error for a string that is not a\n * plain decimal, which the caller should never produce (the lexer validates the\n * literal first) but which is reported rather than guessed at if it does.\n */\nexport function decimalFromLiteral(text: string): DecimalData {\n\tlet s = text;\n\tlet negative = false;\n\tif (s.startsWith(\"-\")) { negative = true; s = s.slice(1); }\n\telse if (s.startsWith(\"+\")) { s = s.slice(1); }\n\tconst dot = s.indexOf(\".\");\n\tconst intPart = dot < 0 ? s : s.slice(0, dot);\n\tconst fracPart = dot < 0 ? \"\" : s.slice(dot + 1);\n\t// A single trailing dot (\"5.\") or a bare fraction (\".5\") are both fine; the\n\t// halves just come out empty and read as zero digits.\n\tconst digits = (intPart + fracPart) || \"0\";\n\tif (!/^[0-9]+$/.test(digits)) {\n\t\tthrow ErrorFactory.parsing(\"INVALID_DECIMAL_LITERAL\", `Not a decimal literal: \"${text}\"`, { raw: text });\n\t}\n\tlet coef = BigInt(digits);\n\tif (negative) coef = -coef;\n\treturn { coef, scale: fracPart.length };\n}\n\n/** Bring two decimals to a shared scale, returning both coefficients and it. */\nfunction align(a: DecimalData, b: DecimalData): { ca: bigint; cb: bigint; scale: number } {\n\tif (a.scale === b.scale) return { ca: a.coef, cb: b.coef, scale: a.scale };\n\tif (a.scale > b.scale) return { ca: a.coef, cb: b.coef * pow10(a.scale - b.scale), scale: a.scale };\n\treturn { ca: a.coef * pow10(b.scale - a.scale), cb: b.coef, scale: b.scale };\n}\n\n/** Exact sum. */\nexport function decimalAdd(a: DecimalData, b: DecimalData): DecimalData {\n\tconst { ca, cb, scale } = align(a, b);\n\treturn { coef: ca + cb, scale };\n}\n\n/** Exact difference. */\nexport function decimalSubtract(a: DecimalData, b: DecimalData): DecimalData {\n\tconst { ca, cb, scale } = align(a, b);\n\treturn { coef: ca - cb, scale };\n}\n\n/** Exact product. The scales add, which is exactly the base-ten rule. */\nexport function decimalMultiply(a: DecimalData, b: DecimalData): DecimalData {\n\treturn { coef: a.coef * b.coef, scale: a.scale + b.scale };\n}\n\n/** Exact negation. */\nexport function decimalNegate(a: DecimalData): DecimalData {\n\treturn { coef: -a.coef, scale: a.scale };\n}\n\n/** Whether the value is exactly zero, regardless of scale. */\nexport function decimalIsZero(a: DecimalData): boolean {\n\treturn a.coef === 0n;\n}\n\n/**\n * Round a coefficient/scale pair to `targetScale` fractional digits, breaking\n * ties away from zero.\n *\n * Scaling UP is exact (append zeros). Scaling DOWN drops digits, and the tie\n * rule looks only at whether twice the dropped remainder reaches the divisor,\n * which is the half-away-from-zero test done in integers so it never rounds a\n * value it was handed exactly.\n */\nfunction roundCoefToScale(coef: bigint, scale: number, targetScale: number): bigint {\n\tif (targetScale >= scale) return coef * pow10(targetScale - scale);\n\tconst divisor = pow10(scale - targetScale);\n\tconst negative = coef < 0n;\n\tconst magnitude = negative ? -coef : coef;\n\tlet q = magnitude / divisor;\n\tconst r = magnitude % divisor;\n\t// Away from zero on a tie: 2*r === divisor rounds up, as does 2*r > divisor.\n\tif (r * 2n >= divisor) q += 1n;\n\treturn negative ? -q : q;\n}\n\n/** Round to `targetScale` fractional digits, half away from zero. */\nexport function decimalRound(a: DecimalData, targetScale: number): DecimalData {\n\treturn { coef: roundCoefToScale(a.coef, a.scale, targetScale), scale: targetScale };\n}\n\n/**\n * Quotient of two decimals, exact where it terminates and rounded to\n * `maxFractionDigits` where it does not.\n *\n * The caller guarantees a non-zero divisor: exact decimal division has no\n * answer at zero, the same way integer division does not, so the money\n * arithmetic checks {@link decimalIsZero} first and keeps the double's Infinity\n * for that case rather than routing it here.\n */\nexport function decimalDivide(a: DecimalData, b: DecimalData, maxFractionDigits: number = DEFAULT_DIVISION_SCALE): DecimalData {\n\tif (decimalIsZero(b)) {\n\t\tthrow ErrorFactory.internal(\"DECIMAL_DIVISION_BY_ZERO\", \"decimalDivide was called with a zero divisor\", {});\n\t}\n\t// a/b at result scale s is round( a.coef * 10^(s + b.scale) / (b.coef * 10^a.scale) ).\n\tconst s = maxFractionDigits;\n\tconst numerator = a.coef * pow10(s + b.scale);\n\tconst denominator = b.coef * pow10(a.scale);\n\tconst negative = (numerator < 0n) !== (denominator < 0n);\n\tconst num = numerator < 0n ? -numerator : numerator;\n\tconst den = denominator < 0n ? -denominator : denominator;\n\tlet q = num / den;\n\tconst r = num % den;\n\tif (r * 2n >= den) q += 1n;\n\treturn { coef: negative ? -q : q, scale: s };\n}\n\n/** Three-way comparison: -1, 0 or 1. */\nexport function decimalCompare(a: DecimalData, b: DecimalData): -1 | 0 | 1 {\n\tconst { ca, cb } = align(a, b);\n\tif (ca < cb) return -1;\n\tif (ca > cb) return 1;\n\treturn 0;\n}\n\n/**\n * The exact decimal as a plain string, with no rounding and no grouping.\n *\n * Used both to hand a lossless value to `Number()` (which then rounds to the\n * nearest double once, correctly) and as the basis for fixed-precision display.\n */\nexport function decimalToString(a: DecimalData): string {\n\tconst negative = a.coef < 0n;\n\tlet digits = (negative ? -a.coef : a.coef).toString();\n\tif (a.scale === 0) return negative ? `-${digits}` : digits;\n\tif (digits.length <= a.scale) digits = digits.padStart(a.scale + 1, \"0\");\n\tconst cut = digits.length - a.scale;\n\tconst whole = digits.slice(0, cut);\n\tconst frac = digits.slice(cut);\n\treturn `${negative ? \"-\" : \"\"}${whole}.${frac}`;\n}\n\n/**\n * The nearest double to the exact value.\n *\n * Goes through {@link decimalToString} so the value is rounded to a double\n * exactly once, from its full decimal form, rather than accumulating error\n * through a `Number(coef) / Number(10^scale)` division.\n */\nexport function decimalToNumber(a: DecimalData): number {\n\treturn Number(decimalToString(a));\n}\n\n/**\n * Render with exactly `fractionDigits` decimal places, rounded half away from\n * zero.\n *\n * This is the money-display path, and it is where the exact representation pays\n * off visibly: `$1.005` shows as `1.01` and `$2.675` as `2.68`, where\n * `(1.005).toFixed(2)` and `(2.675).toFixed(2)` answer `1.00` and `2.67`\n * because the double handed to `toFixed` is already a hair below the value the\n * user typed. No thousands grouping, matching the existing `toFixed`-based\n * currency formatter this replaces.\n */\nexport function decimalToFixed(a: DecimalData, fractionDigits: number): string {\n\tconst rounded = decimalRound(a, fractionDigits);\n\tconst negative = rounded.coef < 0n && rounded.coef !== 0n;\n\tlet digits = (rounded.coef < 0n ? -rounded.coef : rounded.coef).toString();\n\tif (fractionDigits === 0) return negative ? `-${digits}` : digits;\n\tif (digits.length <= fractionDigits) digits = digits.padStart(fractionDigits + 1, \"0\");\n\tconst cut = digits.length - fractionDigits;\n\tconst whole = digits.slice(0, cut);\n\tconst frac = digits.slice(cut);\n\treturn `${negative ? \"-\" : \"\"}${whole}.${frac}`;\n}\n","/**\n * Currency symbol/word → ISO 4217 code aliases, and the reverse table used\n * for display formatting (see `format/FormatEngine.ts`'s `formatUom()`).\n *\n * Single source of truth for BOTH directions so the same ambiguity\n * decisions (documented inline below) aren't made twice, inconsistently,\n * in two different files.\n */\n\n/**\n * Currency SYMBOLS (non-alphanumeric characters), safe to recognize as\n * bare lexer tokens with zero risk of colliding with a variable name,\n * since `:name = expr` variable names can never be symbol characters.\n * `CurrencySymbolParselet.ts` consumes these directly.\n *\n * `¥`/`₱`/`peso` ambiguity note: the PESO SIGN (₱) is, per Unicode, the\n * Philippine peso specifically, but the WORD \"peso\" (see\n * `CURRENCY_WORD_ALIASES` below) defaults to the Mexican peso, the most\n * globally recognized \"peso\" in English financial writing. This is a\n * deliberate inconsistency between the symbol and the word for the same\n * general concept, same reasoning as `¥` (JPY) vs \"yuan\" (CNY) below\n * document rather than silently guess, and a user wanting the other one\n * can always type the ISO code directly (\"PHP\"/\"CNY\").\n */\nexport const CURRENCY_SYMBOL_ALIASES: Record<string, string> = {\n \"$\": \"USD\",\n \"£\": \"GBP\",\n \"€\": \"EUR\",\n // ¥ is genuinely ambiguous between JPY and CNY in real-world usage, JPY\n // is the conventional default (matches Numi/most calculator apps' own\n // choice); a user wanting CNY specifically can still type \"CNY\" directly.\n \"¥\": \"JPY\",\n \"₽\": \"RUB\",\n \"₩\": \"KRW\",\n \"₹\": \"INR\",\n \"₺\": \"TRY\",\n \"₴\": \"UAH\",\n \"₪\": \"ILS\",\n \"₫\": \"VND\",\n \"₦\": \"NGN\",\n \"₱\": \"PHP\",\n};\n\n/**\n * Currency WORD forms (singular/plural, all lowercase. This codebase's\n * unit table is strictly case-sensitive with no aliasing, so \"Euro\"/\"EURO\"\n * are deliberately NOT recognized, matching every other word-unit here).\n * Registered as `UNIT` tokens (see `lexer/units.ts`) rather than bare\n * keywords: a bare keyword can never be a `:variableName` (this codebase's\n * tested, intentional policy. See `VariableParselet.ts`'s doc comment)\n * but `:dollar = 5` etc. must keep working, and UNIT-typed tokens ARE\n * accepted as variable names (e.g. \":b = 5\" already works for the \"b\" bits\n * unit), so these ride the same safe mechanism `workday`/`workdays` used.\n *\n * Deliberately NOT included: \"pound\"/\"pounds\", already a MASS unit in\n * `lexer/units.ts` (450g, matching \"lb\"). Remapping it to GBP would be a\n * real, silent regression for anyone using \"5 pounds\" to mean weight; GBP\n * stays reachable via the £ symbol or the \"GBP\" code, same as before.\n *\n * Deliberately NOT included: \"dinar\", used by ~10 countries (Kuwaiti\n * Bahraini, Jordanian, Iraqi, Algerian, ... dinars) with wildly different\n * values (a Kuwaiti dinar is worth roughly 1000x an Algerian one), no\n * single default is defensible the way ¥→JPY or peso→MXN are. Type the\n * ISO code directly (KWD/BHD/JOD/...).\n *\n * Ambiguous-but-resolved cases, and why:\n * - \"peso\"/\"pesos\" → MXN (Mexican peso is the most globally recognized\n * \"peso\" in English financial writing). See the ₱ symbol note above\n * for why this deliberately differs from the ₱ SYMBOL's PHP mapping.\n * - \"franc\"/\"francs\" → CHF (Swiss franc; also used by several African\n * currencies, CHF is the overwhelmingly dominant \"franc\" in English use).\n * - \"krona\"/\"kronor\" → SEK (Swedish); \"krone\"/\"kroner\" → NOK (Norwegian)\n * Danish also uses \"krone\" (DKK) with the identical spelling as\n * Norwegian; NOK was picked arbitrarily as the more commonly-referenced\n * of the two in English text. Type \"DKK\" directly for Danish krone.\n * - \"riyal\"/\"riyals\"/\"rial\"/\"rials\" → SAR (Saudi riyal), both spellings\n * also refer to Qatari/Omani riyals and the Iranian rial; SAR is the\n * most commonly referenced in English. Type \"QAR\"/\"OMR\"/\"IRR\" directly\n * for the others.\n */\nexport const CURRENCY_WORD_ALIASES: Record<string, string> = {\n dollar: \"USD\", dollars: \"USD\",\n euro: \"EUR\", euros: \"EUR\",\n yen: \"JPY\",\n ruble: \"RUB\", rubles: \"RUB\", rouble: \"RUB\", roubles: \"RUB\",\n won: \"KRW\",\n rupee: \"INR\", rupees: \"INR\",\n yuan: \"CNY\", renminbi: \"CNY\",\n franc: \"CHF\", francs: \"CHF\",\n rand: \"ZAR\",\n krona: \"SEK\", kronor: \"SEK\",\n krone: \"NOK\", kroner: \"NOK\",\n real: \"BRL\", reais: \"BRL\",\n peso: \"MXN\", pesos: \"MXN\",\n shekel: \"ILS\", shekels: \"ILS\",\n lira: \"TRY\",\n hryvnia: \"UAH\", hryvnias: \"UAH\",\n zloty: \"PLN\", zlotys: \"PLN\",\n forint: \"HUF\",\n koruna: \"CZK\",\n dirham: \"AED\", dirhams: \"AED\",\n riyal: \"SAR\", riyals: \"SAR\", rial: \"SAR\", rials: \"SAR\",\n ringgit: \"MYR\",\n rupiah: \"IDR\",\n baht: \"THB\",\n dong: \"VND\",\n naira: \"NGN\",\n};\n\n/**\n * Resolve a raw lexed unit/symbol string to its canonical ISO 4217 code\n * e.g. `\"euro\"` -> `\"EUR\"`, `\"$\"` -> `\"USD\"`, `\"USD\"` -> `\"USD\"` (already\n * canonical, returned unchanged). Returns `undefined` if `text` isn't a\n * recognized currency alias at all (distinct from \"already canonical\"\n * callers should fall back to the original text in that case).\n */\nexport function resolveCurrencyAlias(text: string): string | undefined {\n return CURRENCY_SYMBOL_ALIASES[text] ?? CURRENCY_WORD_ALIASES[text.toLowerCase()];\n}\n\n/** How a currency's amount and symbol are conventionally arranged for display. */\nexport interface CurrencyDisplayInfo {\n /** The symbol/abbreviation to render, e.g. \"$\", \"kr\", \"R$\". */\n readonly symbol: string;\n /** Whether the symbol comes before or after the formatted amount. */\n readonly position: \"prefix\" | \"suffix\";\n /** Whether a space separates the symbol from the amount. */\n readonly spaced: boolean;\n}\n\n/**\n * Display convention per ISO code, for currencies with a widely-recognized\n * symbol/abbreviation and an unambiguous placement convention. NOT\n * exhaustive, any code absent here (most of the ~150 codes\n * `CurrencyExchange.isCurrency()` recognizes) falls back to the existing\n * \"amount CODE\" format (e.g. \"100.00 AED\") in `FormatEngine.formatUom()`,\n * exactly as before this table existed. Extend as needed, same pattern as\n * this session's other \"not exhaustive, additive\" tables (city timezones,\n * ingredient densities).\n *\n * Several currencies share the same symbol (USD/AUD/CAD/NZD/HKD/SGD/MXN\n * all conventionally use \"$\" locally). This is safe here because OUTPUT\n * formatting always starts from an already-resolved, unambiguous ISO code\n * (`value.unit`), unlike INPUT parsing where a bare \"$\" genuinely is\n * ambiguous (see `CURRENCY_SYMBOL_ALIASES`'s USD default above).\n */\nexport const CURRENCY_DISPLAY: Record<string, CurrencyDisplayInfo> = {\n USD: { symbol: \"$\", position: \"prefix\", spaced: false },\n AUD: { symbol: \"$\", position: \"prefix\", spaced: false },\n CAD: { symbol: \"$\", position: \"prefix\", spaced: false },\n NZD: { symbol: \"$\", position: \"prefix\", spaced: false },\n HKD: { symbol: \"$\", position: \"prefix\", spaced: false },\n SGD: { symbol: \"$\", position: \"prefix\", spaced: false },\n MXN: { symbol: \"$\", position: \"prefix\", spaced: false },\n GBP: { symbol: \"£\", position: \"prefix\", spaced: false },\n // English-language convention (€100.00), many EU locales instead suffix\n // with a space (\"100,00 €\"); this engine's default locale is \"en\", so\n // the English convention was chosen. A locale-aware override would be a\n // reasonable future extension, not attempted here.\n EUR: { symbol: \"€\", position: \"prefix\", spaced: false },\n JPY: { symbol: \"¥\", position: \"prefix\", spaced: false },\n CNY: { symbol: \"¥\", position: \"prefix\", spaced: false },\n KRW: { symbol: \"₩\", position: \"prefix\", spaced: false },\n INR: { symbol: \"₹\", position: \"prefix\", spaced: false },\n // Russian convention places the ruble sign AFTER the amount, with a space.\n RUB: { symbol: \"₽\", position: \"suffix\", spaced: true },\n TRY: { symbol: \"₺\", position: \"prefix\", spaced: false },\n UAH: { symbol: \"₴\", position: \"suffix\", spaced: true },\n ILS: { symbol: \"₪\", position: \"prefix\", spaced: false },\n // Vietnamese convention: no space, symbol after the amount.\n VND: { symbol: \"₫\", position: \"suffix\", spaced: false },\n NGN: { symbol: \"₦\", position: \"prefix\", spaced: false },\n PHP: { symbol: \"₱\", position: \"prefix\", spaced: false },\n BRL: { symbol: \"R$\", position: \"prefix\", spaced: false },\n ZAR: { symbol: \"R\", position: \"prefix\", spaced: false },\n // Scandinavian convention: amount then \"kr\", space-separated.\n SEK: { symbol: \"kr\", position: \"suffix\", spaced: true },\n NOK: { symbol: \"kr\", position: \"suffix\", spaced: true },\n DKK: { symbol: \"kr\", position: \"suffix\", spaced: true },\n PLN: { symbol: \"zł\", position: \"suffix\", spaced: true },\n CHF: { symbol: \"Fr\", position: \"suffix\", spaced: true },\n HUF: { symbol: \"Ft\", position: \"suffix\", spaced: true },\n CZK: { symbol: \"Kč\", position: \"suffix\", spaced: true },\n};\n"]}