@cortex-js/compute-engine 0.58.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 +1721 -483
  3. package/dist/compile.min.esm.js +122 -74
  4. package/dist/compile.min.umd.cjs +122 -74
  5. package/dist/compile.umd.cjs +1721 -483
  6. package/dist/compute-engine.esm.js +25209 -22883
  7. package/dist/compute-engine.min.esm.js +135 -87
  8. package/dist/compute-engine.min.umd.cjs +135 -87
  9. package/dist/compute-engine.umd.cjs +24952 -22626
  10. package/dist/core.esm.js +25208 -22882
  11. package/dist/core.min.esm.js +134 -86
  12. package/dist/core.min.umd.cjs +134 -86
  13. package/dist/core.umd.cjs +24951 -22625
  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 +653 -330
  19. package/dist/interval.min.esm.js +8 -8
  20. package/dist/interval.min.umd.cjs +8 -8
  21. package/dist/interval.umd.cjs +653 -330
  22. package/dist/latex-syntax.esm.js +758 -512
  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 +758 -512
  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 +1349 -228
  31. package/dist/numerics.min.esm.js +16 -5
  32. package/dist/numerics.min.umd.cjs +16 -5
  33. package/dist/numerics.umd.cjs +1349 -228
  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 +1 -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 +1 -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 +14 -4
  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 +1 -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 +15 -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 +1 -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 +48 -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 +1 -1
  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 +19 -3
  254. package/dist/types/compute-engine/types-evaluation.d.ts +1 -1
  255. package/dist/types/compute-engine/types-expression.d.ts +17 -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
- /** LatexSyntax 0.58.0 */
1
+ /** LatexSyntax 0.59.0 */
2
2
  (function(global,factory){typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'],factory):(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.LatexSyntax = {}));})(this, (function (exports) { 'use strict';
3
3
  var LatexSyntax = (() => {
4
4
  var __defProp = Object.defineProperty;
@@ -136,12 +136,14 @@ var LatexSyntax = (() => {
136
136
  if (expr === null) return null;
137
137
  if (isDictionaryObject(expr)) return expr;
138
138
  const kv = keyValuePair(expr);
139
- if (kv) return { [kv[0]]: kv[1] };
139
+ if (kv)
140
+ return {
141
+ dict: { [kv[0]]: expressionToDictionaryValue(kv[1]) ?? "Nothing" }
142
+ };
140
143
  if (operator(expr) === "Dictionary") {
141
144
  const dict = {};
142
- const ops = operands(expr);
143
- for (let i = 1; i < nops(expr); i++) {
144
- const kv2 = keyValuePair(ops[i]);
145
+ for (const op of operands(expr)) {
146
+ const kv2 = keyValuePair(op);
145
147
  if (kv2) {
146
148
  dict[kv2[0]] = expressionToDictionaryValue(kv2[1]) ?? "Nothing";
147
149
  }
@@ -480,11 +482,27 @@ var LatexSyntax = (() => {
480
482
  "\u208B": "-"
481
483
  // ₋
482
484
  };
485
+ var STICKY_REGEX_CACHE = /* @__PURE__ */ new Map();
486
+ function stickyRegex(regEx) {
487
+ let result = STICKY_REGEX_CACHE.get(regEx.source);
488
+ if (!result) {
489
+ const source = regEx.source.startsWith("^") ? regEx.source.slice(1) : regEx.source;
490
+ result = new RegExp(source, "y");
491
+ STICKY_REGEX_CACHE.set(regEx.source, result);
492
+ }
493
+ return result;
494
+ }
483
495
  var Tokenizer = class {
484
496
  s;
485
497
  pos;
498
+ /** The input as a plain string (joined graphemes), used by `match()` */
499
+ joined;
500
+ /** For grapheme-array inputs: code-unit offset of each grapheme in
501
+ * `joined` (length `s.length + 1`, last entry is `joined.length`) */
502
+ offsets = null;
486
503
  obeyspaces = false;
487
504
  constructor(s) {
505
+ s = s.normalize("NFC");
488
506
  s = s.replace(/[\u200E\u200F\u2066-\u2069\u202A-\u202E]/g, "");
489
507
  s = s.replace(/\u2212/g, "-");
490
508
  s = s.replace(/[⁰¹²³⁴⁵⁶⁷⁸⁹⁻ⁱⁿ]+/g, (m) => {
@@ -497,6 +515,19 @@ var LatexSyntax = (() => {
497
515
  });
498
516
  this.s = splitGraphemes(s);
499
517
  this.pos = 0;
518
+ if (typeof this.s === "string") {
519
+ this.joined = this.s;
520
+ } else {
521
+ this.joined = this.s.join("");
522
+ const offsets = new Array(this.s.length + 1);
523
+ let offset = 0;
524
+ for (let i = 0; i < this.s.length; i++) {
525
+ offsets[i] = offset;
526
+ offset += this.s[i].length;
527
+ }
528
+ offsets[this.s.length] = offset;
529
+ this.offsets = offsets;
530
+ }
500
531
  }
501
532
  /**
502
533
  * @return True if we reached the end of the stream
@@ -520,12 +551,13 @@ var LatexSyntax = (() => {
520
551
  * Return the next substring matching regEx and advance.
521
552
  */
522
553
  match(regEx) {
523
- let execResult;
554
+ const re = stickyRegex(regEx);
524
555
  if (typeof this.s === "string") {
525
- execResult = regEx.exec(this.s.slice(this.pos));
556
+ re.lastIndex = this.pos;
526
557
  } else {
527
- execResult = regEx.exec(this.s.slice(this.pos).join(""));
558
+ re.lastIndex = this.offsets[this.pos < this.s.length ? this.pos : this.s.length];
528
559
  }
560
+ const execResult = re.exec(this.joined);
529
561
  if (execResult?.[0]) {
530
562
  this.pos += execResult[0].length;
531
563
  return execResult[0];
@@ -632,25 +664,13 @@ var LatexSyntax = (() => {
632
664
  }
633
665
  }
634
666
  } else if (token === "\\csname") {
635
- while (lex.peek() === "<space>") {
636
- lex.next();
637
- }
638
667
  let command = "";
639
668
  let done = false;
640
669
  let tokens = [];
641
670
  do {
642
671
  if (tokens.length === 0) {
643
- if (/^#[0-9?]$/.test(lex.peek())) {
644
- const param = lex.get().slice(1);
645
- tokens = tokenize(
646
- args?.[param] ?? args?.["?"] ?? "\\placeholder{}",
647
- args
648
- );
649
- token = tokens[0];
650
- } else {
651
- token = lex.next();
652
- tokens = token ? [token] : [];
653
- }
672
+ token = lex.next();
673
+ tokens = token ? [token] : [];
654
674
  }
655
675
  done = tokens.length === 0;
656
676
  if (!done && token === "\\endcsname") {
@@ -723,7 +743,7 @@ var LatexSyntax = (() => {
723
743
  if (Array.isArray(tokens)) {
724
744
  for (const item of tokens) {
725
745
  if (Array.isArray(item)) {
726
- flat = [...flat, ...item];
746
+ for (const token of item) flat.push(token);
727
747
  } else {
728
748
  flat.push(item);
729
749
  }
@@ -1208,172 +1228,23 @@ var LatexSyntax = (() => {
1208
1228
  "error",
1209
1229
  ...EXPRESSION_TYPES
1210
1230
  ];
1231
+ var NUMERIC_TYPES_SET = new Set(
1232
+ NUMERIC_TYPES
1233
+ );
1234
+ var COLLECTION_TYPES_SET = new Set(
1235
+ COLLECTION_TYPES
1236
+ );
1237
+ var SCALAR_TYPES_SET = new Set(
1238
+ SCALAR_TYPES
1239
+ );
1240
+ var PRIMITIVE_TYPES_SET = new Set(
1241
+ PRIMITIVE_TYPES
1242
+ );
1211
1243
  function isValidType(t) {
1212
- if (typeof t === "string")
1213
- return PRIMITIVE_TYPES.includes(t);
1244
+ if (typeof t === "string") return PRIMITIVE_TYPES_SET.has(t);
1214
1245
  if (typeof t !== "object") return false;
1215
1246
  if (!("kind" in t)) return false;
1216
- 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";
1217
- }
1218
-
1219
- // src/common/type/serialize.ts
1220
- var NEGATION_PRECEDENCE = 3;
1221
- var UNION_PRECEDENCE = 1;
1222
- var INTERSECTION_PRECEDENCE = 2;
1223
- var LIST_PRECEDENCE = 4;
1224
- var RECORD_PRECEDENCE = 5;
1225
- var DICTIONARY_PRECEDENCE = 6;
1226
- var SET_PRECEDENCE = 7;
1227
- var COLLECTION_PRECEDENCE = 8;
1228
- var TUPLE_PRECEDENCE = 9;
1229
- var SIGNATURE_PRECEDENCE = 10;
1230
- var VALUE_PRECEDENCE = 11;
1231
- function typeToString(type, precedence = 0) {
1232
- if (typeof type === "string") return type;
1233
- let result = "";
1234
- switch (type.kind) {
1235
- case "value":
1236
- if (typeof type.value === "string") result = `"${type.value}"`;
1237
- else if (typeof type.value === "boolean")
1238
- result = type.value ? "true" : "false";
1239
- else result = type.value.toString();
1240
- break;
1241
- case "reference":
1242
- result = type.name;
1243
- break;
1244
- case "negation":
1245
- result = `!${typeToString(type.type, NEGATION_PRECEDENCE)}`;
1246
- break;
1247
- case "union":
1248
- result = type.types.map((t) => typeToString(t, UNION_PRECEDENCE)).join(" | ");
1249
- break;
1250
- case "intersection":
1251
- result = type.types.map((t) => typeToString(t, INTERSECTION_PRECEDENCE)).join(" & ");
1252
- break;
1253
- case "expression":
1254
- result = `expression<${symbolName(type.operator)}>`;
1255
- break;
1256
- case "symbol":
1257
- result = `symbol<${symbolName(type.name)}>`;
1258
- break;
1259
- case "numeric":
1260
- if (Number.isFinite(type.lower) && Number.isFinite(type.upper)) {
1261
- result = `${type.type}<${type.lower}..${type.upper}>`;
1262
- } else if (Number.isFinite(type.lower)) {
1263
- result = `${type.type}<${type.lower}..>`;
1264
- } else if (Number.isFinite(type.upper)) {
1265
- result = `${type.type}<..${type.upper}>`;
1266
- } else {
1267
- result = `${type.type}`;
1268
- }
1269
- break;
1270
- case "list":
1271
- if (type.dimensions && typeof type.elements === "string" && NUMERIC_TYPES.includes(type.elements)) {
1272
- if (type.dimensions === void 0) {
1273
- if (type.elements === "number") result = "tensor";
1274
- } else if (type.dimensions.length === 1) {
1275
- if (type.elements === "number") {
1276
- if (type.dimensions[0] < 0) result = "vector";
1277
- else result = `vector<${type.dimensions[0]}>`;
1278
- } else {
1279
- if (type.dimensions[0] < 0)
1280
- result = `vector<${typeToString(type.elements)}>`;
1281
- else
1282
- result = `vector<${typeToString(type.elements)}^${type.dimensions[0]}>`;
1283
- }
1284
- } else if (type.dimensions.length === 2) {
1285
- const dims = type.dimensions;
1286
- if (type.elements === "number") {
1287
- if (dims[0] < 0 && dims[1] < 0) result = "matrix";
1288
- else result = `matrix<${dims[0]}x${dims[1]}>`;
1289
- } else {
1290
- if (dims[0] < 0 && dims[1] < 0)
1291
- result = `matrix<${typeToString(type.elements)}>`;
1292
- else
1293
- result = `matrix<${typeToString(type.elements)}^(${dims[0]}x${dims[1]})>`;
1294
- }
1295
- }
1296
- }
1297
- if (!result) {
1298
- const dimensions = type.dimensions ? type.dimensions.length === 1 ? `^${type.dimensions[0].toString()}` : `^(${type.dimensions.join("x")})` : "";
1299
- result = `list<${typeToString(type.elements)}${dimensions}>`;
1300
- }
1301
- break;
1302
- case "record":
1303
- const elements = Object.entries(type.elements).map(([key, value]) => `${key}: ${typeToString(value)}`).join(", ");
1304
- result = `record<${elements}>`;
1305
- break;
1306
- case "dictionary":
1307
- result = `dictionary<${typeToString(type.values)}>`;
1308
- break;
1309
- case "set":
1310
- result = `set<${typeToString(type.elements)}>`;
1311
- break;
1312
- case "collection":
1313
- result = `collection<${typeToString(type.elements)}>`;
1314
- break;
1315
- case "indexed_collection":
1316
- result = `indexed_collection<${typeToString(type.elements)}>`;
1317
- break;
1318
- case "tuple":
1319
- if (type.elements.length === 0) result = "tuple";
1320
- else if (type.elements.length === 1) {
1321
- const [el] = type.elements;
1322
- result = `tuple<${namedElement(el)}>`;
1323
- } else {
1324
- result = "tuple<" + type.elements.map((el) => namedElement(el)).join(", ") + ">";
1325
- }
1326
- break;
1327
- case "signature":
1328
- const args = type.args ? type.args.map((arg) => namedElement(arg)).join(", ") : "";
1329
- const optArgs = type.optArgs ? type.optArgs.map((arg) => namedElement(arg) + "?").join(", ") : "";
1330
- const varArg = type.variadicArg ? type.variadicMin === 0 ? `${namedElement(type.variadicArg)}*` : `${namedElement(type.variadicArg)}+` : "";
1331
- const argsList = [args, optArgs, varArg].filter((s) => s).join(", ");
1332
- result = `(${argsList}) -> ${typeToString(type.result)}`;
1333
- break;
1334
- default:
1335
- result = "error";
1336
- }
1337
- if (precedence > 0 && precedence > getPrecedence(type.kind))
1338
- return `(${result})`;
1339
- return result;
1340
- }
1341
- function namedElement(el) {
1342
- if (el.name) return `${el.name}: ${typeToString(el.type)}`;
1343
- return typeToString(el.type);
1344
- }
1345
- function symbolName(name) {
1346
- if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) return name;
1347
- return `\`${name}\``;
1348
- }
1349
- function getPrecedence(kind) {
1350
- switch (kind) {
1351
- case "negation":
1352
- return NEGATION_PRECEDENCE;
1353
- case "union":
1354
- return UNION_PRECEDENCE;
1355
- case "intersection":
1356
- return INTERSECTION_PRECEDENCE;
1357
- case "list":
1358
- return LIST_PRECEDENCE;
1359
- case "record":
1360
- return RECORD_PRECEDENCE;
1361
- case "dictionary":
1362
- return DICTIONARY_PRECEDENCE;
1363
- case "set":
1364
- return SET_PRECEDENCE;
1365
- case "collection":
1366
- case "indexed_collection":
1367
- return COLLECTION_PRECEDENCE;
1368
- case "tuple":
1369
- return TUPLE_PRECEDENCE;
1370
- case "signature":
1371
- return SIGNATURE_PRECEDENCE;
1372
- case "value":
1373
- return VALUE_PRECEDENCE;
1374
- default:
1375
- return 0;
1376
- }
1247
+ 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";
1377
1248
  }
1378
1249
 
1379
1250
  // src/common/type/lexer.ts
@@ -2083,19 +1954,13 @@ var LatexSyntax = (() => {
2083
1954
  );
2084
1955
  let dimensions;
2085
1956
  if (this.match("<")) {
2086
- dimensions = this.parseDimensionWithX();
2087
- if (!dimensions) {
2088
- dimensions = this.parseDimensions();
2089
- }
1957
+ dimensions = this.parseDimensions();
2090
1958
  if (!dimensions) {
2091
1959
  const type = this.parseUnionType();
2092
1960
  if (type) {
2093
1961
  elementType = type;
2094
1962
  if (this.match("^")) {
2095
- dimensions = this.parseDimensionWithX();
2096
- if (!dimensions) {
2097
- dimensions = this.parseDimensions();
2098
- }
1963
+ dimensions = this.parseCaretDimensions();
2099
1964
  }
2100
1965
  }
2101
1966
  }
@@ -2136,19 +2001,13 @@ var LatexSyntax = (() => {
2136
2001
  );
2137
2002
  let dimensions;
2138
2003
  if (this.match("<")) {
2139
- dimensions = this.parseDimensionWithX();
2140
- if (!dimensions) {
2141
- dimensions = this.parseDimensions();
2142
- }
2004
+ dimensions = this.parseDimensions();
2143
2005
  if (!dimensions) {
2144
2006
  const type = this.parseUnionType();
2145
2007
  if (type) {
2146
2008
  elementType = type;
2147
2009
  if (this.match("^")) {
2148
- dimensions = this.parseDimensionWithX();
2149
- if (!dimensions) {
2150
- dimensions = this.parseDimensions();
2151
- }
2010
+ dimensions = this.parseCaretDimensions();
2152
2011
  }
2153
2012
  }
2154
2013
  }
@@ -2179,16 +2038,30 @@ var LatexSyntax = (() => {
2179
2038
  return this.createNode("tensor", { elementType });
2180
2039
  }
2181
2040
  parseDimensions() {
2182
- const dimensions = [];
2183
2041
  const firstDim = this.parseDimension();
2184
2042
  if (!firstDim) return void 0;
2185
- dimensions.push(firstDim);
2186
- while (this.match("x")) {
2187
- const dim = this.parseDimension();
2188
- if (!dim) {
2189
- this.error("Expected dimension after x");
2043
+ const dimensions = [firstDim];
2044
+ for (; ; ) {
2045
+ const tok = this.current;
2046
+ if (tok.type === "IDENTIFIER" && /^(x\d+)+$/.test(tok.value)) {
2047
+ this.advance();
2048
+ for (const m of tok.value.match(/x(\d+)/g))
2049
+ dimensions.push(
2050
+ this.createNode("dimension", {
2051
+ size: parseInt(m.slice(1))
2052
+ })
2053
+ );
2054
+ } else if (tok.type === "IDENTIFIER" && tok.value === "x") {
2055
+ const next = this.lexer.peekToken();
2056
+ if (next.type !== "NUMBER_LITERAL" && next.type !== "?")
2057
+ this.error(
2058
+ "Expected a positive integer literal or `?` after x. For example: `2x3` or `2x?`"
2059
+ );
2060
+ this.advance();
2061
+ dimensions.push(this.parseDimension());
2062
+ } else {
2063
+ break;
2190
2064
  }
2191
- dimensions.push(dim);
2192
2065
  }
2193
2066
  return dimensions;
2194
2067
  }
@@ -2202,35 +2075,11 @@ var LatexSyntax = (() => {
2202
2075
  }
2203
2076
  return void 0;
2204
2077
  }
2205
- parseDimensionWithX() {
2206
- if (this.current.type === "NUMBER_LITERAL") {
2207
- const dimensions = [];
2208
- const firstDim = parseInt(this.advance().value);
2209
- dimensions.push(
2210
- this.createNode("dimension", { size: firstDim })
2211
- );
2212
- if (this.current.type === "IDENTIFIER" && this.current.value.startsWith("x")) {
2213
- const dimString = this.current.value;
2214
- const matches = dimString.match(/x(\d+)/g);
2215
- if (matches && matches.join("") === dimString) {
2216
- this.advance();
2217
- for (const match of matches) {
2218
- const dimValue = parseInt(match.substring(1));
2219
- dimensions.push(
2220
- this.createNode("dimension", { size: dimValue })
2221
- );
2222
- }
2223
- } else if (dimString === "x" || dimString.startsWith("x")) {
2224
- this.error(
2225
- "Expected a positive integer literal or `?` after x. For example: `2x3` or `2x?`"
2226
- );
2227
- }
2228
- }
2229
- if (dimensions.length > 1) {
2230
- return dimensions;
2231
- }
2232
- }
2233
- return void 0;
2078
+ parseCaretDimensions() {
2079
+ const paren = this.match("(");
2080
+ const dimensions = this.parseDimensions();
2081
+ if (paren) this.expect(")");
2082
+ return dimensions;
2234
2083
  }
2235
2084
  parseTupleType() {
2236
2085
  if (this.current.type === "IDENTIFIER" && this.current.value === "tuple") {
@@ -2415,6 +2264,18 @@ var LatexSyntax = (() => {
2415
2264
  this.expect("..");
2416
2265
  const upperBound = this.parseValue();
2417
2266
  this.expect(">");
2267
+ const lower = lowerBound?.value ?? -Infinity;
2268
+ const upper = upperBound?.value ?? Infinity;
2269
+ if (Number.isNaN(lower) || Number.isNaN(upper))
2270
+ this.error(
2271
+ "Invalid numeric type",
2272
+ "Lower and upper bounds must be valid numbers"
2273
+ );
2274
+ if (lower > upper)
2275
+ this.error(
2276
+ `Invalid range: ${lower}..${upper}`,
2277
+ "The lower bound must be less than the upper bound"
2278
+ );
2418
2279
  return this.createNode("numeric", {
2419
2280
  baseType,
2420
2281
  lowerBound,
@@ -2429,7 +2290,7 @@ var LatexSyntax = (() => {
2429
2290
  parsePrimitiveType() {
2430
2291
  if (this.current.type === "IDENTIFIER") {
2431
2292
  const name = this.current.value;
2432
- if (PRIMITIVE_TYPES.includes(name)) {
2293
+ if (PRIMITIVE_TYPES_SET.has(name)) {
2433
2294
  this.advance();
2434
2295
  return this.createNode("primitive", { name });
2435
2296
  }
@@ -2763,14 +2624,32 @@ var LatexSyntax = (() => {
2763
2624
  }
2764
2625
 
2765
2626
  // src/common/type/parse.ts
2627
+ var TYPE_CACHE = /* @__PURE__ */ new Map();
2628
+ var TYPE_CACHE_MAX_SIZE = 2048;
2629
+ function deepFreeze(obj) {
2630
+ if (obj === null || typeof obj !== "object") return obj;
2631
+ if (Object.isFrozen(obj)) return obj;
2632
+ Object.freeze(obj);
2633
+ for (const value of Object.values(obj)) deepFreeze(value);
2634
+ return obj;
2635
+ }
2766
2636
  function parseType(s, typeResolver) {
2767
2637
  if (s === void 0) return void 0;
2768
2638
  if (isValidType(s)) return s;
2769
2639
  if (typeof s !== "string") return void 0;
2640
+ const cacheable = typeResolver === void 0;
2641
+ if (cacheable) {
2642
+ const cached = TYPE_CACHE.get(s);
2643
+ if (cached !== void 0) return cached;
2644
+ }
2770
2645
  try {
2771
2646
  const parser = new Parser(s, { typeResolver });
2772
2647
  const ast = parser.parseType();
2773
2648
  const type = buildTypeFromAST(ast, typeResolver);
2649
+ if (cacheable) {
2650
+ if (TYPE_CACHE.size >= TYPE_CACHE_MAX_SIZE) TYPE_CACHE.clear();
2651
+ TYPE_CACHE.set(s, deepFreeze(type));
2652
+ }
2774
2653
  return type;
2775
2654
  } catch (error) {
2776
2655
  throw new Error(
@@ -2845,19 +2724,36 @@ var LatexSyntax = (() => {
2845
2724
  color: [],
2846
2725
  expression: EXPRESSION_TYPES
2847
2726
  };
2727
+ var PRIMITIVE_SUBTYPES_CLOSURE = (() => {
2728
+ const closure = {};
2729
+ const closeOver = (t) => {
2730
+ if (closure[t]) return closure[t];
2731
+ const result = /* @__PURE__ */ new Set([t]);
2732
+ closure[t] = result;
2733
+ for (const sub of PRIMITIVE_SUBTYPES[t]) {
2734
+ if (sub === t) continue;
2735
+ for (const s of closeOver(sub)) result.add(s);
2736
+ }
2737
+ return result;
2738
+ };
2739
+ for (const t of Object.keys(PRIMITIVE_SUBTYPES))
2740
+ closeOver(t);
2741
+ return closure;
2742
+ })();
2848
2743
  function isPrimitiveSubtype(lhs, rhs) {
2849
2744
  if (rhs === "any") return true;
2850
2745
  if (lhs === "never") return true;
2851
2746
  if (lhs === "unknown" || rhs === "unknown") return false;
2852
2747
  if (lhs === rhs) return true;
2853
- return PRIMITIVE_SUBTYPES[rhs].includes(lhs);
2748
+ return PRIMITIVE_SUBTYPES_CLOSURE[rhs].has(lhs);
2854
2749
  }
2855
2750
  function isSubtype(lhs, rhs) {
2856
- if (typeof lhs === "string" && !PRIMITIVE_TYPES.includes(lhs))
2751
+ if (typeof lhs === "string" && !PRIMITIVE_TYPES_SET.has(lhs))
2857
2752
  lhs = parseType(lhs);
2858
- if (typeof rhs === "string" && !PRIMITIVE_TYPES.includes(rhs))
2753
+ if (typeof rhs === "string" && !PRIMITIVE_TYPES_SET.has(rhs))
2859
2754
  rhs = parseType(rhs);
2860
2755
  if (rhs === "any") return true;
2756
+ if (lhs === "never") return true;
2861
2757
  if (rhs === "never") return false;
2862
2758
  if (rhs === "error") return lhs === "error";
2863
2759
  if (rhs === "nothing") return lhs === "nothing";
@@ -2872,7 +2768,7 @@ var LatexSyntax = (() => {
2872
2768
  if (typeof lhs.value === "number") {
2873
2769
  if (Number.isInteger(lhs.value))
2874
2770
  return isPrimitiveSubtype("integer", rhs);
2875
- return isPrimitiveSubtype("number", rhs);
2771
+ return isPrimitiveSubtype("real", rhs);
2876
2772
  }
2877
2773
  if (typeof lhs.value === "boolean")
2878
2774
  return isPrimitiveSubtype("boolean", rhs);
@@ -3102,7 +2998,7 @@ var LatexSyntax = (() => {
3102
2998
  }
3103
2999
  function isNumeric(type) {
3104
3000
  if (typeof type === "string")
3105
- return NUMERIC_TYPES.includes(type);
3001
+ return NUMERIC_TYPES_SET.has(type);
3106
3002
  if (type.kind === "value") return typeof type.value === "number";
3107
3003
  if (type.kind === "numeric") return true;
3108
3004
  return false;
@@ -3110,7 +3006,7 @@ var LatexSyntax = (() => {
3110
3006
  function isScalar(type) {
3111
3007
  if (isNumeric(type)) return true;
3112
3008
  if (typeof type === "string")
3113
- return SCALAR_TYPES.includes(type);
3009
+ return SCALAR_TYPES_SET.has(type);
3114
3010
  if (type.kind === "value")
3115
3011
  return ["string", "boolean", "number"].includes(typeof type.value);
3116
3012
  return false;
@@ -3118,7 +3014,7 @@ var LatexSyntax = (() => {
3118
3014
  function isCollection(type) {
3119
3015
  if (isIndexedCollection(type)) return true;
3120
3016
  if (typeof type === "string")
3121
- return COLLECTION_TYPES.includes(type);
3017
+ return COLLECTION_TYPES_SET.has(type);
3122
3018
  return ["collection", "set", "record", "dictionary"].includes(type.kind);
3123
3019
  }
3124
3020
  function isIndexedCollection(type) {
@@ -3157,7 +3053,7 @@ var LatexSyntax = (() => {
3157
3053
  if (b === "unknown") return a;
3158
3054
  if (isSubtype(a, b)) return a;
3159
3055
  if (isSubtype(b, a)) return b;
3160
- return superType(a, b);
3056
+ return "never";
3161
3057
  }
3162
3058
  function widen2(a, b) {
3163
3059
  if (a === b) return a;
@@ -3191,16 +3087,17 @@ var LatexSyntax = (() => {
3191
3087
  ]);
3192
3088
  function unionTypes(a, b) {
3193
3089
  const members = [];
3090
+ const keys = /* @__PURE__ */ new Set();
3194
3091
  const push = (t) => {
3195
3092
  if (typeof t === "object" && t.kind === "union") {
3196
3093
  for (const m of t.types) push(m);
3197
3094
  return;
3198
3095
  }
3199
3096
  const key = typeof t === "string" ? t : JSON.stringify(t);
3200
- if (!members.some(
3201
- (m) => (typeof m === "string" ? m : JSON.stringify(m)) === key
3202
- ))
3097
+ if (!keys.has(key)) {
3098
+ keys.add(key);
3203
3099
  members.push(t);
3100
+ }
3204
3101
  };
3205
3102
  push(a);
3206
3103
  push(b);
@@ -3217,6 +3114,32 @@ var LatexSyntax = (() => {
3217
3114
  if (types.length === 1) return types[0];
3218
3115
  return types.reduce((a, b) => widen2(a, b));
3219
3116
  }
3117
+ var SUPERTYPE_PROBE_ORDER = [
3118
+ "non_finite_number",
3119
+ "finite_integer",
3120
+ "integer",
3121
+ "finite_rational",
3122
+ "rational",
3123
+ "finite_real",
3124
+ "real",
3125
+ "imaginary",
3126
+ "finite_complex",
3127
+ "complex",
3128
+ "finite_number",
3129
+ "number",
3130
+ "list",
3131
+ "record",
3132
+ "dictionary",
3133
+ "set",
3134
+ "tuple",
3135
+ "indexed_collection",
3136
+ "collection",
3137
+ "scalar",
3138
+ "value",
3139
+ "function",
3140
+ "expression"
3141
+ ];
3142
+ var PRIMITIVE_SUPERTYPE_CACHE = /* @__PURE__ */ new Map();
3220
3143
  function superType(a, b) {
3221
3144
  if (a === b) return a;
3222
3145
  if (a === "any" || b === "any") return "any";
@@ -3226,34 +3149,185 @@ var LatexSyntax = (() => {
3226
3149
  if (b === "unknown") return a;
3227
3150
  if (a === "nothing") return b;
3228
3151
  if (b === "nothing") return a;
3229
- if (commonSupertype(a, b, "non_finite_number")) return "non_finite_number";
3230
- if (commonSupertype(a, b, "finite_integer")) return "finite_integer";
3231
- if (commonSupertype(a, b, "integer")) return "integer";
3232
- if (commonSupertype(a, b, "finite_rational")) return "finite_rational";
3233
- if (commonSupertype(a, b, "rational")) return "rational";
3234
- if (commonSupertype(a, b, "finite_real")) return "finite_real";
3235
- if (commonSupertype(a, b, "real")) return "real";
3236
- if (commonSupertype(a, b, "imaginary")) return "imaginary";
3237
- if (commonSupertype(a, b, "finite_complex")) return "finite_complex";
3238
- if (commonSupertype(a, b, "complex")) return "complex";
3239
- if (commonSupertype(a, b, "finite_number")) return "finite_number";
3240
- if (commonSupertype(a, b, "number")) return "number";
3241
- if (commonSupertype(a, b, "list")) return "list";
3242
- if (commonSupertype(a, b, "record")) return "record";
3243
- if (commonSupertype(a, b, "dictionary")) return "dictionary";
3244
- if (commonSupertype(a, b, "set")) return "set";
3245
- if (commonSupertype(a, b, "tuple")) return "tuple";
3246
- if (commonSupertype(a, b, "indexed_collection")) return "indexed_collection";
3247
- if (commonSupertype(a, b, "collection")) return "collection";
3248
- if (commonSupertype(a, b, "scalar")) return "scalar";
3249
- if (commonSupertype(a, b, "value")) return "value";
3250
- if (commonSupertype(a, b, "function")) return "function";
3251
- if (commonSupertype(a, b, "expression")) return "expression";
3152
+ if (typeof a === "string" && typeof b === "string") {
3153
+ const key = a < b ? `${a}|${b}` : `${b}|${a}`;
3154
+ let result = PRIMITIVE_SUPERTYPE_CACHE.get(key);
3155
+ if (result === void 0) {
3156
+ result = "any";
3157
+ for (const ancestor of SUPERTYPE_PROBE_ORDER) {
3158
+ const subtypes = PRIMITIVE_SUBTYPES_CLOSURE[ancestor];
3159
+ if (subtypes.has(a) && subtypes.has(b)) {
3160
+ result = ancestor;
3161
+ break;
3162
+ }
3163
+ }
3164
+ PRIMITIVE_SUPERTYPE_CACHE.set(key, result);
3165
+ }
3166
+ return result;
3167
+ }
3168
+ for (const ancestor of SUPERTYPE_PROBE_ORDER)
3169
+ if (isSubtype(a, ancestor) && isSubtype(b, ancestor)) return ancestor;
3252
3170
  return "any";
3253
3171
  }
3254
- function commonSupertype(a, b, ancestor) {
3255
- if (isSubtype(a, ancestor) && isSubtype(b, ancestor)) return true;
3256
- return false;
3172
+
3173
+ // src/common/type/serialize.ts
3174
+ var NEGATION_PRECEDENCE = 3;
3175
+ var UNION_PRECEDENCE = 1;
3176
+ var INTERSECTION_PRECEDENCE = 2;
3177
+ var LIST_PRECEDENCE = 4;
3178
+ var RECORD_PRECEDENCE = 5;
3179
+ var DICTIONARY_PRECEDENCE = 6;
3180
+ var SET_PRECEDENCE = 7;
3181
+ var COLLECTION_PRECEDENCE = 8;
3182
+ var TUPLE_PRECEDENCE = 9;
3183
+ var SIGNATURE_PRECEDENCE = 10;
3184
+ var VALUE_PRECEDENCE = 11;
3185
+ function typeToString(type, precedence = 0) {
3186
+ if (typeof type === "string") return type;
3187
+ let result = "";
3188
+ switch (type.kind) {
3189
+ case "value":
3190
+ if (typeof type.value === "string") result = `"${type.value}"`;
3191
+ else if (typeof type.value === "boolean")
3192
+ result = type.value ? "true" : "false";
3193
+ else result = type.value.toString();
3194
+ break;
3195
+ case "reference":
3196
+ result = type.name;
3197
+ break;
3198
+ case "negation":
3199
+ result = `!${typeToString(type.type, NEGATION_PRECEDENCE)}`;
3200
+ break;
3201
+ case "union":
3202
+ result = type.types.map((t) => typeToString(t, UNION_PRECEDENCE)).join(" | ");
3203
+ break;
3204
+ case "intersection":
3205
+ result = type.types.map((t) => typeToString(t, INTERSECTION_PRECEDENCE)).join(" & ");
3206
+ break;
3207
+ case "expression":
3208
+ result = `expression<${symbolName(type.operator)}>`;
3209
+ break;
3210
+ case "symbol":
3211
+ result = `symbol<${symbolName(type.name)}>`;
3212
+ break;
3213
+ case "numeric":
3214
+ if (Number.isFinite(type.lower) && Number.isFinite(type.upper)) {
3215
+ result = `${type.type}<${type.lower}..${type.upper}>`;
3216
+ } else if (Number.isFinite(type.lower)) {
3217
+ result = `${type.type}<${type.lower}..>`;
3218
+ } else if (Number.isFinite(type.upper)) {
3219
+ result = `${type.type}<..${type.upper}>`;
3220
+ } else {
3221
+ result = `${type.type}`;
3222
+ }
3223
+ break;
3224
+ case "list":
3225
+ if (type.dimensions && typeof type.elements === "string" && NUMERIC_TYPES_SET.has(type.elements)) {
3226
+ if (type.dimensions === void 0) {
3227
+ if (type.elements === "number") result = "tensor";
3228
+ } else if (type.dimensions.length === 1) {
3229
+ if (type.elements === "number") {
3230
+ if (type.dimensions[0] < 0) result = "vector";
3231
+ else result = `vector<${type.dimensions[0]}>`;
3232
+ } else {
3233
+ if (type.dimensions[0] < 0)
3234
+ result = `vector<${typeToString(type.elements)}>`;
3235
+ else
3236
+ result = `vector<${typeToString(type.elements)}^${type.dimensions[0]}>`;
3237
+ }
3238
+ } else if (type.dimensions.length === 2) {
3239
+ const dims = type.dimensions;
3240
+ if (type.elements === "number") {
3241
+ if (dims[0] < 0 && dims[1] < 0) result = "matrix";
3242
+ else result = `matrix<${dims[0]}x${dims[1]}>`;
3243
+ } else {
3244
+ if (dims[0] < 0 && dims[1] < 0)
3245
+ result = `matrix<${typeToString(type.elements)}>`;
3246
+ else
3247
+ result = `matrix<${typeToString(type.elements)}^(${dims[0]}x${dims[1]})>`;
3248
+ }
3249
+ }
3250
+ }
3251
+ if (!result) {
3252
+ const dimensions = type.dimensions ? type.dimensions.length === 1 ? `^${type.dimensions[0].toString()}` : `^(${type.dimensions.join("x")})` : "";
3253
+ result = `list<${typeToString(type.elements)}${dimensions}>`;
3254
+ }
3255
+ break;
3256
+ case "record":
3257
+ const elements = Object.entries(type.elements).map(([key, value]) => `${key}: ${typeToString(value)}`).join(", ");
3258
+ result = `record<${elements}>`;
3259
+ break;
3260
+ case "dictionary":
3261
+ result = `dictionary<${typeToString(type.values)}>`;
3262
+ break;
3263
+ case "set":
3264
+ result = `set<${typeToString(type.elements)}>`;
3265
+ break;
3266
+ case "collection":
3267
+ result = `collection<${typeToString(type.elements)}>`;
3268
+ break;
3269
+ case "indexed_collection":
3270
+ result = `indexed_collection<${typeToString(type.elements)}>`;
3271
+ break;
3272
+ case "tuple":
3273
+ if (type.elements.length === 0) result = "tuple";
3274
+ else if (type.elements.length === 1) {
3275
+ const [el] = type.elements;
3276
+ result = `tuple<${namedElement(el)}>`;
3277
+ } else {
3278
+ result = "tuple<" + type.elements.map((el) => namedElement(el)).join(", ") + ">";
3279
+ }
3280
+ break;
3281
+ case "signature":
3282
+ const args = type.args ? type.args.map((arg) => namedElement(arg)).join(", ") : "";
3283
+ const optArgs = type.optArgs ? type.optArgs.map((arg) => namedElement(arg) + "?").join(", ") : "";
3284
+ const varArg = type.variadicArg ? type.variadicMin === 0 ? `${namedElement(type.variadicArg)}*` : `${namedElement(type.variadicArg)}+` : "";
3285
+ const argsList = [args, optArgs, varArg].filter((s) => s).join(", ");
3286
+ result = `(${argsList}) -> ${typeToString(type.result)}`;
3287
+ break;
3288
+ default:
3289
+ result = "error";
3290
+ }
3291
+ if (precedence > 0 && precedence > getPrecedence(type.kind))
3292
+ return `(${result})`;
3293
+ return result;
3294
+ }
3295
+ function namedElement(el) {
3296
+ if (el.name) return `${el.name}: ${typeToString(el.type)}`;
3297
+ return typeToString(el.type);
3298
+ }
3299
+ function symbolName(name) {
3300
+ if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) return name;
3301
+ return `\`${name}\``;
3302
+ }
3303
+ function getPrecedence(kind) {
3304
+ switch (kind) {
3305
+ case "negation":
3306
+ return NEGATION_PRECEDENCE;
3307
+ case "union":
3308
+ return UNION_PRECEDENCE;
3309
+ case "intersection":
3310
+ return INTERSECTION_PRECEDENCE;
3311
+ case "list":
3312
+ return LIST_PRECEDENCE;
3313
+ case "record":
3314
+ return RECORD_PRECEDENCE;
3315
+ case "dictionary":
3316
+ return DICTIONARY_PRECEDENCE;
3317
+ case "set":
3318
+ return SET_PRECEDENCE;
3319
+ case "collection":
3320
+ case "indexed_collection":
3321
+ return COLLECTION_PRECEDENCE;
3322
+ case "tuple":
3323
+ return TUPLE_PRECEDENCE;
3324
+ case "signature":
3325
+ return SIGNATURE_PRECEDENCE;
3326
+ case "value":
3327
+ return VALUE_PRECEDENCE;
3328
+ default:
3329
+ return 0;
3330
+ }
3257
3331
  }
3258
3332
 
3259
3333
  // src/common/type/boxed-type.ts
@@ -5089,6 +5163,7 @@ var LatexSyntax = (() => {
5089
5163
  }
5090
5164
  }
5091
5165
  if (!variable) return null;
5166
+ if (symbol(variable) === null) return null;
5092
5167
  parser.skipSpace();
5093
5168
  const fn = parser.parseExpression({ minPrec: 740 });
5094
5169
  if (!fn) return null;
@@ -5275,7 +5350,7 @@ var LatexSyntax = (() => {
5275
5350
  if (runs.length === 1) body = runs[0];
5276
5351
  else {
5277
5352
  if (runs.every((x) => stringValue(x) !== null))
5278
- body = "'" + runs.map((x) => stringValue(x)).join() + "'";
5353
+ body = "'" + runs.map((x) => stringValue(x)).join("") + "'";
5279
5354
  else body = ["Text", ...runs];
5280
5355
  }
5281
5356
  return style ? ["Annotated", body, dictionaryFromEntries(style)] : body;
@@ -6838,6 +6913,8 @@ var LatexSyntax = (() => {
6838
6913
  const h = operator(arg);
6839
6914
  if (prevWasNumber && (h === "Divide" || h === "Rational")) {
6840
6915
  result = latexTemplate(serializer.options.multiply, result, term);
6916
+ } else if (/^\d/.test(term)) {
6917
+ result = latexTemplate(serializer.options.multiply, result, term);
6841
6918
  } else if (!serializer.options.invisibleMultiply) {
6842
6919
  result = joinLatex([result, term]);
6843
6920
  } else {
@@ -8283,7 +8360,8 @@ var LatexSyntax = (() => {
8283
8360
  minPrec: MULTIPLICATION_PRECEDENCE,
8284
8361
  condition: (parser2) => trigCommands[parser2.peek] || (until?.condition?.(parser2) ?? false)
8285
8362
  });
8286
- const head = fn === "Arctan" && args?.length === 2 ? "Arctan2" : fn;
8363
+ const isTwoArgArctan = args?.length === 2 && (fn === "Arctan" || Array.isArray(fn) && fn[0] === "InverseFunction" && fn[1] === "Tan");
8364
+ const head = isTwoArgArctan ? "Arctan2" : fn;
8287
8365
  const appliedFn = args === null ? fn : typeof head === "string" ? [head, ...args] : ["Apply", head, ...args];
8288
8366
  return sup === null ? appliedFn : ["Power", appliedFn, sup];
8289
8367
  };
@@ -10790,10 +10868,41 @@ var LatexSyntax = (() => {
10790
10868
  postfixByTrigger: /* @__PURE__ */ new Map(),
10791
10869
  functionByTrigger: /* @__PURE__ */ new Map(),
10792
10870
  symbolByTrigger: /* @__PURE__ */ new Map(),
10793
- expressionByTrigger: /* @__PURE__ */ new Map()
10871
+ expressionByTrigger: /* @__PURE__ */ new Map(),
10872
+ operatorByTrigger: /* @__PURE__ */ new Map(),
10873
+ universalDefs: /* @__PURE__ */ new Map(),
10874
+ symbolTriggerDefs: /* @__PURE__ */ new Map()
10794
10875
  };
10795
10876
  for (const entry of dic)
10796
10877
  addEntry(result, entry, onError);
10878
+ for (let i = result.defs.length - 1; i >= 0; i--) {
10879
+ const def = result.defs[i];
10880
+ const isOperator = def.kind === "infix" || def.kind === "prefix" || def.kind === "postfix";
10881
+ const kinds = isOperator ? [def.kind, "operator"] : [def.kind];
10882
+ for (const kind of kinds) {
10883
+ if (def.latexTrigger === "") {
10884
+ const defs = result.universalDefs.get(kind);
10885
+ if (defs) defs.push(def);
10886
+ else result.universalDefs.set(kind, [def]);
10887
+ }
10888
+ if (def.symbolTrigger) {
10889
+ let byTrigger = result.symbolTriggerDefs.get(kind);
10890
+ if (!byTrigger) {
10891
+ byTrigger = /* @__PURE__ */ new Map();
10892
+ result.symbolTriggerDefs.set(kind, byTrigger);
10893
+ }
10894
+ const defs = byTrigger.get(def.symbolTrigger);
10895
+ if (defs) defs.push(def);
10896
+ else byTrigger.set(def.symbolTrigger, [def]);
10897
+ }
10898
+ if (kind === "operator" && def.latexTrigger && def.latexTrigger !== "") {
10899
+ const operatorDef = def;
10900
+ const defs = result.operatorByTrigger.get(def.latexTrigger);
10901
+ if (defs) defs.push(operatorDef);
10902
+ else result.operatorByTrigger.set(def.latexTrigger, [operatorDef]);
10903
+ }
10904
+ }
10905
+ }
10797
10906
  const COMPLEMENTARY_PAIRS = {
10798
10907
  "(": [")", "\\rparen"],
10799
10908
  "\\lparen": [")", "\\rparen"],
@@ -11158,7 +11267,7 @@ var LatexSyntax = (() => {
11158
11267
  }
11159
11268
  }
11160
11269
  if (isMatchfixEntry(entry)) {
11161
- if ("latexTrigger" in entry || "symbolTrigger" in isPrefixEntry) {
11270
+ if ("latexTrigger" in entry || "symbolTrigger" in entry) {
11162
11271
  onError({
11163
11272
  severity: "warning",
11164
11273
  message: [
@@ -11257,6 +11366,15 @@ var LatexSyntax = (() => {
11257
11366
  }
11258
11367
 
11259
11368
  // src/compute-engine/latex-syntax/parse-symbol.ts
11369
+ var _symbolNameByLatex = null;
11370
+ function getSymbolNameByLatex() {
11371
+ if (!_symbolNameByLatex) {
11372
+ _symbolNameByLatex = /* @__PURE__ */ new Map();
11373
+ for (const [name, latex] of SYMBOLS)
11374
+ if (!_symbolNameByLatex.has(latex)) _symbolNameByLatex.set(latex, name);
11375
+ }
11376
+ return _symbolNameByLatex;
11377
+ }
11260
11378
  var SYMBOL_PREFIX = {
11261
11379
  // Those are "grouping" prefix that also specify spacing
11262
11380
  // around the symbol. We ignore the spacing, though.
@@ -11335,10 +11453,10 @@ var LatexSyntax = (() => {
11335
11453
  parser.nextToken();
11336
11454
  return special;
11337
11455
  }
11338
- const i = SYMBOLS.findIndex((x) => x[1] === token);
11339
- if (i >= 0) {
11456
+ const symbolName2 = getSymbolNameByLatex().get(token);
11457
+ if (symbolName2 !== void 0) {
11340
11458
  parser.nextToken();
11341
- return SYMBOLS[i][0];
11459
+ return symbolName2;
11342
11460
  }
11343
11461
  const c = parser.parseChar();
11344
11462
  if (c !== null) {
@@ -11435,11 +11553,12 @@ var LatexSyntax = (() => {
11435
11553
  body = digit;
11436
11554
  parser.nextToken();
11437
11555
  }
11438
- body += parseSymbolBody(parser);
11439
- if (body === null || !parser.match("<}>")) {
11556
+ const rest = parseSymbolBody(parser);
11557
+ if (rest === null || !parser.match("<}>")) {
11440
11558
  parser.index = start;
11441
11559
  return null;
11442
11560
  }
11561
+ body += rest;
11443
11562
  if (prefix === "_upright" && body.length > 1) return body;
11444
11563
  return body + prefix;
11445
11564
  }
@@ -11650,6 +11769,7 @@ var LatexSyntax = (() => {
11650
11769
  return sum;
11651
11770
  }
11652
11771
  function fpln(x, scale) {
11772
+ if (x <= 0n) throw new RangeError("fpln: input must be positive");
11653
11773
  if (x === scale) return 0n;
11654
11774
  const xNum = Number(x);
11655
11775
  const scaleNum = Number(scale);
@@ -12299,9 +12419,11 @@ var LatexSyntax = (() => {
12299
12419
  if (Number.isFinite(thisExp) && Number.isFinite(otherExp)) {
12300
12420
  if (other.significand === 0n) return _BigDecimal.NAN;
12301
12421
  if (this.significand === 0n) return fromRaw(0n, 0);
12302
- return this.sub(this.div(other).trunc().mul(other)).toPrecision(
12303
- _BigDecimal.precision
12304
- );
12422
+ const ediff = thisExp - otherExp;
12423
+ const num = ediff >= 0 ? this.significand * pow10(ediff) : this.significand;
12424
+ const den = ediff >= 0 ? other.significand : other.significand * pow10(-ediff);
12425
+ const q = num / den;
12426
+ return this.sub(fromRaw(q, 0).mul(other));
12305
12427
  }
12306
12428
  if (thisExp !== thisExp || otherExp !== otherExp) return _BigDecimal.NAN;
12307
12429
  if (!Number.isFinite(thisExp)) return _BigDecimal.NAN;
@@ -12346,7 +12468,10 @@ var LatexSyntax = (() => {
12346
12468
  return this.pow(n.neg()).inv();
12347
12469
  }
12348
12470
  const absSig = this.significand < 0n ? -this.significand : this.significand;
12349
- const thisLog10 = bigintDigits(absSig) + this.exponent;
12471
+ const sigDigits = bigintDigits(absSig);
12472
+ const dropped = sigDigits > 15 ? sigDigits - 15 : 0;
12473
+ const lead = dropped > 0 ? Number(absSig / 10n ** BigInt(dropped)) : Number(absSig);
12474
+ const thisLog10 = Math.log10(lead) + dropped + this.exponent;
12350
12475
  const resultLog10 = Number(expValue) * thisLog10;
12351
12476
  if (resultLog10 > 9e15) {
12352
12477
  return this.significand < 0n && expValue % 2n !== 0n ? _BigDecimal.NEGATIVE_INFINITY : _BigDecimal.POSITIVE_INFINITY;
@@ -12379,7 +12504,19 @@ var LatexSyntax = (() => {
12379
12504
  return _BigDecimal.POSITIVE_INFINITY;
12380
12505
  }
12381
12506
  if (this.significand < 0n) return _BigDecimal.NAN;
12382
- return n.mul(this.ln()).exp();
12507
+ const baseSig = this.significand;
12508
+ const decExpBase = this.exponent + bigintDigits(baseSig) - 1;
12509
+ const nSig = n.significand < 0n ? -n.significand : n.significand;
12510
+ const decExpN = n.exponent + bigintDigits(nSig) - 1;
12511
+ const argMag = decExpN + Math.log10(Math.abs(decExpBase) * 2.303 + 3) + 1;
12512
+ const extra = Math.min(20, Math.max(2, Math.ceil(argMag) + 2));
12513
+ const savedPrec = _BigDecimal.precision;
12514
+ _BigDecimal.precision = savedPrec + extra;
12515
+ try {
12516
+ return n.mul(this.ln()).exp().toPrecision(savedPrec);
12517
+ } finally {
12518
+ _BigDecimal.precision = savedPrec;
12519
+ }
12383
12520
  }
12384
12521
  // ---------- Conversion methods ----------
12385
12522
  /** Convert to a JavaScript number. May lose precision for large values. */
@@ -12620,6 +12757,20 @@ var LatexSyntax = (() => {
12620
12757
  const sig = negative ? -absFp : absFp;
12621
12758
  return fromRaw(sig, resultExp);
12622
12759
  }
12760
+ function decimalExponent(x) {
12761
+ const sig = x.significand < 0n ? -x.significand : x.significand;
12762
+ return x.exponent + bigintDigits(sig) - 1;
12763
+ }
12764
+ var MAX_SAFE_EXPONENT = BigInt(Number.MAX_SAFE_INTEGER);
12765
+ var _ln10Fp = null;
12766
+ var _ln10Scale = null;
12767
+ function ln10Fixed(scale) {
12768
+ if (_ln10Scale !== scale) {
12769
+ _ln10Fp = fpln(10n * scale, scale);
12770
+ _ln10Scale = scale;
12771
+ }
12772
+ return _ln10Fp;
12773
+ }
12623
12774
  BigDecimal.prototype.sqrt = function() {
12624
12775
  if (this.isNaN()) return BigDecimal.NAN;
12625
12776
  if (this.isZero()) return BigDecimal.ZERO;
@@ -12630,9 +12781,13 @@ var LatexSyntax = (() => {
12630
12781
  if (this.significand < 0n) return BigDecimal.NAN;
12631
12782
  const targetPrec = BigDecimal.precision;
12632
12783
  const workingPrec = targetPrec + 10;
12633
- const [fp, scale] = toFixedPoint(this, workingPrec);
12784
+ const e = decimalExponent(this);
12785
+ const k = Math.floor(e / 2);
12786
+ const m = fromRaw(this.significand, this.exponent - 2 * k);
12787
+ const [fp, scale] = toFixedPoint(m, workingPrec);
12634
12788
  const sqrtFp = fpsqrt(fp, scale);
12635
- return fromFixedPoint(sqrtFp, scale, targetPrec);
12789
+ const root = fromFixedPoint(sqrtFp, scale, targetPrec);
12790
+ return fromRaw(root.significand, root.exponent + k);
12636
12791
  };
12637
12792
  BigDecimal.prototype.cbrt = function() {
12638
12793
  if (this.isNaN()) return BigDecimal.NAN;
@@ -12646,10 +12801,13 @@ var LatexSyntax = (() => {
12646
12801
  }
12647
12802
  const targetPrec = BigDecimal.precision;
12648
12803
  const workingPrec = targetPrec + 10;
12649
- const [fp, scale] = toFixedPoint(this, workingPrec);
12804
+ const e = decimalExponent(this);
12805
+ const k = Math.floor(e / 3);
12806
+ const m = fromRaw(this.significand, this.exponent - 3 * k);
12807
+ const [fp, scale] = toFixedPoint(m, workingPrec);
12650
12808
  const C = fp * scale * scale;
12651
12809
  let x;
12652
- const numVal = this.toNumber();
12810
+ const numVal = m.toNumber();
12653
12811
  const scaleNum = Number(scale);
12654
12812
  if (Number.isFinite(numVal) && numVal > 0 && Number.isFinite(scaleNum)) {
12655
12813
  const approx = Math.cbrt(numVal);
@@ -12678,7 +12836,8 @@ var LatexSyntax = (() => {
12678
12836
  const diffNext = bigintAbs(next * next * next - C);
12679
12837
  if (diffNext < diffX) x = next;
12680
12838
  }
12681
- return fromFixedPoint(x, scale, targetPrec);
12839
+ const root = fromFixedPoint(x, scale, targetPrec);
12840
+ return fromRaw(root.significand, root.exponent + k);
12682
12841
  };
12683
12842
  BigDecimal.sqrt = function(x) {
12684
12843
  return x.sqrt();
@@ -12693,11 +12852,27 @@ var LatexSyntax = (() => {
12693
12852
  return BigDecimal.ZERO;
12694
12853
  }
12695
12854
  if (this.isZero()) return BigDecimal.ONE;
12855
+ if (decimalExponent(this) >= 17)
12856
+ return this.significand > 0n ? BigDecimal.POSITIVE_INFINITY : BigDecimal.ZERO;
12696
12857
  const targetPrec = BigDecimal.precision;
12697
- const workingPrec = targetPrec + 15;
12698
- const [fp, scale] = toFixedPoint(this, workingPrec);
12699
- const expFp = fpexp(fp, scale);
12700
- return fromFixedPoint(expFp, scale, targetPrec);
12858
+ const absSig = this.significand < 0n ? -this.significand : this.significand;
12859
+ const magnitude = Math.max(0, this.exponent + bigintDigits(absSig));
12860
+ const workingPrec = targetPrec + 20 + magnitude;
12861
+ const [xFp, scale] = toFixedPoint(this, workingPrec);
12862
+ const l10 = ln10Fixed(scale);
12863
+ let k = xFp / l10;
12864
+ let rFp = xFp - k * l10;
12865
+ if (rFp < 0n) {
12866
+ k -= 1n;
12867
+ rFp += l10;
12868
+ }
12869
+ if (k > MAX_SAFE_EXPONENT || k < -MAX_SAFE_EXPONENT)
12870
+ return k > 0n ? BigDecimal.POSITIVE_INFINITY : BigDecimal.ZERO;
12871
+ const expR = fromFixedPoint(fpexp(rFp, scale), scale, targetPrec);
12872
+ const newExp = expR.exponent + Number(k);
12873
+ if (!Number.isSafeInteger(newExp))
12874
+ return k > 0n ? BigDecimal.POSITIVE_INFINITY : BigDecimal.ZERO;
12875
+ return fromRaw(expR.significand, newExp);
12701
12876
  };
12702
12877
  BigDecimal.prototype.ln = function() {
12703
12878
  if (this.isNaN()) return BigDecimal.NAN;
@@ -12709,10 +12884,16 @@ var LatexSyntax = (() => {
12709
12884
  if (this.significand < 0n) return BigDecimal.NAN;
12710
12885
  if (this.eq(1)) return BigDecimal.ZERO;
12711
12886
  const targetPrec = BigDecimal.precision;
12712
- const workingPrec = targetPrec + 15;
12713
- const [fp, scale] = toFixedPoint(this, workingPrec);
12714
- const lnFp = fpln(fp, scale);
12715
- return fromFixedPoint(lnFp, scale, targetPrec);
12887
+ const sig = this.significand;
12888
+ const digits = bigintDigits(sig);
12889
+ const e = this.exponent + digits - 1;
12890
+ const m = fromRaw(sig, -(digits - 1));
12891
+ const eDigits = Math.abs(e).toString().length;
12892
+ const workingPrec = targetPrec + 20 + eDigits;
12893
+ const [mFp, scale] = toFixedPoint(m, workingPrec);
12894
+ const l10 = ln10Fixed(scale);
12895
+ const resultFp = fpln(mFp, scale) + BigInt(e) * l10;
12896
+ return fromFixedPoint(resultFp, scale, targetPrec);
12716
12897
  };
12717
12898
  BigDecimal.prototype.log = function(base) {
12718
12899
  const b = base instanceof BigDecimal ? base : new BigDecimal(base);
@@ -12732,7 +12913,10 @@ var LatexSyntax = (() => {
12732
12913
  if (!this.isFinite()) return BigDecimal.NAN;
12733
12914
  if (this.isZero()) return BigDecimal.ZERO;
12734
12915
  const targetPrec = BigDecimal.precision;
12735
- const workingPrec = targetPrec + 15;
12916
+ const e = decimalExponent(this);
12917
+ if (e < 0 && -2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
12918
+ const workingPrec = targetPrec + 15 + (e < 0 ? -e : 0);
12919
+ if (e > PI_DIGITS.length - workingPrec - 30) return BigDecimal.NAN;
12736
12920
  const [fp, scale] = toFixedPoint(this, workingPrec);
12737
12921
  const [sinFp] = fpsincos(fp, scale);
12738
12922
  return fromFixedPoint(sinFp, scale, targetPrec);
@@ -12743,6 +12927,8 @@ var LatexSyntax = (() => {
12743
12927
  if (this.isZero()) return BigDecimal.ONE;
12744
12928
  const targetPrec = BigDecimal.precision;
12745
12929
  const workingPrec = targetPrec + 15;
12930
+ const e = decimalExponent(this);
12931
+ if (e > PI_DIGITS.length - workingPrec - 30) return BigDecimal.NAN;
12746
12932
  const [fp, scale] = toFixedPoint(this, workingPrec);
12747
12933
  const [, cosFp] = fpsincos(fp, scale);
12748
12934
  return fromFixedPoint(cosFp, scale, targetPrec);
@@ -12752,7 +12938,10 @@ var LatexSyntax = (() => {
12752
12938
  if (!this.isFinite()) return BigDecimal.NAN;
12753
12939
  if (this.isZero()) return BigDecimal.ZERO;
12754
12940
  const targetPrec = BigDecimal.precision;
12755
- const workingPrec = targetPrec + 15;
12941
+ const e = decimalExponent(this);
12942
+ if (e < 0 && -2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
12943
+ const workingPrec = targetPrec + 15 + (e < 0 ? -e : 0);
12944
+ if (e > PI_DIGITS.length - workingPrec - 30) return BigDecimal.NAN;
12756
12945
  const [fp, scale] = toFixedPoint(this, workingPrec);
12757
12946
  const [sinFp, cosFp] = fpsincos(fp, scale);
12758
12947
  if (cosFp === 0n) {
@@ -12770,7 +12959,9 @@ var LatexSyntax = (() => {
12770
12959
  return piHalf.neg();
12771
12960
  }
12772
12961
  const targetPrec = BigDecimal.precision;
12773
- const workingPrec = targetPrec + 15;
12962
+ const e = decimalExponent(this);
12963
+ if (e < 0 && -2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
12964
+ const workingPrec = targetPrec + 15 + (e < 0 ? -e : 0);
12774
12965
  const [fp, scale] = toFixedPoint(this, workingPrec);
12775
12966
  const atanFp = fpatan(fp, scale);
12776
12967
  return fromFixedPoint(atanFp, scale, targetPrec);
@@ -12787,7 +12978,9 @@ var LatexSyntax = (() => {
12787
12978
  return this.significand > 0n ? piHalf : piHalf.neg();
12788
12979
  }
12789
12980
  const targetPrec = BigDecimal.precision;
12790
- const workingPrec = targetPrec + 20;
12981
+ const e = decimalExponent(this);
12982
+ if (e < 0 && -2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
12983
+ const workingPrec = targetPrec + 20 + (e < 0 ? -e : 0);
12791
12984
  const [xFp, scale] = toFixedPoint(this, workingPrec);
12792
12985
  const x2 = fpmul(xFp, xFp, scale);
12793
12986
  const oneMinusX2 = scale - x2;
@@ -12850,6 +13043,23 @@ var LatexSyntax = (() => {
12850
13043
  if (this.significand > 0n) return BigDecimal.POSITIVE_INFINITY;
12851
13044
  return BigDecimal.NEGATIVE_INFINITY;
12852
13045
  }
13046
+ const targetPrec = BigDecimal.precision;
13047
+ const e = decimalExponent(this);
13048
+ if (e < 0) {
13049
+ if (-2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
13050
+ const saved = BigDecimal.precision;
13051
+ BigDecimal.precision = targetPrec - e + 5;
13052
+ try {
13053
+ const expX2 = this.exp();
13054
+ return expX2.sub(expX2.inv()).div(BigDecimal.TWO).toPrecision(targetPrec);
13055
+ } finally {
13056
+ BigDecimal.precision = saved;
13057
+ }
13058
+ }
13059
+ if (Math.abs(this.toNumber()) > 1.16 * (targetPrec + 3)) {
13060
+ const h = this.abs().exp().div(BigDecimal.TWO);
13061
+ return this.significand > 0n ? h : h.neg();
13062
+ }
12853
13063
  const expX = this.exp();
12854
13064
  const expNegX = expX.inv();
12855
13065
  return expX.sub(expNegX).div(BigDecimal.TWO);
@@ -12860,6 +13070,9 @@ var LatexSyntax = (() => {
12860
13070
  if (!this.isFinite()) {
12861
13071
  return BigDecimal.POSITIVE_INFINITY;
12862
13072
  }
13073
+ const targetPrec = BigDecimal.precision;
13074
+ if (Math.abs(this.toNumber()) > 1.16 * (targetPrec + 3))
13075
+ return this.abs().exp().div(BigDecimal.TWO);
12863
13076
  const expX = this.exp();
12864
13077
  const expNegX = expX.inv();
12865
13078
  return expX.add(expNegX).div(BigDecimal.TWO);
@@ -12871,6 +13084,21 @@ var LatexSyntax = (() => {
12871
13084
  if (this.significand > 0n) return BigDecimal.ONE;
12872
13085
  return BigDecimal.NEGATIVE_ONE;
12873
13086
  }
13087
+ const targetPrec = BigDecimal.precision;
13088
+ const e = decimalExponent(this);
13089
+ if (e < 0) {
13090
+ if (-2 * e >= targetPrec + 4) return this.toPrecision(targetPrec);
13091
+ const saved = BigDecimal.precision;
13092
+ BigDecimal.precision = targetPrec - e + 5;
13093
+ try {
13094
+ const exp2x2 = this.mul(BigDecimal.TWO).exp();
13095
+ return exp2x2.sub(BigDecimal.ONE).div(exp2x2.add(BigDecimal.ONE)).toPrecision(targetPrec);
13096
+ } finally {
13097
+ BigDecimal.precision = saved;
13098
+ }
13099
+ }
13100
+ if (Math.abs(this.toNumber()) > 1.16 * (targetPrec + 3))
13101
+ return this.significand > 0n ? BigDecimal.ONE : BigDecimal.NEGATIVE_ONE;
12874
13102
  const exp2x = this.mul(BigDecimal.TWO).exp();
12875
13103
  return exp2x.sub(BigDecimal.ONE).div(exp2x.add(BigDecimal.ONE));
12876
13104
  };
@@ -13019,7 +13247,7 @@ var LatexSyntax = (() => {
13019
13247
  const peek = parser.peek;
13020
13248
  if (peek === "\\overline") return true;
13021
13249
  if (peek === "\\overset") return true;
13022
- if (peek === "\\wideparent" || peek === "\\overarc") return true;
13250
+ if (peek === "\\wideparen" || peek === "\\overarc") return true;
13023
13251
  if (peek === "(") return true;
13024
13252
  if (peek === "\\left") return true;
13025
13253
  return false;
@@ -13186,6 +13414,106 @@ var LatexSyntax = (() => {
13186
13414
  }
13187
13415
 
13188
13416
  // src/compute-engine/latex-syntax/parse.ts
13417
+ var PARSE_TOKEN_EXCLUDED = /* @__PURE__ */ new Set([
13418
+ ...'!"#$%&(),/;:?@[]\\`|~'.split(""),
13419
+ "\\left",
13420
+ "\\bigl",
13421
+ "\\mleft"
13422
+ ]);
13423
+ var VISUAL_SPACE_COMMANDS = /* @__PURE__ */ new Set([
13424
+ "\\!",
13425
+ "\\,",
13426
+ "\\:",
13427
+ "\\;",
13428
+ "\\enskip",
13429
+ "\\enspace",
13430
+ "\\space",
13431
+ "\\quad",
13432
+ "\\qquad"
13433
+ ]);
13434
+ var TEX_UNIT_TOKENS = [
13435
+ "pt",
13436
+ "em",
13437
+ "mu",
13438
+ "ex",
13439
+ "mm",
13440
+ "cm",
13441
+ "in",
13442
+ "bp",
13443
+ "sp",
13444
+ "dd",
13445
+ "cc",
13446
+ "pc",
13447
+ "nc",
13448
+ "nd"
13449
+ ].map((unit) => [...unit]);
13450
+ var BARE_FUNCTION_MAP = {
13451
+ // Trigonometric
13452
+ sin: "Sin",
13453
+ cos: "Cos",
13454
+ tan: "Tan",
13455
+ cot: "Cot",
13456
+ sec: "Sec",
13457
+ csc: "Csc",
13458
+ // Hyperbolic
13459
+ sinh: "Sinh",
13460
+ cosh: "Cosh",
13461
+ tanh: "Tanh",
13462
+ coth: "Coth",
13463
+ sech: "Sech",
13464
+ csch: "Csch",
13465
+ // Inverse trigonometric
13466
+ arcsin: "Arcsin",
13467
+ arccos: "Arccos",
13468
+ arctan: "Arctan",
13469
+ arccot: "Arccot",
13470
+ arcsec: "Arcsec",
13471
+ arccsc: "Arccsc",
13472
+ asin: "Arcsin",
13473
+ acos: "Arccos",
13474
+ atan: "Arctan",
13475
+ // Inverse hyperbolic
13476
+ arcsinh: "Arsinh",
13477
+ arccosh: "Arcosh",
13478
+ arctanh: "Artanh",
13479
+ arccoth: "Arcoth",
13480
+ arcsech: "Arsech",
13481
+ arccsch: "Arcsch",
13482
+ asinh: "Arsinh",
13483
+ acosh: "Arcosh",
13484
+ atanh: "Artanh",
13485
+ // Logarithms and exponentials
13486
+ log: "Log",
13487
+ ln: "Ln",
13488
+ exp: "Exp",
13489
+ lg: "Lg",
13490
+ lb: "Lb",
13491
+ // Other common functions
13492
+ sqrt: "Sqrt",
13493
+ abs: "Abs",
13494
+ sgn: "Sgn",
13495
+ sign: "Sgn",
13496
+ floor: "Floor",
13497
+ ceil: "Ceil",
13498
+ round: "Round",
13499
+ max: "Max",
13500
+ min: "Min",
13501
+ gcd: "Gcd",
13502
+ lcm: "Lcm",
13503
+ // Roots
13504
+ cbrt: "Root",
13505
+ // Special-cased in `tryParseBareFunction` to add index 3
13506
+ // Combinatorics
13507
+ binom: "Binomial",
13508
+ nCr: "Binomial"
13509
+ };
13510
+ var LOOKAHEAD_TOKEN_TO_STRING = {
13511
+ "<space>": " ",
13512
+ "<$$>": "$$",
13513
+ "<$>": "$",
13514
+ "<{>": "{",
13515
+ "<}>": "}"
13516
+ };
13189
13517
  var _symbolToUnicode = null;
13190
13518
  function getSymbolToUnicode() {
13191
13519
  if (!_symbolToUnicode) {
@@ -13287,7 +13615,7 @@ var LatexSyntax = (() => {
13287
13615
  }
13288
13616
  addSymbol(id, type) {
13289
13617
  if (typeof type === "string") type = new BoxedType(type);
13290
- if (id in this.symbolTable.ids && this.symbolTable.ids[id].is(type.type))
13618
+ if (id in this.symbolTable.ids && !this.symbolTable.ids[id].is(type.type))
13291
13619
  throw new Error(`Symbol ${id} already declared as a different type`);
13292
13620
  this.symbolTable.ids[id] = type;
13293
13621
  }
@@ -13341,6 +13669,10 @@ var LatexSyntax = (() => {
13341
13669
  // Those two properties are used to detect infinite loops while parsing
13342
13670
  _lastPeek = "";
13343
13671
  _peekCounter = 0;
13672
+ // Cache for `lookAhead()`: the token stream and the dictionary are
13673
+ // immutable, so the result only depends on the current index
13674
+ _lookAheadCache = null;
13675
+ _lookAheadIndex = -1;
13344
13676
  constructor(tokens, dictionary, options) {
13345
13677
  this._tokens = tokens;
13346
13678
  this.options = options;
@@ -13497,9 +13829,6 @@ var LatexSyntax = (() => {
13497
13829
  latex(start, end) {
13498
13830
  return tokensToString(this._tokens.slice(start, end));
13499
13831
  }
13500
- latexAhead(n) {
13501
- return this.latex(this.index, this.index + n);
13502
- }
13503
13832
  // latexBefore(): string {
13504
13833
  // return this.latex(0, this.index);
13505
13834
  // }
@@ -13521,77 +13850,72 @@ var LatexSyntax = (() => {
13521
13850
  *
13522
13851
  */
13523
13852
  lookAhead() {
13524
- let n = Math.min(
13853
+ if (this._lookAheadIndex === this.index && this._lookAheadCache !== null)
13854
+ return this._lookAheadCache;
13855
+ const n = Math.min(
13525
13856
  this._dictionary.lookahead,
13526
13857
  this._tokens.length - this.index
13527
13858
  );
13528
- if (n <= 0) return [];
13529
13859
  const result = [];
13530
- while (n > 0) result.push([n, this.latexAhead(n--)]);
13860
+ let s = "";
13861
+ let sep = "";
13862
+ for (let i = 0; i < n; i++) {
13863
+ const token = this._tokens[this.index + i];
13864
+ const segment = LOOKAHEAD_TOKEN_TO_STRING[token] ?? token;
13865
+ if (/[a-zA-Z]/.test(segment[0])) s += sep;
13866
+ sep = /\\[a-zA-Z]+\*?$/.test(segment) ? " " : "";
13867
+ s += segment;
13868
+ result[n - 1 - i] = [i + 1, s];
13869
+ }
13870
+ this._lookAheadCache = result;
13871
+ this._lookAheadIndex = this.index;
13531
13872
  return result;
13532
13873
  }
13533
13874
  peekDefinitions(kind) {
13534
13875
  if (this.atEnd) return [];
13535
13876
  const result = [];
13877
+ const dictionary = this._dictionary;
13536
13878
  let triggerIndex;
13537
13879
  switch (kind) {
13538
13880
  case "infix":
13539
- triggerIndex = this._dictionary.infixByTrigger;
13881
+ triggerIndex = dictionary.infixByTrigger;
13540
13882
  break;
13541
13883
  case "prefix":
13542
- triggerIndex = this._dictionary.prefixByTrigger;
13884
+ triggerIndex = dictionary.prefixByTrigger;
13543
13885
  break;
13544
13886
  case "postfix":
13545
- triggerIndex = this._dictionary.postfixByTrigger;
13887
+ triggerIndex = dictionary.postfixByTrigger;
13546
13888
  break;
13547
13889
  case "function":
13548
- triggerIndex = this._dictionary.functionByTrigger;
13890
+ triggerIndex = dictionary.functionByTrigger;
13549
13891
  break;
13550
13892
  case "symbol":
13551
- triggerIndex = this._dictionary.symbolByTrigger;
13893
+ triggerIndex = dictionary.symbolByTrigger;
13552
13894
  break;
13553
13895
  case "expression":
13554
- triggerIndex = this._dictionary.expressionByTrigger;
13896
+ triggerIndex = dictionary.expressionByTrigger;
13555
13897
  break;
13556
13898
  case "operator":
13557
- triggerIndex = void 0;
13899
+ triggerIndex = dictionary.operatorByTrigger;
13558
13900
  break;
13559
13901
  }
13560
- if (triggerIndex) {
13561
- const defsNeedingIteration = [];
13562
- for (const def of this.getDefs(kind)) {
13563
- if (def.latexTrigger === "" || def.symbolTrigger) {
13564
- defsNeedingIteration.push(def);
13565
- }
13566
- }
13567
- for (const def of defsNeedingIteration) {
13568
- if (def.latexTrigger === "") result.push([def, 0]);
13569
- }
13570
- for (const [n, tokens] of this.lookAhead()) {
13571
- const defs = triggerIndex.get(tokens);
13572
- if (defs) {
13573
- for (const def of defs) result.push([def, n]);
13574
- }
13575
- }
13576
- for (const def of defsNeedingIteration) {
13577
- if (def.symbolTrigger) {
13578
- const n = parseComplexId(this, def.symbolTrigger);
13579
- if (n > 0) result.push([def, n]);
13580
- }
13902
+ const universalDefs = dictionary.universalDefs.get(kind);
13903
+ if (universalDefs) for (const def of universalDefs) result.push([def, 0]);
13904
+ for (const [n, tokens] of this.lookAhead()) {
13905
+ const defs = triggerIndex.get(tokens);
13906
+ if (defs) {
13907
+ for (const def of defs) result.push([def, n]);
13581
13908
  }
13582
- } else {
13583
- const defs = [...this.getDefs(kind)];
13584
- for (const def of defs)
13585
- if (def.latexTrigger === "") result.push([def, 0]);
13586
- for (const [n, tokens] of this.lookAhead()) {
13587
- for (const def of defs)
13588
- if (def.latexTrigger === tokens) result.push([def, n]);
13589
- }
13590
- for (const def of defs) {
13591
- if (def.symbolTrigger) {
13592
- const n = parseComplexId(this, def.symbolTrigger);
13593
- if (n > 0) result.push([def, n]);
13594
- }
13909
+ }
13910
+ const symbolTriggerDefs = dictionary.symbolTriggerDefs.get(kind);
13911
+ if (symbolTriggerDefs) {
13912
+ const start = this.index;
13913
+ const candidate = parseSymbol(this)?.trim();
13914
+ const n = this.index - start;
13915
+ this.index = start;
13916
+ if (candidate && n > 0) {
13917
+ const defs = symbolTriggerDefs.get(candidate);
13918
+ if (defs) for (const def of defs) result.push([def, n]);
13595
13919
  }
13596
13920
  }
13597
13921
  return result;
@@ -13629,17 +13953,7 @@ var LatexSyntax = (() => {
13629
13953
  skipVisualSpace() {
13630
13954
  if (!this.options.skipSpace) return;
13631
13955
  this.skipSpace();
13632
- if ([
13633
- "\\!",
13634
- "\\,",
13635
- "\\:",
13636
- "\\;",
13637
- "\\enskip",
13638
- "\\enspace",
13639
- "\\space",
13640
- "\\quad",
13641
- "\\qquad"
13642
- ].includes(this.peek)) {
13956
+ if (VISUAL_SPACE_COMMANDS.has(this.peek)) {
13643
13957
  this.nextToken();
13644
13958
  this.skipVisualSpace();
13645
13959
  }
@@ -13652,23 +13966,8 @@ var LatexSyntax = (() => {
13652
13966
  this.skipSpace();
13653
13967
  if (!this.match("-")) this.match("+");
13654
13968
  while (/^[\d.]$/.test(this.peek)) this.nextToken();
13655
- for (const unit of [
13656
- "pt",
13657
- "em",
13658
- "mu",
13659
- "ex",
13660
- "mm",
13661
- "cm",
13662
- "in",
13663
- "bp",
13664
- "sp",
13665
- "dd",
13666
- "cc",
13667
- "pc",
13668
- "nc",
13669
- "nd"
13670
- ]) {
13671
- if (this.matchAll([...unit])) break;
13969
+ for (const unit of TEX_UNIT_TOKENS) {
13970
+ if (this.matchAll(unit)) break;
13672
13971
  }
13673
13972
  this.skipVisualSpace();
13674
13973
  }
@@ -13921,13 +14220,7 @@ var LatexSyntax = (() => {
13921
14220
  // tokens (e.g. `\sqrt\frac12` or `\sqrt\operatorname{speed}`).
13922
14221
  parseToken() {
13923
14222
  this.skipSpace();
13924
- const excluding = [
13925
- ...'!"#$%&(),/;:?@[]\\`|~'.split(""),
13926
- "\\left",
13927
- "\\bigl",
13928
- "\\mleft"
13929
- ];
13930
- if (excluding.includes(this.peek)) return null;
14223
+ if (PARSE_TOKEN_EXCLUDED.has(this.peek)) return null;
13931
14224
  if (/^[0-9]$/.test(this.peek)) return parseInt(this.nextToken(), 10);
13932
14225
  return this.parseGenericExpression() ?? this.parseSymbol();
13933
14226
  }
@@ -13994,7 +14287,7 @@ var LatexSyntax = (() => {
13994
14287
  const start = this.index;
13995
14288
  let result = "";
13996
14289
  let level = 0;
13997
- while (!this.atBoundary || level > 0) {
14290
+ while (!this.atEnd && (!this.atBoundary || level > 0)) {
13998
14291
  const token = this.nextToken();
13999
14292
  if (token === "<$>" || token === "<$$>") {
14000
14293
  this.index = start;
@@ -14381,66 +14674,6 @@ var LatexSyntax = (() => {
14381
14674
  this.index = start;
14382
14675
  return null;
14383
14676
  }
14384
- const BARE_FUNCTION_MAP = {
14385
- // Trigonometric
14386
- sin: "Sin",
14387
- cos: "Cos",
14388
- tan: "Tan",
14389
- cot: "Cot",
14390
- sec: "Sec",
14391
- csc: "Csc",
14392
- // Hyperbolic
14393
- sinh: "Sinh",
14394
- cosh: "Cosh",
14395
- tanh: "Tanh",
14396
- coth: "Coth",
14397
- sech: "Sech",
14398
- csch: "Csch",
14399
- // Inverse trigonometric
14400
- arcsin: "Arcsin",
14401
- arccos: "Arccos",
14402
- arctan: "Arctan",
14403
- arccot: "Arccot",
14404
- arcsec: "Arcsec",
14405
- arccsc: "Arccsc",
14406
- asin: "Arcsin",
14407
- acos: "Arccos",
14408
- atan: "Arctan",
14409
- // Inverse hyperbolic
14410
- arcsinh: "Arsinh",
14411
- arccosh: "Arcosh",
14412
- arctanh: "Artanh",
14413
- arccoth: "Arcoth",
14414
- arcsech: "Arsech",
14415
- arccsch: "Arcsch",
14416
- asinh: "Arsinh",
14417
- acosh: "Arcosh",
14418
- atanh: "Artanh",
14419
- // Logarithms and exponentials
14420
- log: "Log",
14421
- ln: "Ln",
14422
- exp: "Exp",
14423
- lg: "Lg",
14424
- lb: "Lb",
14425
- // Other common functions
14426
- sqrt: "Sqrt",
14427
- abs: "Abs",
14428
- sgn: "Sgn",
14429
- sign: "Sgn",
14430
- floor: "Floor",
14431
- ceil: "Ceil",
14432
- round: "Round",
14433
- max: "Max",
14434
- min: "Min",
14435
- gcd: "Gcd",
14436
- lcm: "Lcm",
14437
- // Roots
14438
- cbrt: "Root",
14439
- // Special-cased below to add index 3
14440
- // Combinatorics
14441
- binom: "Binomial",
14442
- nCr: "Binomial"
14443
- };
14444
14677
  const fnName = BARE_FUNCTION_MAP[name];
14445
14678
  if (!fnName) {
14446
14679
  this.index = start;
@@ -14621,9 +14854,7 @@ var LatexSyntax = (() => {
14621
14854
  }
14622
14855
  let result = lhs;
14623
14856
  if (subscripts.length > 0) {
14624
- const defs = [...this.getDefs("infix")].filter(
14625
- (x) => x.latexTrigger === "_"
14626
- );
14857
+ const defs = this._dictionary.infixByTrigger.get("_") ?? [];
14627
14858
  if (defs) {
14628
14859
  const arg = [
14629
14860
  "Subscript",
@@ -14639,9 +14870,7 @@ var LatexSyntax = (() => {
14639
14870
  }
14640
14871
  }
14641
14872
  if (superscripts.length > 0) {
14642
- const defs = [...this.getDefs("infix")].filter(
14643
- (x) => x.latexTrigger === "^"
14644
- );
14873
+ const defs = this._dictionary.infixByTrigger.get("^") ?? [];
14645
14874
  if (defs) {
14646
14875
  const nonEmptySuperscripts = superscripts.filter(
14647
14876
  (x) => !isEmptySequence(x)
@@ -14855,6 +15084,15 @@ var LatexSyntax = (() => {
14855
15084
  if (result === null) {
14856
15085
  result = this.options.parseUnexpectedToken?.(null, this) ?? null;
14857
15086
  if (result === null && this.peek.startsWith("\\")) {
15087
+ if (this.peek === "\\") {
15088
+ const saved = this.index;
15089
+ this.nextToken();
15090
+ this.skipVisualSpace();
15091
+ if (this.atEnd) {
15092
+ return this.decorate(null, start);
15093
+ }
15094
+ this.index = saved;
15095
+ }
14858
15096
  this.nextToken();
14859
15097
  result = this.error("unexpected-command", start);
14860
15098
  }
@@ -15001,14 +15239,6 @@ var LatexSyntax = (() => {
15001
15239
  }
15002
15240
  }
15003
15241
  };
15004
- function parseComplexId(parser, id) {
15005
- const start = parser.index;
15006
- const candidate = parseSymbol(parser)?.trim();
15007
- if (candidate === null) return 0;
15008
- const result = candidate !== id ? 0 : parser.index - start;
15009
- parser.index = start;
15010
- return result;
15011
- }
15012
15242
  function isDelimiterCommand(parser) {
15013
15243
  const command = parser.peek;
15014
15244
  if (Object.values(CLOSE_DELIMITER).includes(command) || CLOSE_DELIMITER[command]) {
@@ -15505,9 +15735,9 @@ var LatexSyntax = (() => {
15505
15735
  if ((openFence === "." || closeFence === ".") && style === "normal")
15506
15736
  style = "scaled";
15507
15737
  if (style === "scaled")
15508
- return `\\left${openFence}${s}\\right${closeFence}}`;
15738
+ return `\\left${openFence}${s}\\right${closeFence}`;
15509
15739
  if (style === "big")
15510
- return `${`\\Bigl${openFence}`}${s}${`\\Bigr${closeFence}`})`;
15740
+ return `\\Bigl${openFence}${s}\\Bigr${closeFence}`;
15511
15741
  return openFence + s + closeFence;
15512
15742
  }
15513
15743
  wrapArguments(expr) {
@@ -15584,6 +15814,55 @@ var LatexSyntax = (() => {
15584
15814
  return this.options.numericSetStyle(expr, level);
15585
15815
  }
15586
15816
  };
15817
+ var _latexBySymbolName = null;
15818
+ function getLatexBySymbolName() {
15819
+ if (!_latexBySymbolName) {
15820
+ _latexBySymbolName = /* @__PURE__ */ new Map();
15821
+ for (const [name, latex] of SYMBOLS)
15822
+ if (!_latexBySymbolName.has(name)) _latexBySymbolName.set(name, latex);
15823
+ }
15824
+ return _latexBySymbolName;
15825
+ }
15826
+ var _latexByCodepoint = null;
15827
+ function getLatexByCodepoint() {
15828
+ if (!_latexByCodepoint) {
15829
+ _latexByCodepoint = /* @__PURE__ */ new Map();
15830
+ for (const [, latex, codepoint] of SYMBOLS)
15831
+ if (!_latexByCodepoint.has(codepoint))
15832
+ _latexByCodepoint.set(codepoint, latex);
15833
+ }
15834
+ return _latexByCodepoint;
15835
+ }
15836
+ var SPELLED_OUT_DIGITS = /* @__PURE__ */ new Map([
15837
+ ["zero", "0"],
15838
+ ["one", "1"],
15839
+ ["two", "2"],
15840
+ ["three", "3"],
15841
+ ["four", "4"],
15842
+ ["five", "5"],
15843
+ ["six", "6"],
15844
+ ["seven", "7"],
15845
+ ["eight", "8"],
15846
+ ["nine", "9"],
15847
+ ["ten", "10"]
15848
+ ]);
15849
+ var EXTRA_SYMBOLS = /* @__PURE__ */ new Map([
15850
+ ["plus", "+"],
15851
+ ["minus", "-"],
15852
+ ["pm", "\\pm"],
15853
+ ["ast", "\\ast"],
15854
+ ["dag", "\\dag"],
15855
+ ["ddag", "\\ddag"],
15856
+ ["hash", "\\#"],
15857
+ ["bottom", "\\bot"],
15858
+ ["top", "\\top"],
15859
+ ["bullet", "\\bullet"],
15860
+ ["circle", "\\circ"],
15861
+ ["diamond", "\\diamond"],
15862
+ ["times", "\\times"],
15863
+ ["square", "\\square"],
15864
+ ["star", "\\star"]
15865
+ ]);
15587
15866
  function specialName(s) {
15588
15867
  const unicodeMatch = s.match(/^____([0-9A-Fa-f]{6})(.*)/s);
15589
15868
  if (unicodeMatch) {
@@ -15592,51 +15871,18 @@ var LatexSyntax = (() => {
15592
15871
  return [`\\unicode{"${paddedHex}}`, unicodeMatch[2]];
15593
15872
  }
15594
15873
  const prefix = s.match(/^([^_]+)/)?.[1] ?? "";
15595
- let i = SYMBOLS.findIndex((x) => prefix === x[0]);
15596
- if (i >= 0) return [SYMBOLS[i][1], s.substring(SYMBOLS[i][0].length)];
15597
- const DIGITS = {
15598
- zero: "0",
15599
- one: "1",
15600
- two: "2",
15601
- three: "3",
15602
- four: "4",
15603
- five: "5",
15604
- six: "6",
15605
- seven: "7",
15606
- eight: "8",
15607
- nine: "9",
15608
- ten: "10"
15609
- };
15610
- i = Object.keys(DIGITS).findIndex((x) => s.startsWith(x));
15611
- if (i >= 0) {
15612
- const key = Object.keys(DIGITS)[i];
15613
- return [DIGITS[key], s.substring(key.length)];
15614
- }
15874
+ const symbolLatex = getLatexBySymbolName().get(prefix);
15875
+ if (symbolLatex !== void 0)
15876
+ return [symbolLatex, s.substring(prefix.length)];
15877
+ const digit = SPELLED_OUT_DIGITS.get(prefix);
15878
+ if (digit !== void 0) return [digit, s.substring(prefix.length)];
15615
15879
  const code = s.codePointAt(0);
15616
- i = SYMBOLS.findIndex((x) => x[2] === code);
15617
- if (i >= 0) return [SYMBOLS[i][1], s.substring(1)];
15618
- const EXTRA_SYMBOLS = {
15619
- plus: "+",
15620
- minus: "-",
15621
- pm: "\\pm",
15622
- ast: "\\ast",
15623
- dag: "\\dag",
15624
- ddag: "\\ddag",
15625
- hash: "\\#",
15626
- bottom: "\\bot",
15627
- top: "\\top",
15628
- bullet: "\\bullet",
15629
- circle: "\\circ",
15630
- diamond: "\\diamond",
15631
- times: "\\times",
15632
- square: "\\square",
15633
- star: "\\star"
15634
- };
15635
- i = Object.keys(EXTRA_SYMBOLS).findIndex((x) => prefix === x);
15636
- if (i >= 0) {
15637
- const key = Object.keys(EXTRA_SYMBOLS)[i];
15638
- return [EXTRA_SYMBOLS[key], s.substring(key.length)];
15880
+ if (code !== void 0) {
15881
+ const latex = getLatexByCodepoint().get(code);
15882
+ if (latex !== void 0) return [latex, s.substring(1)];
15639
15883
  }
15884
+ const extra = EXTRA_SYMBOLS.get(prefix);
15885
+ if (extra !== void 0) return [extra, s.substring(prefix.length)];
15640
15886
  return [prefix, s.substring(prefix.length)];
15641
15887
  }
15642
15888
  function parseModifiers(s) {
@@ -15871,7 +16117,7 @@ var LatexSyntax = (() => {
15871
16117
  }
15872
16118
 
15873
16119
  // src/latex-syntax.ts
15874
- var version = "0.58.0";
16120
+ var version = "0.59.0";
15875
16121
  return __toCommonJS(latex_syntax_exports);
15876
16122
  })();
15877
16123
  Object.assign(exports, LatexSyntax); Object.defineProperty(exports, '__esModule', { value: true });}));