@cortex-js/compute-engine 0.57.0 → 0.59.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 (270) hide show
  1. package/README.md +4 -0
  2. package/dist/compile.esm.js +2376 -501
  3. package/dist/compile.min.esm.js +316 -68
  4. package/dist/compile.min.umd.cjs +316 -68
  5. package/dist/compile.umd.cjs +2376 -501
  6. package/dist/compute-engine.esm.js +15717 -12444
  7. package/dist/compute-engine.min.esm.js +331 -83
  8. package/dist/compute-engine.min.umd.cjs +330 -82
  9. package/dist/compute-engine.umd.cjs +15717 -12444
  10. package/dist/core.esm.js +15716 -12443
  11. package/dist/core.min.esm.js +329 -81
  12. package/dist/core.min.umd.cjs +329 -81
  13. package/dist/core.umd.cjs +15716 -12443
  14. package/dist/identities.esm.js +1921 -0
  15. package/dist/identities.min.esm.js +2 -0
  16. package/dist/identities.min.umd.cjs +4 -0
  17. package/dist/identities.umd.cjs +1946 -0
  18. package/dist/interval.esm.js +779 -339
  19. package/dist/interval.min.esm.js +8 -8
  20. package/dist/interval.min.umd.cjs +8 -8
  21. package/dist/interval.umd.cjs +779 -339
  22. package/dist/latex-syntax.esm.js +971 -608
  23. package/dist/latex-syntax.min.esm.js +7 -7
  24. package/dist/latex-syntax.min.umd.cjs +7 -7
  25. package/dist/latex-syntax.umd.cjs +971 -608
  26. package/dist/math-json.esm.js +8 -12
  27. package/dist/math-json.min.esm.js +2 -2
  28. package/dist/math-json.min.umd.cjs +2 -2
  29. package/dist/math-json.umd.cjs +8 -12
  30. package/dist/numerics.esm.js +1382 -226
  31. package/dist/numerics.min.esm.js +16 -5
  32. package/dist/numerics.min.umd.cjs +16 -5
  33. package/dist/numerics.umd.cjs +1382 -226
  34. package/dist/types/big-decimal/big-decimal.d.ts +1 -1
  35. package/dist/types/big-decimal/index.d.ts +1 -1
  36. package/dist/types/big-decimal/transcendentals.d.ts +1 -1
  37. package/dist/types/big-decimal/utils.d.ts +1 -1
  38. package/dist/types/common/ansi-codes.d.ts +1 -1
  39. package/dist/types/common/configuration-change.d.ts +1 -1
  40. package/dist/types/common/fuzzy-string-match.d.ts +1 -1
  41. package/dist/types/common/grapheme-splitter.d.ts +1 -1
  42. package/dist/types/common/interruptible.d.ts +1 -1
  43. package/dist/types/common/one-of.d.ts +1 -1
  44. package/dist/types/common/signals.d.ts +1 -1
  45. package/dist/types/common/type/ast-nodes.d.ts +1 -1
  46. package/dist/types/common/type/boxed-type.d.ts +1 -1
  47. package/dist/types/common/type/lexer.d.ts +1 -1
  48. package/dist/types/common/type/parse.d.ts +1 -208
  49. package/dist/types/common/type/parser.d.ts +124 -2
  50. package/dist/types/common/type/primitive.d.ts +5 -1
  51. package/dist/types/common/type/reduce.d.ts +1 -1
  52. package/dist/types/common/type/serialize.d.ts +1 -1
  53. package/dist/types/common/type/subtype.d.ts +18 -1
  54. package/dist/types/common/type/type-builder.d.ts +1 -1
  55. package/dist/types/common/type/types.d.ts +1 -1
  56. package/dist/types/common/type/utils.d.ts +1 -1
  57. package/dist/types/common/utils.d.ts +1 -1
  58. package/dist/types/compile.d.ts +1 -1
  59. package/dist/types/compute-engine/assume.d.ts +13 -6
  60. package/dist/types/compute-engine/boxed-expression/abstract-boxed-expression.d.ts +3 -1
  61. package/dist/types/compute-engine/boxed-expression/apply.d.ts +1 -1
  62. package/dist/types/compute-engine/boxed-expression/arithmetic-add.d.ts +1 -1
  63. package/dist/types/compute-engine/boxed-expression/arithmetic-mul-div.d.ts +1 -1
  64. package/dist/types/compute-engine/boxed-expression/arithmetic-power.d.ts +1 -1
  65. package/dist/types/compute-engine/boxed-expression/ascii-math.d.ts +1 -1
  66. package/dist/types/compute-engine/boxed-expression/box.d.ts +1 -1
  67. package/dist/types/compute-engine/boxed-expression/boxed-dictionary.d.ts +1 -1
  68. package/dist/types/compute-engine/boxed-expression/boxed-function.d.ts +1 -1
  69. package/dist/types/compute-engine/boxed-expression/boxed-number.d.ts +1 -1
  70. package/dist/types/compute-engine/boxed-expression/boxed-operator-definition.d.ts +7 -1
  71. package/dist/types/compute-engine/boxed-expression/boxed-patterns.d.ts +1 -1
  72. package/dist/types/compute-engine/boxed-expression/boxed-string.d.ts +1 -1
  73. package/dist/types/compute-engine/boxed-expression/boxed-symbol.d.ts +3 -3
  74. package/dist/types/compute-engine/boxed-expression/boxed-tensor.d.ts +1 -1
  75. package/dist/types/compute-engine/boxed-expression/boxed-value-definition.d.ts +1 -1
  76. package/dist/types/compute-engine/boxed-expression/cache.d.ts +1 -1
  77. package/dist/types/compute-engine/boxed-expression/canonical-utils.d.ts +1 -1
  78. package/dist/types/compute-engine/boxed-expression/canonical.d.ts +1 -1
  79. package/dist/types/compute-engine/boxed-expression/compare.d.ts +1 -1
  80. package/dist/types/compute-engine/boxed-expression/constants.d.ts +1 -1
  81. package/dist/types/compute-engine/boxed-expression/constraint-subject.d.ts +140 -0
  82. package/dist/types/compute-engine/boxed-expression/expand.d.ts +1 -1
  83. package/dist/types/compute-engine/boxed-expression/expression-map.d.ts +1 -1
  84. package/dist/types/compute-engine/boxed-expression/factor.d.ts +1 -1
  85. package/dist/types/compute-engine/boxed-expression/flatten.d.ts +1 -1
  86. package/dist/types/compute-engine/boxed-expression/hold.d.ts +1 -1
  87. package/dist/types/compute-engine/boxed-expression/inequality-bounds.d.ts +34 -12
  88. package/dist/types/compute-engine/boxed-expression/init-lazy-refs.d.ts +1 -1
  89. package/dist/types/compute-engine/boxed-expression/invisible-operator.d.ts +1 -1
  90. package/dist/types/compute-engine/boxed-expression/match.d.ts +1 -1
  91. package/dist/types/compute-engine/boxed-expression/negate.d.ts +1 -1
  92. package/dist/types/compute-engine/boxed-expression/numerics.d.ts +1 -1
  93. package/dist/types/compute-engine/boxed-expression/order.d.ts +1 -1
  94. package/dist/types/compute-engine/boxed-expression/pattern-utils.d.ts +1 -1
  95. package/dist/types/compute-engine/boxed-expression/polynomial-degree.d.ts +1 -1
  96. package/dist/types/compute-engine/boxed-expression/polynomials.d.ts +1 -1
  97. package/dist/types/compute-engine/boxed-expression/predicates.d.ts +1 -1
  98. package/dist/types/compute-engine/boxed-expression/rule-index.d.ts +112 -0
  99. package/dist/types/compute-engine/boxed-expression/rules.d.ts +2 -1
  100. package/dist/types/compute-engine/boxed-expression/serialize.d.ts +1 -1
  101. package/dist/types/compute-engine/boxed-expression/sgn.d.ts +1 -1
  102. package/dist/types/compute-engine/boxed-expression/simplify.d.ts +1 -1
  103. package/dist/types/compute-engine/boxed-expression/solve-linear-system.d.ts +1 -1
  104. package/dist/types/compute-engine/boxed-expression/solve.d.ts +1 -1
  105. package/dist/types/compute-engine/boxed-expression/stochastic-equal.d.ts +1 -1
  106. package/dist/types/compute-engine/boxed-expression/trigonometry.d.ts +1 -1
  107. package/dist/types/compute-engine/boxed-expression/type-guards.d.ts +1 -1
  108. package/dist/types/compute-engine/boxed-expression/utils.d.ts +1 -1
  109. package/dist/types/compute-engine/boxed-expression/validate.d.ts +1 -1
  110. package/dist/types/compute-engine/collection-utils.d.ts +1 -1
  111. package/dist/types/compute-engine/compilation/base-compiler.d.ts +8 -1
  112. package/dist/types/compute-engine/compilation/compile-expression.d.ts +1 -1
  113. package/dist/types/compute-engine/compilation/constant-folding.d.ts +16 -1
  114. package/dist/types/compute-engine/compilation/glsl-target.d.ts +1 -1
  115. package/dist/types/compute-engine/compilation/gpu-target.d.ts +58 -5
  116. package/dist/types/compute-engine/compilation/interval-javascript-target.d.ts +4 -4
  117. package/dist/types/compute-engine/compilation/javascript-target.d.ts +1 -1
  118. package/dist/types/compute-engine/compilation/python-target.d.ts +1 -1
  119. package/dist/types/compute-engine/compilation/types.d.ts +1 -1
  120. package/dist/types/compute-engine/compilation/wgsl-target.d.ts +1 -1
  121. package/dist/types/compute-engine/cost-function.d.ts +1 -1
  122. package/dist/types/compute-engine/engine-assumptions.d.ts +1 -1
  123. package/dist/types/compute-engine/engine-cache.d.ts +1 -1
  124. package/dist/types/compute-engine/engine-common-symbols.d.ts +1 -1
  125. package/dist/types/compute-engine/engine-compilation-targets.d.ts +1 -1
  126. package/dist/types/compute-engine/engine-configuration-lifecycle.d.ts +1 -1
  127. package/dist/types/compute-engine/engine-declarations.d.ts +1 -1
  128. package/dist/types/compute-engine/engine-expression-entrypoints.d.ts +1 -1
  129. package/dist/types/compute-engine/engine-extension-contracts.d.ts +1 -1
  130. package/dist/types/compute-engine/engine-library-bootstrap.d.ts +1 -1
  131. package/dist/types/compute-engine/engine-numeric-configuration.d.ts +1 -1
  132. package/dist/types/compute-engine/engine-runtime-state.d.ts +4 -1
  133. package/dist/types/compute-engine/engine-scope.d.ts +1 -1
  134. package/dist/types/compute-engine/engine-sequences.d.ts +1 -1
  135. package/dist/types/compute-engine/engine-simplification-rules.d.ts +10 -2
  136. package/dist/types/compute-engine/engine-startup-coordinator.d.ts +1 -1
  137. package/dist/types/compute-engine/engine-type-resolver.d.ts +1 -1
  138. package/dist/types/compute-engine/engine-validation-entrypoints.d.ts +1 -1
  139. package/dist/types/compute-engine/free-functions.d.ts +1 -1
  140. package/dist/types/compute-engine/function-utils.d.ts +1 -1
  141. package/dist/types/compute-engine/fungrim/loader.d.ts +13 -0
  142. package/dist/types/compute-engine/fungrim/types.d.ts +160 -0
  143. package/dist/types/compute-engine/global-types.d.ts +1 -1
  144. package/dist/types/compute-engine/index.d.ts +63 -2
  145. package/dist/types/compute-engine/interval/arithmetic.d.ts +1 -1
  146. package/dist/types/compute-engine/interval/comparison.d.ts +1 -1
  147. package/dist/types/compute-engine/interval/elementary.d.ts +10 -2
  148. package/dist/types/compute-engine/interval/index.d.ts +2 -2
  149. package/dist/types/compute-engine/interval/trigonometric.d.ts +1 -1
  150. package/dist/types/compute-engine/interval/types.d.ts +1 -1
  151. package/dist/types/compute-engine/interval/util.d.ts +1 -1
  152. package/dist/types/compute-engine/latex-syntax/dictionary/default-dictionary.d.ts +1 -1
  153. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-algebra.d.ts +1 -1
  154. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-arithmetic.d.ts +1 -1
  155. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-calculus.d.ts +1 -1
  156. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-colors.d.ts +1 -1
  157. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-complex.d.ts +1 -1
  158. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-core.d.ts +1 -1
  159. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-linear-algebra.d.ts +1 -1
  160. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-logic.d.ts +1 -1
  161. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-other.d.ts +1 -1
  162. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-relational-operators.d.ts +1 -1
  163. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-sets.d.ts +1 -1
  164. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-statistics.d.ts +1 -1
  165. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-symbols.d.ts +1 -1
  166. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-trigonometry.d.ts +1 -1
  167. package/dist/types/compute-engine/latex-syntax/dictionary/definitions-units.d.ts +1 -1
  168. package/dist/types/compute-engine/latex-syntax/dictionary/definitions.d.ts +1 -1
  169. package/dist/types/compute-engine/latex-syntax/dictionary/indexed-types.d.ts +4 -1
  170. package/dist/types/compute-engine/latex-syntax/latex-syntax.d.ts +1 -1
  171. package/dist/types/compute-engine/latex-syntax/parse-number.d.ts +1 -1
  172. package/dist/types/compute-engine/latex-syntax/parse-symbol.d.ts +1 -1
  173. package/dist/types/compute-engine/latex-syntax/parse.d.ts +3 -2
  174. package/dist/types/compute-engine/latex-syntax/serialize-dms.d.ts +1 -1
  175. package/dist/types/compute-engine/latex-syntax/serialize-number.d.ts +1 -11
  176. package/dist/types/compute-engine/latex-syntax/serializer-style.d.ts +1 -1
  177. package/dist/types/compute-engine/latex-syntax/serializer.d.ts +1 -1
  178. package/dist/types/compute-engine/latex-syntax/tokenizer.d.ts +1 -1
  179. package/dist/types/compute-engine/latex-syntax/types.d.ts +1 -1
  180. package/dist/types/compute-engine/latex-syntax/utils.d.ts +1 -1
  181. package/dist/types/compute-engine/library/arithmetic.d.ts +1 -1
  182. package/dist/types/compute-engine/library/calculus.d.ts +1 -1
  183. package/dist/types/compute-engine/library/collections.d.ts +1 -1
  184. package/dist/types/compute-engine/library/colors.d.ts +1 -1
  185. package/dist/types/compute-engine/library/combinatorics.d.ts +1 -1
  186. package/dist/types/compute-engine/library/complex.d.ts +13 -1
  187. package/dist/types/compute-engine/library/control-structures.d.ts +1 -1
  188. package/dist/types/compute-engine/library/core.d.ts +1 -1
  189. package/dist/types/compute-engine/library/fractals.d.ts +1 -1
  190. package/dist/types/compute-engine/library/library.d.ts +1 -1
  191. package/dist/types/compute-engine/library/linear-algebra.d.ts +1 -1
  192. package/dist/types/compute-engine/library/logic-analysis.d.ts +1 -1
  193. package/dist/types/compute-engine/library/logic.d.ts +1 -1
  194. package/dist/types/compute-engine/library/number-theory.d.ts +1 -1
  195. package/dist/types/compute-engine/library/polynomials.d.ts +1 -1
  196. package/dist/types/compute-engine/library/quantity-arithmetic.d.ts +1 -1
  197. package/dist/types/compute-engine/library/random-expression.d.ts +1 -1
  198. package/dist/types/compute-engine/library/relational-operator.d.ts +1 -1
  199. package/dist/types/compute-engine/library/sets.d.ts +27 -1
  200. package/dist/types/compute-engine/library/statistics.d.ts +1 -1
  201. package/dist/types/compute-engine/library/trigonometry.d.ts +1 -1
  202. package/dist/types/compute-engine/library/type-handlers.d.ts +1 -1
  203. package/dist/types/compute-engine/library/unit-data.d.ts +1 -1
  204. package/dist/types/compute-engine/library/units.d.ts +1 -1
  205. package/dist/types/compute-engine/library/utils.d.ts +1 -1
  206. package/dist/types/compute-engine/numeric-value/big-numeric-value.d.ts +1 -1
  207. package/dist/types/compute-engine/numeric-value/exact-numeric-value.d.ts +7 -1
  208. package/dist/types/compute-engine/numeric-value/machine-numeric-value.d.ts +1 -1
  209. package/dist/types/compute-engine/numeric-value/types.d.ts +1 -1
  210. package/dist/types/compute-engine/numerics/bernoulli.d.ts +39 -0
  211. package/dist/types/compute-engine/numerics/bigint.d.ts +1 -1
  212. package/dist/types/compute-engine/numerics/expression.d.ts +1 -1
  213. package/dist/types/compute-engine/numerics/interval.d.ts +1 -1
  214. package/dist/types/compute-engine/numerics/linear-algebra.d.ts +1 -1
  215. package/dist/types/compute-engine/numerics/monte-carlo.d.ts +1 -1
  216. package/dist/types/compute-engine/numerics/numeric-bigint.d.ts +1 -1
  217. package/dist/types/compute-engine/numerics/numeric-bignum.d.ts +1 -1
  218. package/dist/types/compute-engine/numerics/numeric-complex.d.ts +12 -1
  219. package/dist/types/compute-engine/numerics/numeric.d.ts +1 -1
  220. package/dist/types/compute-engine/numerics/primes.d.ts +1 -1
  221. package/dist/types/compute-engine/numerics/random.d.ts +23 -0
  222. package/dist/types/compute-engine/numerics/rationals.d.ts +1 -1
  223. package/dist/types/compute-engine/numerics/richardson.d.ts +1 -1
  224. package/dist/types/compute-engine/numerics/special-functions.d.ts +78 -10
  225. package/dist/types/compute-engine/numerics/statistics.d.ts +1 -1
  226. package/dist/types/compute-engine/numerics/strings.d.ts +1 -1
  227. package/dist/types/compute-engine/numerics/types.d.ts +1 -1
  228. package/dist/types/compute-engine/numerics/unit-data.d.ts +1 -1
  229. package/dist/types/compute-engine/oeis.d.ts +1 -1
  230. package/dist/types/compute-engine/sequence.d.ts +1 -1
  231. package/dist/types/compute-engine/symbolic/antiderivative.d.ts +1 -1
  232. package/dist/types/compute-engine/symbolic/derivative.d.ts +1 -1
  233. package/dist/types/compute-engine/symbolic/distribute.d.ts +1 -1
  234. package/dist/types/compute-engine/symbolic/fu-cost.d.ts +1 -1
  235. package/dist/types/compute-engine/symbolic/fu-transforms.d.ts +1 -1
  236. package/dist/types/compute-engine/symbolic/fu.d.ts +1 -1
  237. package/dist/types/compute-engine/symbolic/logic-utils.d.ts +1 -1
  238. package/dist/types/compute-engine/symbolic/simplify-abs.d.ts +1 -1
  239. package/dist/types/compute-engine/symbolic/simplify-divide.d.ts +1 -1
  240. package/dist/types/compute-engine/symbolic/simplify-factorial.d.ts +1 -1
  241. package/dist/types/compute-engine/symbolic/simplify-hyperbolic.d.ts +1 -1
  242. package/dist/types/compute-engine/symbolic/simplify-infinity.d.ts +1 -1
  243. package/dist/types/compute-engine/symbolic/simplify-log.d.ts +1 -1
  244. package/dist/types/compute-engine/symbolic/simplify-logic.d.ts +1 -1
  245. package/dist/types/compute-engine/symbolic/simplify-power.d.ts +1 -1
  246. package/dist/types/compute-engine/symbolic/simplify-product.d.ts +1 -1
  247. package/dist/types/compute-engine/symbolic/simplify-rules.d.ts +1 -1
  248. package/dist/types/compute-engine/symbolic/simplify-sum.d.ts +1 -1
  249. package/dist/types/compute-engine/symbolic/simplify-trig.d.ts +1 -1
  250. package/dist/types/compute-engine/tensor/tensor-fields.d.ts +1 -1
  251. package/dist/types/compute-engine/tensor/tensors.d.ts +3 -3
  252. package/dist/types/compute-engine/types-definitions.d.ts +1 -1
  253. package/dist/types/compute-engine/types-engine.d.ts +52 -3
  254. package/dist/types/compute-engine/types-evaluation.d.ts +1 -1
  255. package/dist/types/compute-engine/types-expression.d.ts +85 -14
  256. package/dist/types/compute-engine/types-kernel-evaluation.d.ts +32 -1
  257. package/dist/types/compute-engine/types-kernel-serialization.d.ts +45 -3
  258. package/dist/types/compute-engine/types-serialization.d.ts +1 -1
  259. package/dist/types/compute-engine/types.d.ts +1 -1
  260. package/dist/types/compute-engine.d.ts +1 -1
  261. package/dist/types/core.d.ts +1 -1
  262. package/dist/types/identities.d.ts +3 -0
  263. package/dist/types/interval.d.ts +1 -1
  264. package/dist/types/latex-syntax.d.ts +2 -2
  265. package/dist/types/math-json/symbols.d.ts +1 -1
  266. package/dist/types/math-json/types.d.ts +1 -1
  267. package/dist/types/math-json/utils.d.ts +1 -1
  268. package/dist/types/math-json.d.ts +2 -2
  269. package/dist/types/numerics.d.ts +1 -1
  270. package/package.json +9 -3
@@ -1,4 +1,4 @@
1
- /** Compute Engine 0.57.0 */
1
+ /** Compute Engine 0.59.0 */
2
2
 
3
3
  // src/compute-engine/interval/util.ts
4
4
  function ok(value) {
@@ -117,9 +117,18 @@ function negate(x) {
117
117
  return ok({ lo: -xVal.hi, hi: -xVal.lo });
118
118
  }
119
119
  function _mul(a, b) {
120
- const products = [a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi];
120
+ const products = [
121
+ _prod(a.lo, b.lo),
122
+ _prod(a.lo, b.hi),
123
+ _prod(a.hi, b.lo),
124
+ _prod(a.hi, b.hi)
125
+ ];
121
126
  return { lo: Math.min(...products), hi: Math.max(...products) };
122
127
  }
128
+ function _prod(x, y) {
129
+ if (x === 0 || y === 0) return 0;
130
+ return x * y;
131
+ }
123
132
  function mul(a, b) {
124
133
  const unwrapped = unwrapOrPropagate(a, b);
125
134
  if (!Array.isArray(unwrapped)) return unwrapped;
@@ -284,6 +293,7 @@ function fpexp(x, scale) {
284
293
  return sum;
285
294
  }
286
295
  function fpln(x, scale) {
296
+ if (x <= 0n) throw new RangeError("fpln: input must be positive");
287
297
  if (x === scale) return 0n;
288
298
  const xNum = Number(x);
289
299
  const scaleNum = Number(scale);
@@ -933,9 +943,11 @@ var BigDecimal = class _BigDecimal {
933
943
  if (Number.isFinite(thisExp) && Number.isFinite(otherExp)) {
934
944
  if (other.significand === 0n) return _BigDecimal.NAN;
935
945
  if (this.significand === 0n) return fromRaw(0n, 0);
936
- return this.sub(this.div(other).trunc().mul(other)).toPrecision(
937
- _BigDecimal.precision
938
- );
946
+ const ediff = thisExp - otherExp;
947
+ const num = ediff >= 0 ? this.significand * pow10(ediff) : this.significand;
948
+ const den = ediff >= 0 ? other.significand : other.significand * pow10(-ediff);
949
+ const q = num / den;
950
+ return this.sub(fromRaw(q, 0).mul(other));
939
951
  }
940
952
  if (thisExp !== thisExp || otherExp !== otherExp) return _BigDecimal.NAN;
941
953
  if (!Number.isFinite(thisExp)) return _BigDecimal.NAN;
@@ -980,7 +992,10 @@ var BigDecimal = class _BigDecimal {
980
992
  return this.pow(n.neg()).inv();
981
993
  }
982
994
  const absSig = this.significand < 0n ? -this.significand : this.significand;
983
- const thisLog10 = bigintDigits(absSig) + this.exponent;
995
+ const sigDigits = bigintDigits(absSig);
996
+ const dropped = sigDigits > 15 ? sigDigits - 15 : 0;
997
+ const lead = dropped > 0 ? Number(absSig / 10n ** BigInt(dropped)) : Number(absSig);
998
+ const thisLog10 = Math.log10(lead) + dropped + this.exponent;
984
999
  const resultLog10 = Number(expValue) * thisLog10;
985
1000
  if (resultLog10 > 9e15) {
986
1001
  return this.significand < 0n && expValue % 2n !== 0n ? _BigDecimal.NEGATIVE_INFINITY : _BigDecimal.POSITIVE_INFINITY;
@@ -1013,7 +1028,19 @@ var BigDecimal = class _BigDecimal {
1013
1028
  return _BigDecimal.POSITIVE_INFINITY;
1014
1029
  }
1015
1030
  if (this.significand < 0n) return _BigDecimal.NAN;
1016
- return n.mul(this.ln()).exp();
1031
+ const baseSig = this.significand;
1032
+ const decExpBase = this.exponent + bigintDigits(baseSig) - 1;
1033
+ const nSig = n.significand < 0n ? -n.significand : n.significand;
1034
+ const decExpN = n.exponent + bigintDigits(nSig) - 1;
1035
+ const argMag = decExpN + Math.log10(Math.abs(decExpBase) * 2.303 + 3) + 1;
1036
+ const extra = Math.min(20, Math.max(2, Math.ceil(argMag) + 2));
1037
+ const savedPrec = _BigDecimal.precision;
1038
+ _BigDecimal.precision = savedPrec + extra;
1039
+ try {
1040
+ return n.mul(this.ln()).exp().toPrecision(savedPrec);
1041
+ } finally {
1042
+ _BigDecimal.precision = savedPrec;
1043
+ }
1017
1044
  }
1018
1045
  // ---------- Conversion methods ----------
1019
1046
  /** Convert to a JavaScript number. May lose precision for large values. */
@@ -1254,6 +1281,20 @@ function fromFixedPoint(fp, scale, targetPrecision) {
1254
1281
  const sig = negative ? -absFp : absFp;
1255
1282
  return fromRaw(sig, resultExp);
1256
1283
  }
1284
+ function decimalExponent(x) {
1285
+ const sig = x.significand < 0n ? -x.significand : x.significand;
1286
+ return x.exponent + bigintDigits(sig) - 1;
1287
+ }
1288
+ var MAX_SAFE_EXPONENT = BigInt(Number.MAX_SAFE_INTEGER);
1289
+ var _ln10Fp = null;
1290
+ var _ln10Scale = null;
1291
+ function ln10Fixed(scale) {
1292
+ if (_ln10Scale !== scale) {
1293
+ _ln10Fp = fpln(10n * scale, scale);
1294
+ _ln10Scale = scale;
1295
+ }
1296
+ return _ln10Fp;
1297
+ }
1257
1298
  BigDecimal.prototype.sqrt = function() {
1258
1299
  if (this.isNaN()) return BigDecimal.NAN;
1259
1300
  if (this.isZero()) return BigDecimal.ZERO;
@@ -1264,9 +1305,13 @@ BigDecimal.prototype.sqrt = function() {
1264
1305
  if (this.significand < 0n) return BigDecimal.NAN;
1265
1306
  const targetPrec = BigDecimal.precision;
1266
1307
  const workingPrec = targetPrec + 10;
1267
- const [fp, scale] = toFixedPoint(this, workingPrec);
1308
+ const e = decimalExponent(this);
1309
+ const k = Math.floor(e / 2);
1310
+ const m = fromRaw(this.significand, this.exponent - 2 * k);
1311
+ const [fp, scale] = toFixedPoint(m, workingPrec);
1268
1312
  const sqrtFp = fpsqrt(fp, scale);
1269
- return fromFixedPoint(sqrtFp, scale, targetPrec);
1313
+ const root = fromFixedPoint(sqrtFp, scale, targetPrec);
1314
+ return fromRaw(root.significand, root.exponent + k);
1270
1315
  };
1271
1316
  BigDecimal.prototype.cbrt = function() {
1272
1317
  if (this.isNaN()) return BigDecimal.NAN;
@@ -1280,10 +1325,13 @@ BigDecimal.prototype.cbrt = function() {
1280
1325
  }
1281
1326
  const targetPrec = BigDecimal.precision;
1282
1327
  const workingPrec = targetPrec + 10;
1283
- const [fp, scale] = toFixedPoint(this, workingPrec);
1328
+ const e = decimalExponent(this);
1329
+ const k = Math.floor(e / 3);
1330
+ const m = fromRaw(this.significand, this.exponent - 3 * k);
1331
+ const [fp, scale] = toFixedPoint(m, workingPrec);
1284
1332
  const C = fp * scale * scale;
1285
1333
  let x;
1286
- const numVal = this.toNumber();
1334
+ const numVal = m.toNumber();
1287
1335
  const scaleNum = Number(scale);
1288
1336
  if (Number.isFinite(numVal) && numVal > 0 && Number.isFinite(scaleNum)) {
1289
1337
  const approx = Math.cbrt(numVal);
@@ -1312,7 +1360,8 @@ BigDecimal.prototype.cbrt = function() {
1312
1360
  const diffNext = bigintAbs(next * next * next - C);
1313
1361
  if (diffNext < diffX) x = next;
1314
1362
  }
1315
- return fromFixedPoint(x, scale, targetPrec);
1363
+ const root = fromFixedPoint(x, scale, targetPrec);
1364
+ return fromRaw(root.significand, root.exponent + k);
1316
1365
  };
1317
1366
  BigDecimal.sqrt = function(x) {
1318
1367
  return x.sqrt();
@@ -1327,11 +1376,27 @@ BigDecimal.prototype.exp = function() {
1327
1376
  return BigDecimal.ZERO;
1328
1377
  }
1329
1378
  if (this.isZero()) return BigDecimal.ONE;
1379
+ if (decimalExponent(this) >= 17)
1380
+ return this.significand > 0n ? BigDecimal.POSITIVE_INFINITY : BigDecimal.ZERO;
1330
1381
  const targetPrec = BigDecimal.precision;
1331
- const workingPrec = targetPrec + 15;
1332
- const [fp, scale] = toFixedPoint(this, workingPrec);
1333
- const expFp = fpexp(fp, scale);
1334
- return fromFixedPoint(expFp, scale, targetPrec);
1382
+ const absSig = this.significand < 0n ? -this.significand : this.significand;
1383
+ const magnitude = Math.max(0, this.exponent + bigintDigits(absSig));
1384
+ const workingPrec = targetPrec + 20 + magnitude;
1385
+ const [xFp, scale] = toFixedPoint(this, workingPrec);
1386
+ const l10 = ln10Fixed(scale);
1387
+ let k = xFp / l10;
1388
+ let rFp = xFp - k * l10;
1389
+ if (rFp < 0n) {
1390
+ k -= 1n;
1391
+ rFp += l10;
1392
+ }
1393
+ if (k > MAX_SAFE_EXPONENT || k < -MAX_SAFE_EXPONENT)
1394
+ return k > 0n ? BigDecimal.POSITIVE_INFINITY : BigDecimal.ZERO;
1395
+ const expR = fromFixedPoint(fpexp(rFp, scale), scale, targetPrec);
1396
+ const newExp = expR.exponent + Number(k);
1397
+ if (!Number.isSafeInteger(newExp))
1398
+ return k > 0n ? BigDecimal.POSITIVE_INFINITY : BigDecimal.ZERO;
1399
+ return fromRaw(expR.significand, newExp);
1335
1400
  };
1336
1401
  BigDecimal.prototype.ln = function() {
1337
1402
  if (this.isNaN()) return BigDecimal.NAN;
@@ -1343,10 +1408,16 @@ BigDecimal.prototype.ln = function() {
1343
1408
  if (this.significand < 0n) return BigDecimal.NAN;
1344
1409
  if (this.eq(1)) return BigDecimal.ZERO;
1345
1410
  const targetPrec = BigDecimal.precision;
1346
- const workingPrec = targetPrec + 15;
1347
- const [fp, scale] = toFixedPoint(this, workingPrec);
1348
- const lnFp = fpln(fp, scale);
1349
- return fromFixedPoint(lnFp, scale, targetPrec);
1411
+ const sig = this.significand;
1412
+ const digits = bigintDigits(sig);
1413
+ const e = this.exponent + digits - 1;
1414
+ const m = fromRaw(sig, -(digits - 1));
1415
+ const eDigits = Math.abs(e).toString().length;
1416
+ const workingPrec = targetPrec + 20 + eDigits;
1417
+ const [mFp, scale] = toFixedPoint(m, workingPrec);
1418
+ const l10 = ln10Fixed(scale);
1419
+ const resultFp = fpln(mFp, scale) + BigInt(e) * l10;
1420
+ return fromFixedPoint(resultFp, scale, targetPrec);
1350
1421
  };
1351
1422
  BigDecimal.prototype.log = function(base) {
1352
1423
  const b = base instanceof BigDecimal ? base : new BigDecimal(base);
@@ -1366,7 +1437,10 @@ BigDecimal.prototype.sin = function() {
1366
1437
  if (!this.isFinite()) return BigDecimal.NAN;
1367
1438
  if (this.isZero()) return BigDecimal.ZERO;
1368
1439
  const targetPrec = BigDecimal.precision;
1369
- const workingPrec = targetPrec + 15;
1440
+ const e = decimalExponent(this);
1441
+ if (e < 0 && -2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
1442
+ const workingPrec = targetPrec + 15 + (e < 0 ? -e : 0);
1443
+ if (e > PI_DIGITS.length - workingPrec - 30) return BigDecimal.NAN;
1370
1444
  const [fp, scale] = toFixedPoint(this, workingPrec);
1371
1445
  const [sinFp] = fpsincos(fp, scale);
1372
1446
  return fromFixedPoint(sinFp, scale, targetPrec);
@@ -1377,6 +1451,8 @@ BigDecimal.prototype.cos = function() {
1377
1451
  if (this.isZero()) return BigDecimal.ONE;
1378
1452
  const targetPrec = BigDecimal.precision;
1379
1453
  const workingPrec = targetPrec + 15;
1454
+ const e = decimalExponent(this);
1455
+ if (e > PI_DIGITS.length - workingPrec - 30) return BigDecimal.NAN;
1380
1456
  const [fp, scale] = toFixedPoint(this, workingPrec);
1381
1457
  const [, cosFp] = fpsincos(fp, scale);
1382
1458
  return fromFixedPoint(cosFp, scale, targetPrec);
@@ -1386,7 +1462,10 @@ BigDecimal.prototype.tan = function() {
1386
1462
  if (!this.isFinite()) return BigDecimal.NAN;
1387
1463
  if (this.isZero()) return BigDecimal.ZERO;
1388
1464
  const targetPrec = BigDecimal.precision;
1389
- const workingPrec = targetPrec + 15;
1465
+ const e = decimalExponent(this);
1466
+ if (e < 0 && -2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
1467
+ const workingPrec = targetPrec + 15 + (e < 0 ? -e : 0);
1468
+ if (e > PI_DIGITS.length - workingPrec - 30) return BigDecimal.NAN;
1390
1469
  const [fp, scale] = toFixedPoint(this, workingPrec);
1391
1470
  const [sinFp, cosFp] = fpsincos(fp, scale);
1392
1471
  if (cosFp === 0n) {
@@ -1404,7 +1483,9 @@ BigDecimal.prototype.atan = function() {
1404
1483
  return piHalf.neg();
1405
1484
  }
1406
1485
  const targetPrec = BigDecimal.precision;
1407
- const workingPrec = targetPrec + 15;
1486
+ const e = decimalExponent(this);
1487
+ if (e < 0 && -2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
1488
+ const workingPrec = targetPrec + 15 + (e < 0 ? -e : 0);
1408
1489
  const [fp, scale] = toFixedPoint(this, workingPrec);
1409
1490
  const atanFp = fpatan(fp, scale);
1410
1491
  return fromFixedPoint(atanFp, scale, targetPrec);
@@ -1421,7 +1502,9 @@ BigDecimal.prototype.asin = function() {
1421
1502
  return this.significand > 0n ? piHalf : piHalf.neg();
1422
1503
  }
1423
1504
  const targetPrec = BigDecimal.precision;
1424
- const workingPrec = targetPrec + 20;
1505
+ const e = decimalExponent(this);
1506
+ if (e < 0 && -2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
1507
+ const workingPrec = targetPrec + 20 + (e < 0 ? -e : 0);
1425
1508
  const [xFp, scale] = toFixedPoint(this, workingPrec);
1426
1509
  const x2 = fpmul(xFp, xFp, scale);
1427
1510
  const oneMinusX2 = scale - x2;
@@ -1484,6 +1567,23 @@ BigDecimal.prototype.sinh = function() {
1484
1567
  if (this.significand > 0n) return BigDecimal.POSITIVE_INFINITY;
1485
1568
  return BigDecimal.NEGATIVE_INFINITY;
1486
1569
  }
1570
+ const targetPrec = BigDecimal.precision;
1571
+ const e = decimalExponent(this);
1572
+ if (e < 0) {
1573
+ if (-2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
1574
+ const saved = BigDecimal.precision;
1575
+ BigDecimal.precision = targetPrec - e + 5;
1576
+ try {
1577
+ const expX2 = this.exp();
1578
+ return expX2.sub(expX2.inv()).div(BigDecimal.TWO).toPrecision(targetPrec);
1579
+ } finally {
1580
+ BigDecimal.precision = saved;
1581
+ }
1582
+ }
1583
+ if (Math.abs(this.toNumber()) > 1.16 * (targetPrec + 3)) {
1584
+ const h = this.abs().exp().div(BigDecimal.TWO);
1585
+ return this.significand > 0n ? h : h.neg();
1586
+ }
1487
1587
  const expX = this.exp();
1488
1588
  const expNegX = expX.inv();
1489
1589
  return expX.sub(expNegX).div(BigDecimal.TWO);
@@ -1494,6 +1594,9 @@ BigDecimal.prototype.cosh = function() {
1494
1594
  if (!this.isFinite()) {
1495
1595
  return BigDecimal.POSITIVE_INFINITY;
1496
1596
  }
1597
+ const targetPrec = BigDecimal.precision;
1598
+ if (Math.abs(this.toNumber()) > 1.16 * (targetPrec + 3))
1599
+ return this.abs().exp().div(BigDecimal.TWO);
1497
1600
  const expX = this.exp();
1498
1601
  const expNegX = expX.inv();
1499
1602
  return expX.add(expNegX).div(BigDecimal.TWO);
@@ -1505,6 +1608,21 @@ BigDecimal.prototype.tanh = function() {
1505
1608
  if (this.significand > 0n) return BigDecimal.ONE;
1506
1609
  return BigDecimal.NEGATIVE_ONE;
1507
1610
  }
1611
+ const targetPrec = BigDecimal.precision;
1612
+ const e = decimalExponent(this);
1613
+ if (e < 0) {
1614
+ if (-2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
1615
+ const saved = BigDecimal.precision;
1616
+ BigDecimal.precision = targetPrec - e + 5;
1617
+ try {
1618
+ const exp2x2 = this.mul(BigDecimal.TWO).exp();
1619
+ return exp2x2.sub(BigDecimal.ONE).div(exp2x2.add(BigDecimal.ONE)).toPrecision(targetPrec);
1620
+ } finally {
1621
+ BigDecimal.precision = saved;
1622
+ }
1623
+ }
1624
+ if (Math.abs(this.toNumber()) > 1.16 * (targetPrec + 3))
1625
+ return this.significand > 0n ? BigDecimal.ONE : BigDecimal.NEGATIVE_ONE;
1508
1626
  const exp2x = this.mul(BigDecimal.TWO).exp();
1509
1627
  return exp2x.sub(BigDecimal.ONE).div(exp2x.add(BigDecimal.ONE));
1510
1628
  };
@@ -1550,9 +1668,14 @@ var lanczos_7_c = [
1550
1668
  ];
1551
1669
  function gammaln(z) {
1552
1670
  if (z < 0) return NaN;
1671
+ let shift = 0;
1672
+ while (z < 10) {
1673
+ shift += Math.log(z);
1674
+ z += 1;
1675
+ }
1553
1676
  const pi = Math.PI;
1554
1677
  const z3 = z * z * z;
1555
- return z * Math.log(z) - z - 0.5 * Math.log(z) + 0.5 * Math.log(2 * pi) + 1 / (12 * z) - 1 / (360 * z3) + 1 / (1260 * z3 * z * z);
1678
+ return z * Math.log(z) - z - 0.5 * Math.log(z) + 0.5 * Math.log(2 * pi) + 1 / (12 * z) - 1 / (360 * z3) + 1 / (1260 * z3 * z * z) - shift;
1556
1679
  }
1557
1680
  function gamma(z) {
1558
1681
  if (z < 0.5) return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z));
@@ -1564,20 +1687,43 @@ function gamma(z) {
1564
1687
  return Math.sqrt(2 * Math.PI) * Math.pow(t, z + 0.5) * Math.exp(-t) * x;
1565
1688
  }
1566
1689
  function erfc(x) {
1567
- return 1 - erf(x);
1690
+ if (Number.isNaN(x)) return NaN;
1691
+ if (!Number.isFinite(x)) return x > 0 ? 0 : 2;
1692
+ if (x < 0) return 2 - erfc(-x);
1693
+ if (x < 2) return 1 - erf(x);
1694
+ const tiny = 1e-300;
1695
+ let f = x === 0 ? tiny : x;
1696
+ let c = f;
1697
+ let d = 0;
1698
+ for (let k = 1; k <= 500; k++) {
1699
+ const a = k / 2;
1700
+ d = x + a * d;
1701
+ if (d === 0) d = tiny;
1702
+ d = 1 / d;
1703
+ c = x + a / c;
1704
+ if (c === 0) c = tiny;
1705
+ const delta = c * d;
1706
+ f *= delta;
1707
+ if (Math.abs(delta - 1) < 1e-17) break;
1708
+ }
1709
+ return Math.exp(-x * x) / (Math.sqrt(Math.PI) * f);
1568
1710
  }
1569
1711
  function erf(x) {
1570
- const a1 = 0.254829592;
1571
- const a2 = -0.284496736;
1572
- const a3 = 1.421413741;
1573
- const a4 = -1.453152027;
1574
- const a5 = 1.061405429;
1575
- const p = 0.3275911;
1712
+ if (Number.isNaN(x)) return NaN;
1713
+ if (x === 0) return 0;
1714
+ if (!Number.isFinite(x)) return x > 0 ? 1 : -1;
1576
1715
  const sign2 = x < 0 ? -1 : 1;
1577
- x = Math.abs(x);
1578
- const t = 1 / (1 + p * x);
1579
- const y = ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t;
1580
- return sign2 * (1 - y * Math.exp(-x * x));
1716
+ const ax = Math.abs(x);
1717
+ if (ax >= 6) return sign2;
1718
+ const x2 = ax * ax;
1719
+ let term = ax;
1720
+ let sum = ax;
1721
+ for (let n = 1; n < 200; n++) {
1722
+ term *= 2 * x2 / (2 * n + 1);
1723
+ sum += term;
1724
+ if (term < sum * 1e-18) break;
1725
+ }
1726
+ return sign2 * (2 / Math.sqrt(Math.PI)) * Math.exp(-x2) * sum;
1581
1727
  }
1582
1728
  var BERNOULLI_2K = [
1583
1729
  1 / 6,
@@ -1704,7 +1850,7 @@ function fresnelS(x) {
1704
1850
  const t = x2 * x2;
1705
1851
  return sign2 * x * x2 * polevl(t, SN) / polevl(t, SD);
1706
1852
  }
1707
- if (x < 36) {
1853
+ if (x < 36974) {
1708
1854
  const x2 = x * x;
1709
1855
  const t = Math.PI * x2;
1710
1856
  const u = 1 / (t * t);
@@ -1729,7 +1875,7 @@ function fresnelC(x) {
1729
1875
  const t = x2 * x2;
1730
1876
  return sign2 * x * polevl(t, CN) / polevl(t, CD);
1731
1877
  }
1732
- if (x < 36) {
1878
+ if (x < 36974) {
1733
1879
  const x2 = x * x;
1734
1880
  const t = Math.PI * x2;
1735
1881
  const u = 1 / (t * t);
@@ -1771,7 +1917,8 @@ function gcd(a, b) {
1771
1917
  }
1772
1918
  function lcm(a, b) {
1773
1919
  if (a === 0 || b === 0) return 0;
1774
- const res = BigInt(a) * BigInt(b) / BigInt(gcd(a, b));
1920
+ let res = BigInt(a) * BigInt(b) / BigInt(gcd(a, b));
1921
+ if (res < 0n) res = -res;
1775
1922
  return Number(res);
1776
1923
  }
1777
1924
  function factorial(n) {
@@ -3137,172 +3284,23 @@ var PRIMITIVE_TYPES = [
3137
3284
  "error",
3138
3285
  ...EXPRESSION_TYPES
3139
3286
  ];
3287
+ var NUMERIC_TYPES_SET = new Set(
3288
+ NUMERIC_TYPES
3289
+ );
3290
+ var COLLECTION_TYPES_SET = new Set(
3291
+ COLLECTION_TYPES
3292
+ );
3293
+ var SCALAR_TYPES_SET = new Set(
3294
+ SCALAR_TYPES
3295
+ );
3296
+ var PRIMITIVE_TYPES_SET = new Set(
3297
+ PRIMITIVE_TYPES
3298
+ );
3140
3299
  function isValidType(t) {
3141
- if (typeof t === "string")
3142
- return PRIMITIVE_TYPES.includes(t);
3300
+ if (typeof t === "string") return PRIMITIVE_TYPES_SET.has(t);
3143
3301
  if (typeof t !== "object") return false;
3144
3302
  if (!("kind" in t)) return false;
3145
- return t.kind === "signature" || t.kind === "union" || t.kind === "intersection" || t.kind === "negation" || t.kind === "tuple" || t.kind === "list" || t.kind === "record" || t.kind === "dictionary" || t.kind === "set" || t.kind === "function" || t.kind === "collection" || t.kind === "indexed_collection" || t.kind === "reference";
3146
- }
3147
-
3148
- // src/common/type/serialize.ts
3149
- var NEGATION_PRECEDENCE = 3;
3150
- var UNION_PRECEDENCE = 1;
3151
- var INTERSECTION_PRECEDENCE = 2;
3152
- var LIST_PRECEDENCE = 4;
3153
- var RECORD_PRECEDENCE = 5;
3154
- var DICTIONARY_PRECEDENCE = 6;
3155
- var SET_PRECEDENCE = 7;
3156
- var COLLECTION_PRECEDENCE = 8;
3157
- var TUPLE_PRECEDENCE = 9;
3158
- var SIGNATURE_PRECEDENCE = 10;
3159
- var VALUE_PRECEDENCE = 11;
3160
- function typeToString(type, precedence = 0) {
3161
- if (typeof type === "string") return type;
3162
- let result = "";
3163
- switch (type.kind) {
3164
- case "value":
3165
- if (typeof type.value === "string") result = `"${type.value}"`;
3166
- else if (typeof type.value === "boolean")
3167
- result = type.value ? "true" : "false";
3168
- else result = type.value.toString();
3169
- break;
3170
- case "reference":
3171
- result = type.name;
3172
- break;
3173
- case "negation":
3174
- result = `!${typeToString(type.type, NEGATION_PRECEDENCE)}`;
3175
- break;
3176
- case "union":
3177
- result = type.types.map((t) => typeToString(t, UNION_PRECEDENCE)).join(" | ");
3178
- break;
3179
- case "intersection":
3180
- result = type.types.map((t) => typeToString(t, INTERSECTION_PRECEDENCE)).join(" & ");
3181
- break;
3182
- case "expression":
3183
- result = `expression<${symbolName(type.operator)}>`;
3184
- break;
3185
- case "symbol":
3186
- result = `symbol<${symbolName(type.name)}>`;
3187
- break;
3188
- case "numeric":
3189
- if (Number.isFinite(type.lower) && Number.isFinite(type.upper)) {
3190
- result = `${type.type}<${type.lower}..${type.upper}>`;
3191
- } else if (Number.isFinite(type.lower)) {
3192
- result = `${type.type}<${type.lower}..>`;
3193
- } else if (Number.isFinite(type.upper)) {
3194
- result = `${type.type}<..${type.upper}>`;
3195
- } else {
3196
- result = `${type.type}`;
3197
- }
3198
- break;
3199
- case "list":
3200
- if (type.dimensions && typeof type.elements === "string" && NUMERIC_TYPES.includes(type.elements)) {
3201
- if (type.dimensions === void 0) {
3202
- if (type.elements === "number") result = "tensor";
3203
- } else if (type.dimensions.length === 1) {
3204
- if (type.elements === "number") {
3205
- if (type.dimensions[0] < 0) result = "vector";
3206
- else result = `vector<${type.dimensions[0]}>`;
3207
- } else {
3208
- if (type.dimensions[0] < 0)
3209
- result = `vector<${typeToString(type.elements)}>`;
3210
- else
3211
- result = `vector<${typeToString(type.elements)}^${type.dimensions[0]}>`;
3212
- }
3213
- } else if (type.dimensions.length === 2) {
3214
- const dims = type.dimensions;
3215
- if (type.elements === "number") {
3216
- if (dims[0] < 0 && dims[1] < 0) result = "matrix";
3217
- else result = `matrix<${dims[0]}x${dims[1]}>`;
3218
- } else {
3219
- if (dims[0] < 0 && dims[1] < 0)
3220
- result = `matrix<${typeToString(type.elements)}>`;
3221
- else
3222
- result = `matrix<${typeToString(type.elements)}^(${dims[0]}x${dims[1]})>`;
3223
- }
3224
- }
3225
- }
3226
- if (!result) {
3227
- const dimensions = type.dimensions ? type.dimensions.length === 1 ? `^${type.dimensions[0].toString()}` : `^(${type.dimensions.join("x")})` : "";
3228
- result = `list<${typeToString(type.elements)}${dimensions}>`;
3229
- }
3230
- break;
3231
- case "record":
3232
- const elements = Object.entries(type.elements).map(([key, value]) => `${key}: ${typeToString(value)}`).join(", ");
3233
- result = `record<${elements}>`;
3234
- break;
3235
- case "dictionary":
3236
- result = `dictionary<${typeToString(type.values)}>`;
3237
- break;
3238
- case "set":
3239
- result = `set<${typeToString(type.elements)}>`;
3240
- break;
3241
- case "collection":
3242
- result = `collection<${typeToString(type.elements)}>`;
3243
- break;
3244
- case "indexed_collection":
3245
- result = `indexed_collection<${typeToString(type.elements)}>`;
3246
- break;
3247
- case "tuple":
3248
- if (type.elements.length === 0) result = "tuple";
3249
- else if (type.elements.length === 1) {
3250
- const [el] = type.elements;
3251
- result = `tuple<${namedElement(el)}>`;
3252
- } else {
3253
- result = "tuple<" + type.elements.map((el) => namedElement(el)).join(", ") + ">";
3254
- }
3255
- break;
3256
- case "signature":
3257
- const args = type.args ? type.args.map((arg) => namedElement(arg)).join(", ") : "";
3258
- const optArgs = type.optArgs ? type.optArgs.map((arg) => namedElement(arg) + "?").join(", ") : "";
3259
- const varArg = type.variadicArg ? type.variadicMin === 0 ? `${namedElement(type.variadicArg)}*` : `${namedElement(type.variadicArg)}+` : "";
3260
- const argsList = [args, optArgs, varArg].filter((s) => s).join(", ");
3261
- result = `(${argsList}) -> ${typeToString(type.result)}`;
3262
- break;
3263
- default:
3264
- result = "error";
3265
- }
3266
- if (precedence > 0 && precedence > getPrecedence(type.kind))
3267
- return `(${result})`;
3268
- return result;
3269
- }
3270
- function namedElement(el) {
3271
- if (el.name) return `${el.name}: ${typeToString(el.type)}`;
3272
- return typeToString(el.type);
3273
- }
3274
- function symbolName(name) {
3275
- if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) return name;
3276
- return `\`${name}\``;
3277
- }
3278
- function getPrecedence(kind) {
3279
- switch (kind) {
3280
- case "negation":
3281
- return NEGATION_PRECEDENCE;
3282
- case "union":
3283
- return UNION_PRECEDENCE;
3284
- case "intersection":
3285
- return INTERSECTION_PRECEDENCE;
3286
- case "list":
3287
- return LIST_PRECEDENCE;
3288
- case "record":
3289
- return RECORD_PRECEDENCE;
3290
- case "dictionary":
3291
- return DICTIONARY_PRECEDENCE;
3292
- case "set":
3293
- return SET_PRECEDENCE;
3294
- case "collection":
3295
- case "indexed_collection":
3296
- return COLLECTION_PRECEDENCE;
3297
- case "tuple":
3298
- return TUPLE_PRECEDENCE;
3299
- case "signature":
3300
- return SIGNATURE_PRECEDENCE;
3301
- case "value":
3302
- return VALUE_PRECEDENCE;
3303
- default:
3304
- return 0;
3305
- }
3303
+ return t.kind === "signature" || t.kind === "union" || t.kind === "intersection" || t.kind === "negation" || t.kind === "value" || t.kind === "tuple" || t.kind === "list" || t.kind === "record" || t.kind === "dictionary" || t.kind === "set" || t.kind === "symbol" || t.kind === "expression" || t.kind === "numeric" || t.kind === "collection" || t.kind === "indexed_collection" || t.kind === "reference";
3306
3304
  }
3307
3305
 
3308
3306
  // src/common/type/lexer.ts
@@ -4012,19 +4010,13 @@ var Parser = class {
4012
4010
  );
4013
4011
  let dimensions;
4014
4012
  if (this.match("<")) {
4015
- dimensions = this.parseDimensionWithX();
4016
- if (!dimensions) {
4017
- dimensions = this.parseDimensions();
4018
- }
4013
+ dimensions = this.parseDimensions();
4019
4014
  if (!dimensions) {
4020
4015
  const type = this.parseUnionType();
4021
4016
  if (type) {
4022
4017
  elementType = type;
4023
4018
  if (this.match("^")) {
4024
- dimensions = this.parseDimensionWithX();
4025
- if (!dimensions) {
4026
- dimensions = this.parseDimensions();
4027
- }
4019
+ dimensions = this.parseCaretDimensions();
4028
4020
  }
4029
4021
  }
4030
4022
  }
@@ -4065,19 +4057,13 @@ var Parser = class {
4065
4057
  );
4066
4058
  let dimensions;
4067
4059
  if (this.match("<")) {
4068
- dimensions = this.parseDimensionWithX();
4069
- if (!dimensions) {
4070
- dimensions = this.parseDimensions();
4071
- }
4060
+ dimensions = this.parseDimensions();
4072
4061
  if (!dimensions) {
4073
4062
  const type = this.parseUnionType();
4074
4063
  if (type) {
4075
4064
  elementType = type;
4076
4065
  if (this.match("^")) {
4077
- dimensions = this.parseDimensionWithX();
4078
- if (!dimensions) {
4079
- dimensions = this.parseDimensions();
4080
- }
4066
+ dimensions = this.parseCaretDimensions();
4081
4067
  }
4082
4068
  }
4083
4069
  }
@@ -4108,16 +4094,30 @@ var Parser = class {
4108
4094
  return this.createNode("tensor", { elementType });
4109
4095
  }
4110
4096
  parseDimensions() {
4111
- const dimensions = [];
4112
4097
  const firstDim = this.parseDimension();
4113
4098
  if (!firstDim) return void 0;
4114
- dimensions.push(firstDim);
4115
- while (this.match("x")) {
4116
- const dim = this.parseDimension();
4117
- if (!dim) {
4118
- this.error("Expected dimension after x");
4099
+ const dimensions = [firstDim];
4100
+ for (; ; ) {
4101
+ const tok = this.current;
4102
+ if (tok.type === "IDENTIFIER" && /^(x\d+)+$/.test(tok.value)) {
4103
+ this.advance();
4104
+ for (const m of tok.value.match(/x(\d+)/g))
4105
+ dimensions.push(
4106
+ this.createNode("dimension", {
4107
+ size: parseInt(m.slice(1))
4108
+ })
4109
+ );
4110
+ } else if (tok.type === "IDENTIFIER" && tok.value === "x") {
4111
+ const next = this.lexer.peekToken();
4112
+ if (next.type !== "NUMBER_LITERAL" && next.type !== "?")
4113
+ this.error(
4114
+ "Expected a positive integer literal or `?` after x. For example: `2x3` or `2x?`"
4115
+ );
4116
+ this.advance();
4117
+ dimensions.push(this.parseDimension());
4118
+ } else {
4119
+ break;
4119
4120
  }
4120
- dimensions.push(dim);
4121
4121
  }
4122
4122
  return dimensions;
4123
4123
  }
@@ -4131,35 +4131,11 @@ var Parser = class {
4131
4131
  }
4132
4132
  return void 0;
4133
4133
  }
4134
- parseDimensionWithX() {
4135
- if (this.current.type === "NUMBER_LITERAL") {
4136
- const dimensions = [];
4137
- const firstDim = parseInt(this.advance().value);
4138
- dimensions.push(
4139
- this.createNode("dimension", { size: firstDim })
4140
- );
4141
- if (this.current.type === "IDENTIFIER" && this.current.value.startsWith("x")) {
4142
- const dimString = this.current.value;
4143
- const matches = dimString.match(/x(\d+)/g);
4144
- if (matches && matches.join("") === dimString) {
4145
- this.advance();
4146
- for (const match of matches) {
4147
- const dimValue = parseInt(match.substring(1));
4148
- dimensions.push(
4149
- this.createNode("dimension", { size: dimValue })
4150
- );
4151
- }
4152
- } else if (dimString === "x" || dimString.startsWith("x")) {
4153
- this.error(
4154
- "Expected a positive integer literal or `?` after x. For example: `2x3` or `2x?`"
4155
- );
4156
- }
4157
- }
4158
- if (dimensions.length > 1) {
4159
- return dimensions;
4160
- }
4161
- }
4162
- return void 0;
4134
+ parseCaretDimensions() {
4135
+ const paren = this.match("(");
4136
+ const dimensions = this.parseDimensions();
4137
+ if (paren) this.expect(")");
4138
+ return dimensions;
4163
4139
  }
4164
4140
  parseTupleType() {
4165
4141
  if (this.current.type === "IDENTIFIER" && this.current.value === "tuple") {
@@ -4344,6 +4320,18 @@ var Parser = class {
4344
4320
  this.expect("..");
4345
4321
  const upperBound = this.parseValue();
4346
4322
  this.expect(">");
4323
+ const lower = lowerBound?.value ?? -Infinity;
4324
+ const upper = upperBound?.value ?? Infinity;
4325
+ if (Number.isNaN(lower) || Number.isNaN(upper))
4326
+ this.error(
4327
+ "Invalid numeric type",
4328
+ "Lower and upper bounds must be valid numbers"
4329
+ );
4330
+ if (lower > upper)
4331
+ this.error(
4332
+ `Invalid range: ${lower}..${upper}`,
4333
+ "The lower bound must be less than the upper bound"
4334
+ );
4347
4335
  return this.createNode("numeric", {
4348
4336
  baseType,
4349
4337
  lowerBound,
@@ -4358,7 +4346,7 @@ var Parser = class {
4358
4346
  parsePrimitiveType() {
4359
4347
  if (this.current.type === "IDENTIFIER") {
4360
4348
  const name = this.current.value;
4361
- if (PRIMITIVE_TYPES.includes(name)) {
4349
+ if (PRIMITIVE_TYPES_SET.has(name)) {
4362
4350
  this.advance();
4363
4351
  return this.createNode("primitive", { name });
4364
4352
  }
@@ -4692,14 +4680,32 @@ function buildTypeFromAST(node, typeResolver) {
4692
4680
  }
4693
4681
 
4694
4682
  // src/common/type/parse.ts
4683
+ var TYPE_CACHE = /* @__PURE__ */ new Map();
4684
+ var TYPE_CACHE_MAX_SIZE = 2048;
4685
+ function deepFreeze(obj) {
4686
+ if (obj === null || typeof obj !== "object") return obj;
4687
+ if (Object.isFrozen(obj)) return obj;
4688
+ Object.freeze(obj);
4689
+ for (const value of Object.values(obj)) deepFreeze(value);
4690
+ return obj;
4691
+ }
4695
4692
  function parseType(s, typeResolver) {
4696
4693
  if (s === void 0) return void 0;
4697
4694
  if (isValidType(s)) return s;
4698
4695
  if (typeof s !== "string") return void 0;
4696
+ const cacheable = typeResolver === void 0;
4697
+ if (cacheable) {
4698
+ const cached = TYPE_CACHE.get(s);
4699
+ if (cached !== void 0) return cached;
4700
+ }
4699
4701
  try {
4700
4702
  const parser = new Parser(s, { typeResolver });
4701
4703
  const ast = parser.parseType();
4702
4704
  const type = buildTypeFromAST(ast, typeResolver);
4705
+ if (cacheable) {
4706
+ if (TYPE_CACHE.size >= TYPE_CACHE_MAX_SIZE) TYPE_CACHE.clear();
4707
+ TYPE_CACHE.set(s, deepFreeze(type));
4708
+ }
4703
4709
  return type;
4704
4710
  } catch (error) {
4705
4711
  throw new Error(
@@ -4774,19 +4780,36 @@ var PRIMITIVE_SUBTYPES = {
4774
4780
  color: [],
4775
4781
  expression: EXPRESSION_TYPES
4776
4782
  };
4783
+ var PRIMITIVE_SUBTYPES_CLOSURE = (() => {
4784
+ const closure = {};
4785
+ const closeOver = (t) => {
4786
+ if (closure[t]) return closure[t];
4787
+ const result = /* @__PURE__ */ new Set([t]);
4788
+ closure[t] = result;
4789
+ for (const sub2 of PRIMITIVE_SUBTYPES[t]) {
4790
+ if (sub2 === t) continue;
4791
+ for (const s of closeOver(sub2)) result.add(s);
4792
+ }
4793
+ return result;
4794
+ };
4795
+ for (const t of Object.keys(PRIMITIVE_SUBTYPES))
4796
+ closeOver(t);
4797
+ return closure;
4798
+ })();
4777
4799
  function isPrimitiveSubtype(lhs, rhs) {
4778
4800
  if (rhs === "any") return true;
4779
4801
  if (lhs === "never") return true;
4780
4802
  if (lhs === "unknown" || rhs === "unknown") return false;
4781
4803
  if (lhs === rhs) return true;
4782
- return PRIMITIVE_SUBTYPES[rhs].includes(lhs);
4804
+ return PRIMITIVE_SUBTYPES_CLOSURE[rhs].has(lhs);
4783
4805
  }
4784
4806
  function isSubtype(lhs, rhs) {
4785
- if (typeof lhs === "string" && !PRIMITIVE_TYPES.includes(lhs))
4807
+ if (typeof lhs === "string" && !PRIMITIVE_TYPES_SET.has(lhs))
4786
4808
  lhs = parseType(lhs);
4787
- if (typeof rhs === "string" && !PRIMITIVE_TYPES.includes(rhs))
4809
+ if (typeof rhs === "string" && !PRIMITIVE_TYPES_SET.has(rhs))
4788
4810
  rhs = parseType(rhs);
4789
4811
  if (rhs === "any") return true;
4812
+ if (lhs === "never") return true;
4790
4813
  if (rhs === "never") return false;
4791
4814
  if (rhs === "error") return lhs === "error";
4792
4815
  if (rhs === "nothing") return lhs === "nothing";
@@ -4801,7 +4824,7 @@ function isSubtype(lhs, rhs) {
4801
4824
  if (typeof lhs.value === "number") {
4802
4825
  if (Number.isInteger(lhs.value))
4803
4826
  return isPrimitiveSubtype("integer", rhs);
4804
- return isPrimitiveSubtype("number", rhs);
4827
+ return isPrimitiveSubtype("real", rhs);
4805
4828
  }
4806
4829
  if (typeof lhs.value === "boolean")
4807
4830
  return isPrimitiveSubtype("boolean", rhs);
@@ -5031,7 +5054,7 @@ function isSubtype(lhs, rhs) {
5031
5054
  }
5032
5055
  function isNumeric(type) {
5033
5056
  if (typeof type === "string")
5034
- return NUMERIC_TYPES.includes(type);
5057
+ return NUMERIC_TYPES_SET.has(type);
5035
5058
  if (type.kind === "value") return typeof type.value === "number";
5036
5059
  if (type.kind === "numeric") return true;
5037
5060
  return false;
@@ -5039,7 +5062,7 @@ function isNumeric(type) {
5039
5062
  function isScalar(type) {
5040
5063
  if (isNumeric(type)) return true;
5041
5064
  if (typeof type === "string")
5042
- return SCALAR_TYPES.includes(type);
5065
+ return SCALAR_TYPES_SET.has(type);
5043
5066
  if (type.kind === "value")
5044
5067
  return ["string", "boolean", "number"].includes(typeof type.value);
5045
5068
  return false;
@@ -5047,7 +5070,7 @@ function isScalar(type) {
5047
5070
  function isCollection(type) {
5048
5071
  if (isIndexedCollection(type)) return true;
5049
5072
  if (typeof type === "string")
5050
- return COLLECTION_TYPES.includes(type);
5073
+ return COLLECTION_TYPES_SET.has(type);
5051
5074
  return ["collection", "set", "record", "dictionary"].includes(type.kind);
5052
5075
  }
5053
5076
  function isIndexedCollection(type) {
@@ -5086,7 +5109,7 @@ function narrow2(a, b) {
5086
5109
  if (b === "unknown") return a;
5087
5110
  if (isSubtype(a, b)) return a;
5088
5111
  if (isSubtype(b, a)) return b;
5089
- return superType(a, b);
5112
+ return "never";
5090
5113
  }
5091
5114
  function widen2(a, b) {
5092
5115
  if (a === b) return a;
@@ -5099,7 +5122,43 @@ function widen2(a, b) {
5099
5122
  if (b === "nothing") return a;
5100
5123
  if (isSubtype(a, b)) return b;
5101
5124
  if (isSubtype(b, a)) return a;
5102
- return superType(a, b);
5125
+ const sup = superType(a, b);
5126
+ if (LOSSY_SUPERTYPE.has(sup)) return unionTypes(a, b);
5127
+ return sup;
5128
+ }
5129
+ var LOSSY_SUPERTYPE = /* @__PURE__ */ new Set([
5130
+ "scalar",
5131
+ "value",
5132
+ "function",
5133
+ "expression",
5134
+ "collection",
5135
+ "indexed_collection",
5136
+ "list",
5137
+ "set",
5138
+ "tuple",
5139
+ "record",
5140
+ "dictionary",
5141
+ "map",
5142
+ "any"
5143
+ ]);
5144
+ function unionTypes(a, b) {
5145
+ const members = [];
5146
+ const keys = /* @__PURE__ */ new Set();
5147
+ const push = (t) => {
5148
+ if (typeof t === "object" && t.kind === "union") {
5149
+ for (const m of t.types) push(m);
5150
+ return;
5151
+ }
5152
+ const key = typeof t === "string" ? t : JSON.stringify(t);
5153
+ if (!keys.has(key)) {
5154
+ keys.add(key);
5155
+ members.push(t);
5156
+ }
5157
+ };
5158
+ push(a);
5159
+ push(b);
5160
+ if (members.length === 1) return members[0];
5161
+ return { kind: "union", types: members };
5103
5162
  }
5104
5163
  function narrow(...types) {
5105
5164
  if (types.length === 0) return "nothing";
@@ -5111,6 +5170,32 @@ function widen(...types) {
5111
5170
  if (types.length === 1) return types[0];
5112
5171
  return types.reduce((a, b) => widen2(a, b));
5113
5172
  }
5173
+ var SUPERTYPE_PROBE_ORDER = [
5174
+ "non_finite_number",
5175
+ "finite_integer",
5176
+ "integer",
5177
+ "finite_rational",
5178
+ "rational",
5179
+ "finite_real",
5180
+ "real",
5181
+ "imaginary",
5182
+ "finite_complex",
5183
+ "complex",
5184
+ "finite_number",
5185
+ "number",
5186
+ "list",
5187
+ "record",
5188
+ "dictionary",
5189
+ "set",
5190
+ "tuple",
5191
+ "indexed_collection",
5192
+ "collection",
5193
+ "scalar",
5194
+ "value",
5195
+ "function",
5196
+ "expression"
5197
+ ];
5198
+ var PRIMITIVE_SUPERTYPE_CACHE = /* @__PURE__ */ new Map();
5114
5199
  function superType(a, b) {
5115
5200
  if (a === b) return a;
5116
5201
  if (a === "any" || b === "any") return "any";
@@ -5120,34 +5205,185 @@ function superType(a, b) {
5120
5205
  if (b === "unknown") return a;
5121
5206
  if (a === "nothing") return b;
5122
5207
  if (b === "nothing") return a;
5123
- if (commonSupertype(a, b, "non_finite_number")) return "non_finite_number";
5124
- if (commonSupertype(a, b, "finite_integer")) return "finite_integer";
5125
- if (commonSupertype(a, b, "integer")) return "integer";
5126
- if (commonSupertype(a, b, "finite_rational")) return "finite_rational";
5127
- if (commonSupertype(a, b, "rational")) return "rational";
5128
- if (commonSupertype(a, b, "finite_real")) return "finite_real";
5129
- if (commonSupertype(a, b, "real")) return "real";
5130
- if (commonSupertype(a, b, "imaginary")) return "imaginary";
5131
- if (commonSupertype(a, b, "finite_complex")) return "finite_complex";
5132
- if (commonSupertype(a, b, "complex")) return "complex";
5133
- if (commonSupertype(a, b, "finite_number")) return "finite_number";
5134
- if (commonSupertype(a, b, "number")) return "number";
5135
- if (commonSupertype(a, b, "list")) return "list";
5136
- if (commonSupertype(a, b, "record")) return "record";
5137
- if (commonSupertype(a, b, "dictionary")) return "dictionary";
5138
- if (commonSupertype(a, b, "set")) return "set";
5139
- if (commonSupertype(a, b, "tuple")) return "tuple";
5140
- if (commonSupertype(a, b, "indexed_collection")) return "indexed_collection";
5141
- if (commonSupertype(a, b, "collection")) return "collection";
5142
- if (commonSupertype(a, b, "scalar")) return "scalar";
5143
- if (commonSupertype(a, b, "value")) return "value";
5144
- if (commonSupertype(a, b, "function")) return "function";
5145
- if (commonSupertype(a, b, "expression")) return "expression";
5208
+ if (typeof a === "string" && typeof b === "string") {
5209
+ const key = a < b ? `${a}|${b}` : `${b}|${a}`;
5210
+ let result = PRIMITIVE_SUPERTYPE_CACHE.get(key);
5211
+ if (result === void 0) {
5212
+ result = "any";
5213
+ for (const ancestor of SUPERTYPE_PROBE_ORDER) {
5214
+ const subtypes = PRIMITIVE_SUBTYPES_CLOSURE[ancestor];
5215
+ if (subtypes.has(a) && subtypes.has(b)) {
5216
+ result = ancestor;
5217
+ break;
5218
+ }
5219
+ }
5220
+ PRIMITIVE_SUPERTYPE_CACHE.set(key, result);
5221
+ }
5222
+ return result;
5223
+ }
5224
+ for (const ancestor of SUPERTYPE_PROBE_ORDER)
5225
+ if (isSubtype(a, ancestor) && isSubtype(b, ancestor)) return ancestor;
5146
5226
  return "any";
5147
5227
  }
5148
- function commonSupertype(a, b, ancestor) {
5149
- if (isSubtype(a, ancestor) && isSubtype(b, ancestor)) return true;
5150
- return false;
5228
+
5229
+ // src/common/type/serialize.ts
5230
+ var NEGATION_PRECEDENCE = 3;
5231
+ var UNION_PRECEDENCE = 1;
5232
+ var INTERSECTION_PRECEDENCE = 2;
5233
+ var LIST_PRECEDENCE = 4;
5234
+ var RECORD_PRECEDENCE = 5;
5235
+ var DICTIONARY_PRECEDENCE = 6;
5236
+ var SET_PRECEDENCE = 7;
5237
+ var COLLECTION_PRECEDENCE = 8;
5238
+ var TUPLE_PRECEDENCE = 9;
5239
+ var SIGNATURE_PRECEDENCE = 10;
5240
+ var VALUE_PRECEDENCE = 11;
5241
+ function typeToString(type, precedence = 0) {
5242
+ if (typeof type === "string") return type;
5243
+ let result = "";
5244
+ switch (type.kind) {
5245
+ case "value":
5246
+ if (typeof type.value === "string") result = `"${type.value}"`;
5247
+ else if (typeof type.value === "boolean")
5248
+ result = type.value ? "true" : "false";
5249
+ else result = type.value.toString();
5250
+ break;
5251
+ case "reference":
5252
+ result = type.name;
5253
+ break;
5254
+ case "negation":
5255
+ result = `!${typeToString(type.type, NEGATION_PRECEDENCE)}`;
5256
+ break;
5257
+ case "union":
5258
+ result = type.types.map((t) => typeToString(t, UNION_PRECEDENCE)).join(" | ");
5259
+ break;
5260
+ case "intersection":
5261
+ result = type.types.map((t) => typeToString(t, INTERSECTION_PRECEDENCE)).join(" & ");
5262
+ break;
5263
+ case "expression":
5264
+ result = `expression<${symbolName(type.operator)}>`;
5265
+ break;
5266
+ case "symbol":
5267
+ result = `symbol<${symbolName(type.name)}>`;
5268
+ break;
5269
+ case "numeric":
5270
+ if (Number.isFinite(type.lower) && Number.isFinite(type.upper)) {
5271
+ result = `${type.type}<${type.lower}..${type.upper}>`;
5272
+ } else if (Number.isFinite(type.lower)) {
5273
+ result = `${type.type}<${type.lower}..>`;
5274
+ } else if (Number.isFinite(type.upper)) {
5275
+ result = `${type.type}<..${type.upper}>`;
5276
+ } else {
5277
+ result = `${type.type}`;
5278
+ }
5279
+ break;
5280
+ case "list":
5281
+ if (type.dimensions && typeof type.elements === "string" && NUMERIC_TYPES_SET.has(type.elements)) {
5282
+ if (type.dimensions === void 0) {
5283
+ if (type.elements === "number") result = "tensor";
5284
+ } else if (type.dimensions.length === 1) {
5285
+ if (type.elements === "number") {
5286
+ if (type.dimensions[0] < 0) result = "vector";
5287
+ else result = `vector<${type.dimensions[0]}>`;
5288
+ } else {
5289
+ if (type.dimensions[0] < 0)
5290
+ result = `vector<${typeToString(type.elements)}>`;
5291
+ else
5292
+ result = `vector<${typeToString(type.elements)}^${type.dimensions[0]}>`;
5293
+ }
5294
+ } else if (type.dimensions.length === 2) {
5295
+ const dims = type.dimensions;
5296
+ if (type.elements === "number") {
5297
+ if (dims[0] < 0 && dims[1] < 0) result = "matrix";
5298
+ else result = `matrix<${dims[0]}x${dims[1]}>`;
5299
+ } else {
5300
+ if (dims[0] < 0 && dims[1] < 0)
5301
+ result = `matrix<${typeToString(type.elements)}>`;
5302
+ else
5303
+ result = `matrix<${typeToString(type.elements)}^(${dims[0]}x${dims[1]})>`;
5304
+ }
5305
+ }
5306
+ }
5307
+ if (!result) {
5308
+ const dimensions = type.dimensions ? type.dimensions.length === 1 ? `^${type.dimensions[0].toString()}` : `^(${type.dimensions.join("x")})` : "";
5309
+ result = `list<${typeToString(type.elements)}${dimensions}>`;
5310
+ }
5311
+ break;
5312
+ case "record":
5313
+ const elements = Object.entries(type.elements).map(([key, value]) => `${key}: ${typeToString(value)}`).join(", ");
5314
+ result = `record<${elements}>`;
5315
+ break;
5316
+ case "dictionary":
5317
+ result = `dictionary<${typeToString(type.values)}>`;
5318
+ break;
5319
+ case "set":
5320
+ result = `set<${typeToString(type.elements)}>`;
5321
+ break;
5322
+ case "collection":
5323
+ result = `collection<${typeToString(type.elements)}>`;
5324
+ break;
5325
+ case "indexed_collection":
5326
+ result = `indexed_collection<${typeToString(type.elements)}>`;
5327
+ break;
5328
+ case "tuple":
5329
+ if (type.elements.length === 0) result = "tuple";
5330
+ else if (type.elements.length === 1) {
5331
+ const [el] = type.elements;
5332
+ result = `tuple<${namedElement(el)}>`;
5333
+ } else {
5334
+ result = "tuple<" + type.elements.map((el) => namedElement(el)).join(", ") + ">";
5335
+ }
5336
+ break;
5337
+ case "signature":
5338
+ const args = type.args ? type.args.map((arg) => namedElement(arg)).join(", ") : "";
5339
+ const optArgs = type.optArgs ? type.optArgs.map((arg) => namedElement(arg) + "?").join(", ") : "";
5340
+ const varArg = type.variadicArg ? type.variadicMin === 0 ? `${namedElement(type.variadicArg)}*` : `${namedElement(type.variadicArg)}+` : "";
5341
+ const argsList = [args, optArgs, varArg].filter((s) => s).join(", ");
5342
+ result = `(${argsList}) -> ${typeToString(type.result)}`;
5343
+ break;
5344
+ default:
5345
+ result = "error";
5346
+ }
5347
+ if (precedence > 0 && precedence > getPrecedence(type.kind))
5348
+ return `(${result})`;
5349
+ return result;
5350
+ }
5351
+ function namedElement(el) {
5352
+ if (el.name) return `${el.name}: ${typeToString(el.type)}`;
5353
+ return typeToString(el.type);
5354
+ }
5355
+ function symbolName(name) {
5356
+ if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) return name;
5357
+ return `\`${name}\``;
5358
+ }
5359
+ function getPrecedence(kind) {
5360
+ switch (kind) {
5361
+ case "negation":
5362
+ return NEGATION_PRECEDENCE;
5363
+ case "union":
5364
+ return UNION_PRECEDENCE;
5365
+ case "intersection":
5366
+ return INTERSECTION_PRECEDENCE;
5367
+ case "list":
5368
+ return LIST_PRECEDENCE;
5369
+ case "record":
5370
+ return RECORD_PRECEDENCE;
5371
+ case "dictionary":
5372
+ return DICTIONARY_PRECEDENCE;
5373
+ case "set":
5374
+ return SET_PRECEDENCE;
5375
+ case "collection":
5376
+ case "indexed_collection":
5377
+ return COLLECTION_PRECEDENCE;
5378
+ case "tuple":
5379
+ return TUPLE_PRECEDENCE;
5380
+ case "signature":
5381
+ return SIGNATURE_PRECEDENCE;
5382
+ case "value":
5383
+ return VALUE_PRECEDENCE;
5384
+ default:
5385
+ return 0;
5386
+ }
5151
5387
  }
5152
5388
 
5153
5389
  // src/common/type/boxed-type.ts
@@ -5207,6 +5443,12 @@ var BoxedType = class _BoxedType {
5207
5443
  }
5208
5444
  };
5209
5445
 
5446
+ // src/compute-engine/boxed-expression/constraint-subject.ts
5447
+ var EMPTY_FACT_INDEX = Object.freeze({
5448
+ bySubject: /* @__PURE__ */ new Map(),
5449
+ membership: /* @__PURE__ */ new Map()
5450
+ });
5451
+
5210
5452
  // src/compute-engine/boxed-expression/stochastic-equal.ts
5211
5453
  var WELL_KNOWN_POINTS = [
5212
5454
  0,
@@ -5312,12 +5554,14 @@ function dictionaryFromExpression(expr) {
5312
5554
  if (expr === null) return null;
5313
5555
  if (isDictionaryObject(expr)) return expr;
5314
5556
  const kv = keyValuePair(expr);
5315
- if (kv) return { [kv[0]]: kv[1] };
5557
+ if (kv)
5558
+ return {
5559
+ dict: { [kv[0]]: expressionToDictionaryValue(kv[1]) ?? "Nothing" }
5560
+ };
5316
5561
  if (operator(expr) === "Dictionary") {
5317
5562
  const dict = {};
5318
- const ops = operands(expr);
5319
- for (let i = 1; i < nops(expr); i++) {
5320
- const kv2 = keyValuePair(ops[i]);
5563
+ for (const op of operands(expr)) {
5564
+ const kv2 = keyValuePair(op);
5321
5565
  if (kv2) {
5322
5566
  dict[kv2[0]] = expressionToDictionaryValue(kv2[1]) ?? "Nothing";
5323
5567
  }
@@ -6255,15 +6499,16 @@ var DEFINITIONS_CORE = [
6255
6499
  precedence: ASSIGNMENT_PRECEDENCE,
6256
6500
  parse: parseAssign
6257
6501
  },
6258
- // General colon operator (type annotation, mapping notation)
6259
- // Precedence below assignment (260) so `:=` takes priority,
6260
- // and below arrows (270) so `f: A \to B` parses as `Colon(f, To(A, B))`
6502
+ // General colon operator (type annotation, mapping notation, Desmos piecewise)
6503
+ // Precedence below comparisons (245) so `cond : val` (Desmos compact piecewise)
6504
+ // parses as `Colon(cond, val)`, and below arrows (270) so
6505
+ // `f: A \to B` parses as `Colon(f, To(A, B))`.
6261
6506
  {
6262
6507
  name: "Colon",
6263
6508
  latexTrigger: ":",
6264
6509
  kind: "infix",
6265
6510
  associativity: "right",
6266
- precedence: 250,
6511
+ precedence: 240,
6267
6512
  serialize: (serializer, expr) => joinLatex([
6268
6513
  serializer.serialize(operand(expr, 1)),
6269
6514
  "\\colon",
@@ -6274,7 +6519,7 @@ var DEFINITIONS_CORE = [
6274
6519
  latexTrigger: "\\colon",
6275
6520
  kind: "infix",
6276
6521
  associativity: "right",
6277
- precedence: 250,
6522
+ precedence: 240,
6278
6523
  parse: "Colon"
6279
6524
  },
6280
6525
  {
@@ -7250,6 +7495,7 @@ var DEFINITIONS_CORE = [
7250
7495
  }
7251
7496
  }
7252
7497
  if (!variable) return null;
7498
+ if (symbol(variable) === null) return null;
7253
7499
  parser.skipSpace();
7254
7500
  const fn = parser.parseExpression({ minPrec: 740 });
7255
7501
  if (!fn) return null;
@@ -7436,7 +7682,7 @@ function parseTextRun(parser, style) {
7436
7682
  if (runs.length === 1) body = runs[0];
7437
7683
  else {
7438
7684
  if (runs.every((x) => stringValue(x) !== null))
7439
- body = "'" + runs.map((x) => stringValue(x)).join() + "'";
7685
+ body = "'" + runs.map((x) => stringValue(x)).join("") + "'";
7440
7686
  else body = ["Text", ...runs];
7441
7687
  }
7442
7688
  return style ? ["Annotated", body, dictionaryFromEntries(style)] : body;
@@ -7844,7 +8090,10 @@ function parseForComprehension(parser, lhs, until) {
7844
8090
  p.skipVisualSpace();
7845
8091
  const isComma = p.peek === ",";
7846
8092
  p.index = saved;
7847
- return isComma;
8093
+ if (isComma) return true;
8094
+ if (peekKeyword(p, "where")) return true;
8095
+ if (peekKeyword(p, "with")) return true;
8096
+ return false;
7848
8097
  }
7849
8098
  };
7850
8099
  const elements = [];
@@ -7885,6 +8134,25 @@ function parseWhereExpression(parser, lhs, until) {
7885
8134
  parser.skipVisualSpace();
7886
8135
  } while (parser.match(","));
7887
8136
  if (bindings.length === 0) return null;
8137
+ const forStart = parser.index;
8138
+ if (matchKeyword(parser, "for")) {
8139
+ const loop = parseForComprehension(parser, lhs, until);
8140
+ if (loop) {
8141
+ const block2 = [];
8142
+ for (const b of bindings) {
8143
+ const normalized = normalizeLocalAssign(b);
8144
+ if (operator(normalized) === "Assign") {
8145
+ block2.push(["Declare", operand(normalized, 1)]);
8146
+ block2.push(normalized);
8147
+ } else {
8148
+ block2.push(normalized);
8149
+ }
8150
+ }
8151
+ block2.push(loop);
8152
+ return ["Block", ...block2];
8153
+ }
8154
+ parser.index = forStart;
8155
+ }
7888
8156
  const block = [];
7889
8157
  for (const b of bindings) {
7890
8158
  const normalized = normalizeLocalAssign(b);
@@ -8098,6 +8366,17 @@ function parseIntervalBody(body, openLeft, openRight) {
8098
8366
  const upperExpr = openRight ? ["Open", upper] : upper;
8099
8367
  return ["Interval", lowerExpr, upperExpr];
8100
8368
  }
8369
+ var COMPARISON_HEADS = /* @__PURE__ */ new Set([
8370
+ "Less",
8371
+ "LessEqual",
8372
+ "Greater",
8373
+ "GreaterEqual",
8374
+ "Equal",
8375
+ "NotEqual",
8376
+ "And",
8377
+ "Or",
8378
+ "Not"
8379
+ ]);
8101
8380
  var DEFINITIONS_SETS = [
8102
8381
  //
8103
8382
  // Constants
@@ -8356,18 +8635,58 @@ var DEFINITIONS_SETS = [
8356
8635
  closeTrigger: "}",
8357
8636
  parse: (_parser, body) => {
8358
8637
  if (isEmptySequence(body)) return "EmptySet";
8638
+ if (operator(body) == "Delimiter" && stringValue(operand(body, 2)) === ",") {
8639
+ body = operand(body, 1);
8640
+ }
8359
8641
  const h = operator(body);
8360
- if (h === "Divides" || h === "Colon") {
8642
+ if (h === "Divides") {
8361
8643
  const expr = operand(body, 1);
8362
8644
  const condition = operand(body, 2);
8363
8645
  if (expr !== null && condition !== null)
8364
8646
  return ["Set", expr, ["Condition", condition]];
8365
8647
  }
8366
- if (operator(body) == "Delimiter" && stringValue(operand(body, 2)) === ",") {
8367
- body = operand(body, 1);
8648
+ if (h === "Colon") {
8649
+ const lhs = operand(body, 1);
8650
+ const rhs = operand(body, 2);
8651
+ if (lhs !== null && rhs !== null) {
8652
+ const lhsOp = operator(lhs);
8653
+ if (lhsOp !== null && COMPARISON_HEADS.has(lhsOp)) {
8654
+ return ["Which", lhs, rhs];
8655
+ }
8656
+ return ["Set", lhs, ["Condition", rhs]];
8657
+ }
8368
8658
  }
8369
- if (operator(body) !== "Sequence") return ["Set", body];
8370
- return ["Set", ...operands(body)];
8659
+ if (h === "Sequence") {
8660
+ const elements = operands(body);
8661
+ const colonElements = elements.filter((el) => operator(el) === "Colon");
8662
+ const allPiecewise = colonElements.length > 0 && colonElements.every((el) => {
8663
+ const lhs = operand(el, 1);
8664
+ const lhsOp = lhs !== null ? operator(lhs) : null;
8665
+ return lhsOp !== null && COMPARISON_HEADS.has(lhsOp);
8666
+ });
8667
+ if (allPiecewise) {
8668
+ const whichOps = [];
8669
+ for (let i = 0; i < elements.length; i++) {
8670
+ const el = elements[i];
8671
+ if (operator(el) === "Colon") {
8672
+ const cond = operand(el, 1);
8673
+ const val = operand(el, 2);
8674
+ if (cond === null || val === null) {
8675
+ return ["Set", ...elements];
8676
+ }
8677
+ whichOps.push(cond, val);
8678
+ } else {
8679
+ if (i !== elements.length - 1) {
8680
+ return ["Set", ...elements];
8681
+ }
8682
+ whichOps.push("True", el);
8683
+ }
8684
+ }
8685
+ return ["Which", ...whichOps];
8686
+ }
8687
+ return ["Set", ...elements];
8688
+ }
8689
+ return ["Set", body];
8371
8690
  },
8372
8691
  serialize: (serializer, expr) => {
8373
8692
  if (nops(expr) === 2 && operator(operand(expr, 2)) === "Condition") {
@@ -8896,6 +9215,8 @@ function serializeMultiply(serializer, expr) {
8896
9215
  const h = operator(arg);
8897
9216
  if (prevWasNumber && (h === "Divide" || h === "Rational")) {
8898
9217
  result = latexTemplate(serializer.options.multiply, result, term);
9218
+ } else if (/^\d/.test(term)) {
9219
+ result = latexTemplate(serializer.options.multiply, result, term);
8899
9220
  } else if (!serializer.options.invisibleMultiply) {
8900
9221
  result = joinLatex([result, term]);
8901
9222
  } else {
@@ -10341,7 +10662,9 @@ function parseTrig(op) {
10341
10662
  minPrec: MULTIPLICATION_PRECEDENCE,
10342
10663
  condition: (parser2) => trigCommands[parser2.peek] || (until?.condition?.(parser2) ?? false)
10343
10664
  });
10344
- const appliedFn = args === null ? fn : typeof fn === "string" ? [fn, ...args] : ["Apply", fn, ...args];
10665
+ const isTwoArgArctan = args?.length === 2 && (fn === "Arctan" || Array.isArray(fn) && fn[0] === "InverseFunction" && fn[1] === "Tan");
10666
+ const head = isTwoArgArctan ? "Arctan2" : fn;
10667
+ const appliedFn = args === null ? fn : typeof head === "string" ? [head, ...args] : ["Apply", head, ...args];
10345
10668
  return sup === null ? appliedFn : ["Power", appliedFn, sup];
10346
10669
  };
10347
10670
  }
@@ -12464,10 +12787,17 @@ var DEFINITIONS_OTHERS = [
12464
12787
  // The capitalized library entries already exist; these are pure parse
12465
12788
  // aliases so the lowercase names don't land in `unsupported-operator`.
12466
12789
  // ---------------------------------------------------------------------------
12790
+ { latexTrigger: "\\operatorname{count}", parse: "Length" },
12467
12791
  { latexTrigger: "\\operatorname{random}", parse: "Random" },
12468
12792
  { latexTrigger: "\\operatorname{shuffle}", parse: "Shuffle" },
12469
12793
  { latexTrigger: "\\operatorname{repeat}", parse: "Repeat" },
12470
12794
  { latexTrigger: "\\operatorname{join}", parse: "Join" },
12795
+ { latexTrigger: "\\operatorname{range}", parse: "Range" },
12796
+ // Note: `\operatorname{with}` (Desmos's local-binding clause) is intentionally
12797
+ // NOT registered here. Use the math-notation equivalent `\operatorname{where}`
12798
+ // (with `\coloneq` for bindings), or register `with` as a custom dictionary
12799
+ // entry at the integration layer — see the "Desmos-Specific Syntax — Prefer
12800
+ // Custom LaTeX Dictionary" section in COMPUTE_ENGINE.md for a worked example.
12471
12801
  // ---------------------------------------------------------------------------
12472
12802
  // Geometric primitive heads. Registered as known typed heads so consumers
12473
12803
  // can branch on the operator name; CE itself doesn't render them. The
@@ -12620,6 +12950,30 @@ var POSSIBLE_EMOJI = `(?:${ZWJ_ELEMENT})(${ZWJ}${ZWJ_ELEMENT})*`;
12620
12950
  var SOME_EMOJI = new RegExp(`(?:${POSSIBLE_EMOJI})+`, "u");
12621
12951
  var EMOJIS = new RegExp(`^(?:${POSSIBLE_EMOJI})+$`, "u");
12622
12952
 
12953
+ // src/compute-engine/latex-syntax/parse.ts
12954
+ var PARSE_TOKEN_EXCLUDED = /* @__PURE__ */ new Set([
12955
+ ...'!"#$%&(),/;:?@[]\\`|~'.split(""),
12956
+ "\\left",
12957
+ "\\bigl",
12958
+ "\\mleft"
12959
+ ]);
12960
+ var TEX_UNIT_TOKENS = [
12961
+ "pt",
12962
+ "em",
12963
+ "mu",
12964
+ "ex",
12965
+ "mm",
12966
+ "cm",
12967
+ "in",
12968
+ "bp",
12969
+ "sp",
12970
+ "dd",
12971
+ "cc",
12972
+ "pc",
12973
+ "nc",
12974
+ "nd"
12975
+ ].map((unit) => [...unit]);
12976
+
12623
12977
  // src/compute-engine/boxed-expression/expand.ts
12624
12978
  var binomials = [
12625
12979
  [1],
@@ -12921,6 +13275,7 @@ function mod(a, b) {
12921
13275
  const period = Math.abs(
12922
13276
  bVal.lo === bVal.hi ? bVal.lo : Math.max(Math.abs(bVal.lo), Math.abs(bVal.hi))
12923
13277
  );
13278
+ const divisorNegative = bVal.hi < 0;
12924
13279
  const flo = Math.floor(aVal.lo / period);
12925
13280
  const fhi = Math.floor(aVal.hi / period);
12926
13281
  if (flo !== fhi) {
@@ -12928,6 +13283,11 @@ function mod(a, b) {
12928
13283
  }
12929
13284
  const modLo = aVal.lo - period * flo;
12930
13285
  const modHi = aVal.hi - period * flo;
13286
+ if (divisorNegative) {
13287
+ if (modLo === 0)
13288
+ return { kind: "singular", at: aVal.lo, continuity: "right" };
13289
+ return ok({ lo: modLo - period, hi: modHi - period });
13290
+ }
12931
13291
  return ok({ lo: Math.min(modLo, modHi), hi: Math.max(modLo, modHi) });
12932
13292
  }
12933
13293
  function remainder(a, b) {
@@ -12959,6 +13319,23 @@ function gamma2(x) {
12959
13319
  const [xVal] = unwrapped;
12960
13320
  return _gamma(xVal);
12961
13321
  }
13322
+ var GAMMA_NEG_EXTREMA_X = [
13323
+ -0.504083008264455,
13324
+ -1.573498473162391,
13325
+ -2.610720868444145,
13326
+ -3.635293366436901,
13327
+ -4.653163765628266,
13328
+ -5.667162441556885,
13329
+ -6.678418213073426,
13330
+ -7.687788325031709,
13331
+ -8.695764163640956,
13332
+ -9.702672540001863
13333
+ ];
13334
+ function gammaNegStripExtremum(lo) {
13335
+ const n = Math.floor(lo);
13336
+ const idx = -n - 1;
13337
+ return idx >= 0 && idx < GAMMA_NEG_EXTREMA_X.length ? GAMMA_NEG_EXTREMA_X[idx] : null;
13338
+ }
12962
13339
  function _gamma(x) {
12963
13340
  if (x.hi >= 0 && x.lo <= 0) {
12964
13341
  return { kind: "singular", at: 0 };
@@ -12971,7 +13348,21 @@ function _gamma(x) {
12971
13348
  }
12972
13349
  const gLo = gamma(x.lo);
12973
13350
  const gHi = gamma(x.hi);
12974
- return ok({ lo: Math.min(gLo, gHi), hi: Math.max(gLo, gHi) });
13351
+ let lo = Math.min(gLo, gHi);
13352
+ let hi = Math.max(gLo, gHi);
13353
+ const xStar = gammaNegStripExtremum(x.lo);
13354
+ if (xStar !== null) {
13355
+ if (xStar >= x.lo && xStar <= x.hi) {
13356
+ const g = gamma(xStar);
13357
+ lo = Math.min(lo, g);
13358
+ hi = Math.max(hi, g);
13359
+ }
13360
+ } else {
13361
+ const stripEven = Math.floor(x.lo) % 2 === 0;
13362
+ if (stripEven) lo = Math.min(lo, 0);
13363
+ else hi = Math.max(hi, 0);
13364
+ }
13365
+ return ok({ lo, hi });
12975
13366
  }
12976
13367
  if (x.lo >= GAMMA_MIN_X) {
12977
13368
  return ok({ lo: gamma(x.lo), hi: gamma(x.hi) });
@@ -13002,7 +13393,15 @@ function _gammaln(x) {
13002
13393
  }
13003
13394
  const gLo = gammaln(x.lo);
13004
13395
  const gHi = gammaln(x.hi);
13005
- return ok({ lo: Math.min(gLo, gHi), hi: Math.max(gLo, gHi) });
13396
+ let lo = Math.min(gLo, gHi);
13397
+ const hi = Math.max(gLo, gHi);
13398
+ const xStar = gammaNegStripExtremum(x.lo);
13399
+ if (xStar !== null) {
13400
+ if (xStar >= x.lo && xStar <= x.hi) lo = Math.min(lo, gammaln(xStar));
13401
+ } else {
13402
+ lo = -Infinity;
13403
+ }
13404
+ return ok({ lo, hi });
13006
13405
  }
13007
13406
  return ok({ lo: gammaln(x.lo), hi: gammaln(x.hi) });
13008
13407
  }
@@ -13028,6 +13427,33 @@ function factorial22(x) {
13028
13427
  return ok({ lo: Math.min(fLo, fHi), hi: Math.max(fLo, fHi) });
13029
13428
  return ok({ lo: fLo, hi: fHi });
13030
13429
  }
13430
+ var MAX_INT_ENUM_POINTS = 4096;
13431
+ function integerPoints(lo, hi, cap) {
13432
+ const a = Math.round(lo);
13433
+ const b = Math.round(hi);
13434
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
13435
+ if (b - a + 1 > cap) return null;
13436
+ const out = [];
13437
+ for (let i = a; i <= b; i++) out.push(i);
13438
+ return out;
13439
+ }
13440
+ function enumerateInteger2(a, b, f) {
13441
+ const xs = integerPoints(a.lo, a.hi, MAX_INT_ENUM_POINTS);
13442
+ const ys = integerPoints(b.lo, b.hi, MAX_INT_ENUM_POINTS);
13443
+ if (!xs || !ys || xs.length * ys.length > MAX_INT_ENUM_POINTS) return null;
13444
+ let lo = Infinity;
13445
+ let hi = -Infinity;
13446
+ for (const x of xs)
13447
+ for (const y of ys) {
13448
+ const v = f(x, y);
13449
+ if (Number.isFinite(v)) {
13450
+ if (v < lo) lo = v;
13451
+ if (v > hi) hi = v;
13452
+ }
13453
+ }
13454
+ if (lo === Infinity) return null;
13455
+ return ok({ lo, hi });
13456
+ }
13031
13457
  function binomial(n, k) {
13032
13458
  const uN = unwrapOrPropagate(n);
13033
13459
  if (!Array.isArray(uN)) return uN;
@@ -13035,13 +13461,10 @@ function binomial(n, k) {
13035
13461
  if (!Array.isArray(uK)) return uK;
13036
13462
  const [nVal] = uN;
13037
13463
  const [kVal] = uK;
13038
- const vals = [
13039
- choose(Math.round(nVal.lo), Math.round(kVal.lo)),
13040
- choose(Math.round(nVal.lo), Math.round(kVal.hi)),
13041
- choose(Math.round(nVal.hi), Math.round(kVal.lo)),
13042
- choose(Math.round(nVal.hi), Math.round(kVal.hi))
13043
- ];
13044
- return ok({ lo: Math.min(...vals), hi: Math.max(...vals) });
13464
+ const enumerated = enumerateInteger2(nVal, kVal, choose);
13465
+ if (enumerated) return enumerated;
13466
+ const nMax = Math.round(nVal.hi);
13467
+ return ok({ lo: 0, hi: choose(nMax, Math.floor(nMax / 2)) });
13045
13468
  }
13046
13469
  function gcd3(a, b) {
13047
13470
  const uA = unwrapOrPropagate(a);
@@ -13050,13 +13473,15 @@ function gcd3(a, b) {
13050
13473
  if (!Array.isArray(uB)) return uB;
13051
13474
  const [aVal] = uA;
13052
13475
  const [bVal] = uB;
13053
- const vals = [
13054
- gcd(Math.round(aVal.lo), Math.round(bVal.lo)),
13055
- gcd(Math.round(aVal.lo), Math.round(bVal.hi)),
13056
- gcd(Math.round(aVal.hi), Math.round(bVal.lo)),
13057
- gcd(Math.round(aVal.hi), Math.round(bVal.hi))
13058
- ];
13059
- return ok({ lo: Math.min(...vals), hi: Math.max(...vals) });
13476
+ const enumerated = enumerateInteger2(aVal, bVal, gcd);
13477
+ if (enumerated) return enumerated;
13478
+ const m = Math.max(
13479
+ Math.abs(Math.round(aVal.lo)),
13480
+ Math.abs(Math.round(aVal.hi)),
13481
+ Math.abs(Math.round(bVal.lo)),
13482
+ Math.abs(Math.round(bVal.hi))
13483
+ );
13484
+ return ok({ lo: 0, hi: m });
13060
13485
  }
13061
13486
  function lcm3(a, b) {
13062
13487
  const uA = unwrapOrPropagate(a);
@@ -13065,13 +13490,11 @@ function lcm3(a, b) {
13065
13490
  if (!Array.isArray(uB)) return uB;
13066
13491
  const [aVal] = uA;
13067
13492
  const [bVal] = uB;
13068
- const vals = [
13069
- lcm(Math.round(aVal.lo), Math.round(bVal.lo)),
13070
- lcm(Math.round(aVal.lo), Math.round(bVal.hi)),
13071
- lcm(Math.round(aVal.hi), Math.round(bVal.lo)),
13072
- lcm(Math.round(aVal.hi), Math.round(bVal.hi))
13073
- ];
13074
- return ok({ lo: Math.min(...vals), hi: Math.max(...vals) });
13493
+ const enumerated = enumerateInteger2(aVal, bVal, lcm);
13494
+ if (enumerated) return enumerated;
13495
+ const ma = Math.max(Math.abs(Math.round(aVal.lo)), Math.abs(Math.round(aVal.hi)));
13496
+ const mb = Math.max(Math.abs(Math.round(bVal.lo)), Math.abs(Math.round(bVal.hi)));
13497
+ return ok({ lo: 0, hi: ma * mb });
13075
13498
  }
13076
13499
  function chop2(x) {
13077
13500
  const unwrapped = unwrapOrPropagate(x);
@@ -13463,7 +13886,6 @@ var SINC_EXTREMA = [
13463
13886
  29.8116,
13464
13887
  32.95639
13465
13888
  ];
13466
- var SINC_GLOBAL_LO = -0.21724;
13467
13889
  function sinc(x) {
13468
13890
  const unwrapped = unwrapOrPropagate(x);
13469
13891
  if (!Array.isArray(unwrapped)) return unwrapped;
@@ -13484,8 +13906,14 @@ function sinc(x) {
13484
13906
  if (e >= xVal.lo && e <= xVal.hi) update(sincVal(e));
13485
13907
  if (-e >= xVal.lo && -e <= xVal.hi) update(sincVal(-e));
13486
13908
  }
13487
- if (Math.abs(xVal.lo) > lastExtremum || Math.abs(xVal.hi) > lastExtremum) {
13488
- update(SINC_GLOBAL_LO);
13909
+ let minBeyondAbs = Infinity;
13910
+ if (xVal.hi > lastExtremum)
13911
+ minBeyondAbs = Math.min(minBeyondAbs, Math.max(xVal.lo, lastExtremum));
13912
+ if (xVal.lo < -lastExtremum)
13913
+ minBeyondAbs = Math.min(minBeyondAbs, -Math.min(xVal.hi, -lastExtremum));
13914
+ if (Number.isFinite(minBeyondAbs) && minBeyondAbs > 0) {
13915
+ update(1 / minBeyondAbs);
13916
+ update(-1 / minBeyondAbs);
13489
13917
  }
13490
13918
  return ok({ lo, hi });
13491
13919
  }
@@ -13511,8 +13939,21 @@ function fresnelS2(x) {
13511
13939
  if (e >= xVal.lo && e <= xVal.hi) update(fresnelS(e));
13512
13940
  if (-e >= xVal.lo && -e <= xVal.hi) update(fresnelS(-e));
13513
13941
  }
13942
+ fresnelConvergenceBound(xVal, FRESNEL_S_EXTREMA, fresnelS, update);
13514
13943
  return ok({ lo, hi });
13515
13944
  }
13945
+ function fresnelConvergenceBound(xVal, extrema, scalar, update) {
13946
+ const lastE = extrema[extrema.length - 1];
13947
+ const amp = Math.abs(scalar(lastE) - 0.5);
13948
+ if (xVal.hi > lastE) {
13949
+ update(0.5 + amp);
13950
+ update(0.5 - amp);
13951
+ }
13952
+ if (xVal.lo < -lastE) {
13953
+ update(-0.5 - amp);
13954
+ update(-0.5 + amp);
13955
+ }
13956
+ }
13516
13957
  function fresnelC2(x) {
13517
13958
  const unwrapped = unwrapOrPropagate(x);
13518
13959
  if (!Array.isArray(unwrapped)) return unwrapped;
@@ -13529,6 +13970,7 @@ function fresnelC2(x) {
13529
13970
  if (e >= xVal.lo && e <= xVal.hi) update(fresnelC(e));
13530
13971
  if (-e >= xVal.lo && -e <= xVal.hi) update(fresnelC(-e));
13531
13972
  }
13973
+ fresnelConvergenceBound(xVal, FRESNEL_C_EXTREMA, fresnelC, update);
13532
13974
  return ok({ lo, hi });
13533
13975
  }
13534
13976
 
@@ -13636,11 +14078,9 @@ function clamp(x, lo, hi) {
13636
14078
  const unwrapped = unwrapOrPropagate(x, lo, hi);
13637
14079
  if (!Array.isArray(unwrapped)) return unwrapped;
13638
14080
  const [xVal, loVal, hiVal] = unwrapped;
13639
- const resultLo = Math.max(xVal.lo, loVal.lo);
13640
- const resultHi = Math.min(xVal.hi, hiVal.hi);
13641
- if (resultLo > resultHi) {
13642
- return { kind: "empty" };
13643
- }
14081
+ const lowered = { lo: Math.max(xVal.lo, loVal.lo), hi: Math.max(xVal.hi, loVal.hi) };
14082
+ const resultLo = Math.min(lowered.lo, hiVal.lo);
14083
+ const resultHi = Math.min(lowered.hi, hiVal.hi);
13644
14084
  return { kind: "interval", value: { lo: resultLo, hi: resultHi } };
13645
14085
  }
13646
14086
 
@@ -13746,7 +14186,7 @@ var IntervalArithmetic = {
13746
14186
  };
13747
14187
 
13748
14188
  // src/interval.ts
13749
- var version = "0.57.0";
14189
+ var version = "0.59.0";
13750
14190
  export {
13751
14191
  IntervalArithmetic,
13752
14192
  _mul,