hinmil 0.0.0-stage → 0.2.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 (301) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2306 -2
  3. package/dist/cli.d.ts +15 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +338 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/commentParser.d.ts +384 -0
  8. package/dist/commentParser.d.ts.map +1 -0
  9. package/dist/commentParser.js +2487 -0
  10. package/dist/commentParser.js.map +1 -0
  11. package/dist/config.d.ts +203 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +375 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/debugLog.d.ts +13 -0
  16. package/dist/debugLog.d.ts.map +1 -0
  17. package/dist/debugLog.js +44 -0
  18. package/dist/debugLog.js.map +1 -0
  19. package/dist/estree.d.ts +100 -0
  20. package/dist/estree.d.ts.map +1 -0
  21. package/dist/estree.js +34 -0
  22. package/dist/estree.js.map +1 -0
  23. package/dist/hm/env.d.ts +134 -0
  24. package/dist/hm/env.d.ts.map +1 -0
  25. package/dist/hm/env.js +939 -0
  26. package/dist/hm/env.js.map +1 -0
  27. package/dist/hm/index.d.ts +7 -0
  28. package/dist/hm/index.d.ts.map +1 -0
  29. package/dist/hm/index.js +26 -0
  30. package/dist/hm/index.js.map +1 -0
  31. package/dist/hm/substitution.d.ts +57 -0
  32. package/dist/hm/substitution.d.ts.map +1 -0
  33. package/dist/hm/substitution.js +546 -0
  34. package/dist/hm/substitution.js.map +1 -0
  35. package/dist/hm/typeParser.d.ts +39 -0
  36. package/dist/hm/typeParser.d.ts.map +1 -0
  37. package/dist/hm/typeParser.js +1285 -0
  38. package/dist/hm/typeParser.js.map +1 -0
  39. package/dist/hm/typeUtils.d.ts +248 -0
  40. package/dist/hm/typeUtils.d.ts.map +1 -0
  41. package/dist/hm/typeUtils.js +905 -0
  42. package/dist/hm/typeUtils.js.map +1 -0
  43. package/dist/hm/types.d.ts +738 -0
  44. package/dist/hm/types.d.ts.map +1 -0
  45. package/dist/hm/types.js +1853 -0
  46. package/dist/hm/types.js.map +1 -0
  47. package/dist/hm/unify.d.ts +59 -0
  48. package/dist/hm/unify.d.ts.map +1 -0
  49. package/dist/hm/unify.js +1700 -0
  50. package/dist/hm/unify.js.map +1 -0
  51. package/dist/index.d.ts +20 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +196 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/infer/annotation-rigid.d.ts +76 -0
  56. package/dist/infer/annotation-rigid.d.ts.map +1 -0
  57. package/dist/infer/annotation-rigid.js +542 -0
  58. package/dist/infer/annotation-rigid.js.map +1 -0
  59. package/dist/infer/annotation-validation.d.ts +109 -0
  60. package/dist/infer/annotation-validation.d.ts.map +1 -0
  61. package/dist/infer/annotation-validation.js +1078 -0
  62. package/dist/infer/annotation-validation.js.map +1 -0
  63. package/dist/infer/annotations.d.ts +277 -0
  64. package/dist/infer/annotations.d.ts.map +1 -0
  65. package/dist/infer/annotations.js +1343 -0
  66. package/dist/infer/annotations.js.map +1 -0
  67. package/dist/infer/call-overloads.d.ts +24 -0
  68. package/dist/infer/call-overloads.d.ts.map +1 -0
  69. package/dist/infer/call-overloads.js +900 -0
  70. package/dist/infer/call-overloads.js.map +1 -0
  71. package/dist/infer/call-rows.d.ts +154 -0
  72. package/dist/infer/call-rows.d.ts.map +1 -0
  73. package/dist/infer/call-rows.js +2162 -0
  74. package/dist/infer/call-rows.js.map +1 -0
  75. package/dist/infer/calls.d.ts +20 -0
  76. package/dist/infer/calls.d.ts.map +1 -0
  77. package/dist/infer/calls.js +1468 -0
  78. package/dist/infer/calls.js.map +1 -0
  79. package/dist/infer/constraints.d.ts +99 -0
  80. package/dist/infer/constraints.d.ts.map +1 -0
  81. package/dist/infer/constraints.js +1208 -0
  82. package/dist/infer/constraints.js.map +1 -0
  83. package/dist/infer/expr-assignment.d.ts +20 -0
  84. package/dist/infer/expr-assignment.d.ts.map +1 -0
  85. package/dist/infer/expr-assignment.js +620 -0
  86. package/dist/infer/expr-assignment.js.map +1 -0
  87. package/dist/infer/expr-constraint-lookup.d.ts +44 -0
  88. package/dist/infer/expr-constraint-lookup.d.ts.map +1 -0
  89. package/dist/infer/expr-constraint-lookup.js +207 -0
  90. package/dist/infer/expr-constraint-lookup.js.map +1 -0
  91. package/dist/infer/expr-functions.d.ts +20 -0
  92. package/dist/infer/expr-functions.d.ts.map +1 -0
  93. package/dist/infer/expr-functions.js +1359 -0
  94. package/dist/infer/expr-functions.js.map +1 -0
  95. package/dist/infer/expr-jsx.d.ts +19 -0
  96. package/dist/infer/expr-jsx.d.ts.map +1 -0
  97. package/dist/infer/expr-jsx.js +310 -0
  98. package/dist/infer/expr-jsx.js.map +1 -0
  99. package/dist/infer/expr-member.d.ts +40 -0
  100. package/dist/infer/expr-member.d.ts.map +1 -0
  101. package/dist/infer/expr-member.js +1154 -0
  102. package/dist/infer/expr-member.js.map +1 -0
  103. package/dist/infer/expr-prototype.d.ts +11 -0
  104. package/dist/infer/expr-prototype.d.ts.map +1 -0
  105. package/dist/infer/expr-prototype.js +202 -0
  106. package/dist/infer/expr-prototype.js.map +1 -0
  107. package/dist/infer/expressions.d.ts +40 -0
  108. package/dist/infer/expressions.d.ts.map +1 -0
  109. package/dist/infer/expressions.js +1497 -0
  110. package/dist/infer/expressions.js.map +1 -0
  111. package/dist/infer/functionPatterns.d.ts +229 -0
  112. package/dist/infer/functionPatterns.d.ts.map +1 -0
  113. package/dist/infer/functionPatterns.js +1035 -0
  114. package/dist/infer/functionPatterns.js.map +1 -0
  115. package/dist/infer/helpers.d.ts +73 -0
  116. package/dist/infer/helpers.d.ts.map +1 -0
  117. package/dist/infer/helpers.js +187 -0
  118. package/dist/infer/helpers.js.map +1 -0
  119. package/dist/infer/index.d.ts +551 -0
  120. package/dist/infer/index.d.ts.map +1 -0
  121. package/dist/infer/index.js +1127 -0
  122. package/dist/infer/index.js.map +1 -0
  123. package/dist/infer/jsx-dom.d.ts +26 -0
  124. package/dist/infer/jsx-dom.d.ts.map +1 -0
  125. package/dist/infer/jsx-dom.js +303 -0
  126. package/dist/infer/jsx-dom.js.map +1 -0
  127. package/dist/infer/moduleReps.d.ts +7 -0
  128. package/dist/infer/moduleReps.d.ts.map +1 -0
  129. package/dist/infer/moduleReps.js +48 -0
  130. package/dist/infer/moduleReps.js.map +1 -0
  131. package/dist/infer/modules.d.ts +10 -0
  132. package/dist/infer/modules.d.ts.map +1 -0
  133. package/dist/infer/modules.js +775 -0
  134. package/dist/infer/modules.js.map +1 -0
  135. package/dist/infer/narrowing.d.ts +199 -0
  136. package/dist/infer/narrowing.d.ts.map +1 -0
  137. package/dist/infer/narrowing.js +1428 -0
  138. package/dist/infer/narrowing.js.map +1 -0
  139. package/dist/infer/results.d.ts +24 -0
  140. package/dist/infer/results.d.ts.map +1 -0
  141. package/dist/infer/results.js +611 -0
  142. package/dist/infer/results.js.map +1 -0
  143. package/dist/infer/setupPass.d.ts +11 -0
  144. package/dist/infer/setupPass.d.ts.map +1 -0
  145. package/dist/infer/setupPass.js +524 -0
  146. package/dist/infer/setupPass.js.map +1 -0
  147. package/dist/infer/statements.d.ts +26 -0
  148. package/dist/infer/statements.d.ts.map +1 -0
  149. package/dist/infer/statements.js +750 -0
  150. package/dist/infer/statements.js.map +1 -0
  151. package/dist/infer/stmt-bindings.d.ts +22 -0
  152. package/dist/infer/stmt-bindings.d.ts.map +1 -0
  153. package/dist/infer/stmt-bindings.js +1482 -0
  154. package/dist/infer/stmt-bindings.js.map +1 -0
  155. package/dist/infer/stmt-destructure.d.ts +29 -0
  156. package/dist/infer/stmt-destructure.d.ts.map +1 -0
  157. package/dist/infer/stmt-destructure.js +490 -0
  158. package/dist/infer/stmt-destructure.js.map +1 -0
  159. package/dist/infer/types.d.ts +220 -0
  160. package/dist/infer/types.d.ts.map +1 -0
  161. package/dist/infer/types.js +46 -0
  162. package/dist/infer/types.js.map +1 -0
  163. package/dist/infer/unifyDiag.d.ts +46 -0
  164. package/dist/infer/unifyDiag.d.ts.map +1 -0
  165. package/dist/infer/unifyDiag.js +642 -0
  166. package/dist/infer/unifyDiag.js.map +1 -0
  167. package/dist/parsing-babel.d.ts +3 -0
  168. package/dist/parsing-babel.d.ts.map +1 -0
  169. package/dist/parsing-babel.js +353 -0
  170. package/dist/parsing-babel.js.map +1 -0
  171. package/dist/parsing.d.ts +69 -0
  172. package/dist/parsing.d.ts.map +1 -0
  173. package/dist/parsing.js +288 -0
  174. package/dist/parsing.js.map +1 -0
  175. package/dist/registries/constraintRegistry.d.ts +233 -0
  176. package/dist/registries/constraintRegistry.d.ts.map +1 -0
  177. package/dist/registries/constraintRegistry.js +803 -0
  178. package/dist/registries/constraintRegistry.js.map +1 -0
  179. package/dist/registries/dataTypeRegistry.d.ts +63 -0
  180. package/dist/registries/dataTypeRegistry.d.ts.map +1 -0
  181. package/dist/registries/dataTypeRegistry.js +180 -0
  182. package/dist/registries/dataTypeRegistry.js.map +1 -0
  183. package/dist/registries/domGlobals.d.ts +33 -0
  184. package/dist/registries/domGlobals.d.ts.map +1 -0
  185. package/dist/registries/domGlobals.js +309 -0
  186. package/dist/registries/domGlobals.js.map +1 -0
  187. package/dist/registries/methodRegistry.d.ts +277 -0
  188. package/dist/registries/methodRegistry.d.ts.map +1 -0
  189. package/dist/registries/methodRegistry.js +2074 -0
  190. package/dist/registries/methodRegistry.js.map +1 -0
  191. package/dist/registries/session.d.ts +38 -0
  192. package/dist/registries/session.d.ts.map +1 -0
  193. package/dist/registries/session.js +75 -0
  194. package/dist/registries/session.js.map +1 -0
  195. package/dist/server.d.ts +2 -0
  196. package/dist/server.d.ts.map +1 -0
  197. package/dist/server.js +1896 -0
  198. package/dist/server.js.map +1 -0
  199. package/dist/services/codeActions.d.ts +22 -0
  200. package/dist/services/codeActions.d.ts.map +1 -0
  201. package/dist/services/codeActions.js +465 -0
  202. package/dist/services/codeActions.js.map +1 -0
  203. package/dist/services/completion.d.ts +259 -0
  204. package/dist/services/completion.d.ts.map +1 -0
  205. package/dist/services/completion.js +2794 -0
  206. package/dist/services/completion.js.map +1 -0
  207. package/dist/services/definitions.d.ts +37 -0
  208. package/dist/services/definitions.d.ts.map +1 -0
  209. package/dist/services/definitions.js +605 -0
  210. package/dist/services/definitions.js.map +1 -0
  211. package/dist/services/diagnosticCodes.d.ts +70 -0
  212. package/dist/services/diagnosticCodes.d.ts.map +1 -0
  213. package/dist/services/diagnosticCodes.js +239 -0
  214. package/dist/services/diagnosticCodes.js.map +1 -0
  215. package/dist/services/diagnostics.d.ts +86 -0
  216. package/dist/services/diagnostics.d.ts.map +1 -0
  217. package/dist/services/diagnostics.js +665 -0
  218. package/dist/services/diagnostics.js.map +1 -0
  219. package/dist/services/documentCache.d.ts +88 -0
  220. package/dist/services/documentCache.d.ts.map +1 -0
  221. package/dist/services/documentCache.js +108 -0
  222. package/dist/services/documentCache.js.map +1 -0
  223. package/dist/services/documentSymbols.d.ts +20 -0
  224. package/dist/services/documentSymbols.d.ts.map +1 -0
  225. package/dist/services/documentSymbols.js +381 -0
  226. package/dist/services/documentSymbols.js.map +1 -0
  227. package/dist/services/fileSelection.d.ts +24 -0
  228. package/dist/services/fileSelection.d.ts.map +1 -0
  229. package/dist/services/fileSelection.js +154 -0
  230. package/dist/services/fileSelection.js.map +1 -0
  231. package/dist/services/fileSelectionRefresh.d.ts +26 -0
  232. package/dist/services/fileSelectionRefresh.d.ts.map +1 -0
  233. package/dist/services/fileSelectionRefresh.js +77 -0
  234. package/dist/services/fileSelectionRefresh.js.map +1 -0
  235. package/dist/services/files.d.ts +342 -0
  236. package/dist/services/files.d.ts.map +1 -0
  237. package/dist/services/files.js +1712 -0
  238. package/dist/services/files.js.map +1 -0
  239. package/dist/services/fsProbe.d.ts +14 -0
  240. package/dist/services/fsProbe.d.ts.map +1 -0
  241. package/dist/services/fsProbe.js +112 -0
  242. package/dist/services/fsProbe.js.map +1 -0
  243. package/dist/services/globalsLoader.d.ts +20 -0
  244. package/dist/services/globalsLoader.d.ts.map +1 -0
  245. package/dist/services/globalsLoader.js +122 -0
  246. package/dist/services/globalsLoader.js.map +1 -0
  247. package/dist/services/hmFileServices.d.ts +113 -0
  248. package/dist/services/hmFileServices.d.ts.map +1 -0
  249. package/dist/services/hmFileServices.js +686 -0
  250. package/dist/services/hmFileServices.js.map +1 -0
  251. package/dist/services/hover.d.ts +280 -0
  252. package/dist/services/hover.d.ts.map +1 -0
  253. package/dist/services/hover.js +1687 -0
  254. package/dist/services/hover.js.map +1 -0
  255. package/dist/services/importContext.d.ts +396 -0
  256. package/dist/services/importContext.d.ts.map +1 -0
  257. package/dist/services/importContext.js +1999 -0
  258. package/dist/services/importContext.js.map +1 -0
  259. package/dist/services/projectChecker.d.ts +50 -0
  260. package/dist/services/projectChecker.d.ts.map +1 -0
  261. package/dist/services/projectChecker.js +228 -0
  262. package/dist/services/projectChecker.js.map +1 -0
  263. package/dist/services/references.d.ts +41 -0
  264. package/dist/services/references.d.ts.map +1 -0
  265. package/dist/services/references.js +757 -0
  266. package/dist/services/references.js.map +1 -0
  267. package/dist/services/rename.d.ts +22 -0
  268. package/dist/services/rename.d.ts.map +1 -0
  269. package/dist/services/rename.js +101 -0
  270. package/dist/services/rename.js.map +1 -0
  271. package/dist/services/shortCircuit.d.ts +27 -0
  272. package/dist/services/shortCircuit.d.ts.map +1 -0
  273. package/dist/services/shortCircuit.js +28 -0
  274. package/dist/services/shortCircuit.js.map +1 -0
  275. package/dist/services/sidecarPerf.d.ts +19 -0
  276. package/dist/services/sidecarPerf.d.ts.map +1 -0
  277. package/dist/services/sidecarPerf.js +59 -0
  278. package/dist/services/sidecarPerf.js.map +1 -0
  279. package/dist/services/signatureHelp.d.ts +27 -0
  280. package/dist/services/signatureHelp.d.ts.map +1 -0
  281. package/dist/services/signatureHelp.js +984 -0
  282. package/dist/services/signatureHelp.js.map +1 -0
  283. package/dist/walking.d.ts +25 -0
  284. package/dist/walking.d.ts.map +1 -0
  285. package/dist/walking.js +107 -0
  286. package/dist/walking.js.map +1 -0
  287. package/hm-types-builtin/assert.hm +20 -0
  288. package/hm-types-builtin/buffer.hm +8 -0
  289. package/hm-types-builtin/child_process.hm +16 -0
  290. package/hm-types-builtin/crypto.hm +17 -0
  291. package/hm-types-builtin/fs.hm +15 -0
  292. package/hm-types-builtin/http.hm +14 -0
  293. package/hm-types-builtin/os.hm +19 -0
  294. package/hm-types-builtin/path.hm +18 -0
  295. package/hm-types-builtin/react-dom.hm +27 -0
  296. package/hm-types-builtin/react.hm +113 -0
  297. package/hm-types-builtin/url.hm +7 -0
  298. package/hm-types-builtin/zlib.hm +12 -0
  299. package/package.json +53 -4
  300. package/schemas/hinmil.config.schema.json +261 -0
  301. package/schemas/package-hinmil.schema.json +59 -0
@@ -0,0 +1,803 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Constraint Registry — type class constraints for HM type annotations
4
+ //
5
+ // Plain language: a *constraint* is a membership requirement for types.
6
+ // "Functor f => …" reads: "this works for any container type f, PROVIDED f
7
+ // supports mapping". This file is the notebook of all declared constraints
8
+ // and their required methods, plus the logic that decides whether a concrete
9
+ // type earns the membership card ("does Array have a map method? then Array
10
+ // satisfies Functor").
11
+ //
12
+ // A constraint like `Functor` declares a set of method requirements.
13
+ // Any type that has those methods registered (via `#` annotations) satisfies
14
+ // the constraint structurally — no explicit `instance` declaration needed.
15
+ //
16
+ // Definition syntax (in JS comments):
17
+ // // ::constraint Functor f { map :: f a ~> (a -> b) -> f b }
18
+ // // ::constraint Monad m { chain :: m a ~> (a -> m b) -> m b, of :: a -> m a }
19
+ //
20
+ // Usage in type signatures:
21
+ // // map :: Functor f => (a -> b) -> f a -> f b
22
+ // ============================================================================
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.ConstraintRegistry = void 0;
25
+ exports.registerConstraint = registerConstraint;
26
+ exports.lookupConstraint = lookupConstraint;
27
+ exports.getConstraintNames = getConstraintNames;
28
+ exports.getEffectiveMethods = getEffectiveMethods;
29
+ exports.constraintSuperclassClosure = constraintSuperclassClosure;
30
+ exports.clearConstraints = clearConstraints;
31
+ exports.snapshotConstraintRegistry = snapshotConstraintRegistry;
32
+ exports.restoreConstraintRegistry = restoreConstraintRegistry;
33
+ exports.mergeConstraintRegistry = mergeConstraintRegistry;
34
+ exports.checkConstraint = checkConstraint;
35
+ exports.parseConstraintDirective = parseConstraintDirective;
36
+ exports.inferExpectedKind = inferExpectedKind;
37
+ exports.validateConstraintDef = validateConstraintDef;
38
+ exports.checkConstraintMethodShape = checkConstraintMethodShape;
39
+ exports.checkStaticConstraintMethodShape = checkStaticConstraintMethodShape;
40
+ exports.matchesConstraintShape = matchesConstraintShape;
41
+ const methodRegistry_1 = require("./methodRegistry");
42
+ const types_1 = require("../hm/types");
43
+ const typeParser_1 = require("../hm/typeParser");
44
+ // ---------------------------------------------------------------------------
45
+ // Registry class
46
+ // ---------------------------------------------------------------------------
47
+ /** Encapsulates constraint registry state and operations. */
48
+ class ConstraintRegistry {
49
+ constructor() {
50
+ this.registry = new Map();
51
+ }
52
+ /** Register a constraint definition. Computes expectedKind if not provided. */
53
+ register(def) {
54
+ if (def.expectedKind === undefined) {
55
+ def.expectedKind = inferExpectedKind(def.typeVar, def.methods);
56
+ }
57
+ this.registry.set(def.name, def);
58
+ }
59
+ /** Look up a constraint definition by name. */
60
+ lookup(name) {
61
+ const def = this.registry.get(name) ?? null;
62
+ if (def)
63
+ this.resolveInheritedKind(def);
64
+ return def;
65
+ }
66
+ /**
67
+ * Extends-only constraints (e.g. `::constraint Alternative f
68
+ * { f :: Applicative, f :: Plus }`) have no method signatures of their own,
69
+ * so parse-time kind inference defaults them to `*`. Their true kind is the
70
+ * kind of their parents. Resolved lazily (parents may be registered after
71
+ * the child) and memoized by upgrading `def.expectedKind` in place.
72
+ */
73
+ resolveInheritedKind(def) {
74
+ if (def.expectedKind !== '*' ||
75
+ def.methods.length > 0 ||
76
+ (def.selfClauses && def.selfClauses.length > 0) ||
77
+ !def.extends ||
78
+ def.extends.length === 0) {
79
+ return;
80
+ }
81
+ // Walk all ancestors (cycle-safe); at least one concrete ancestor carries
82
+ // its own kind from method signatures.
83
+ for (const ancestor of this.superclassClosure(def.name)) {
84
+ if (ancestor === def.name)
85
+ continue;
86
+ const parent = this.registry.get(ancestor);
87
+ if (parent?.expectedKind === '* -> *') {
88
+ def.expectedKind = '* -> *';
89
+ return;
90
+ }
91
+ }
92
+ }
93
+ /** Get all registered constraint names. */
94
+ getNames() {
95
+ return Array.from(this.registry.keys());
96
+ }
97
+ /** Clear all constraint definitions. */
98
+ clear() {
99
+ this.registry.clear();
100
+ }
101
+ /** Save a snapshot of all constraint registrations. */
102
+ snapshot() {
103
+ return new Map(this.registry);
104
+ }
105
+ /** Restore constraint registrations from a snapshot. */
106
+ restore(snap) {
107
+ this.registry.clear();
108
+ for (const [k, v] of snap) {
109
+ this.registry.set(k, v);
110
+ }
111
+ }
112
+ /** Merge a snapshot's registrations (non-destructive). */
113
+ merge(snap) {
114
+ for (const [k, v] of snap) {
115
+ if (!this.registry.has(k)) {
116
+ this.registry.set(k, v);
117
+ }
118
+ }
119
+ }
120
+ /**
121
+ * Collect all effective methods for a constraint, including inherited ones.
122
+ * Child methods override parent methods of the same name.
123
+ * Uses a visited set to prevent infinite loops in case of cycles.
124
+ */
125
+ getEffectiveMethods(constraintName) {
126
+ const methods = new Map();
127
+ const visited = new Set();
128
+ const collect = (name) => {
129
+ if (visited.has(name))
130
+ return;
131
+ visited.add(name);
132
+ const def = this.registry.get(name);
133
+ if (!def)
134
+ return;
135
+ // Collect parent methods first (so child methods override)
136
+ if (def.extends) {
137
+ for (const parent of def.extends) {
138
+ collect(parent);
139
+ }
140
+ }
141
+ // Own methods override inherited ones
142
+ for (const m of def.methods) {
143
+ methods.set(m.name, { ...m, ownerTypeVar: def.typeVar });
144
+ }
145
+ };
146
+ collect(constraintName);
147
+ return Array.from(methods.values());
148
+ }
149
+ /**
150
+ * Collect the superclass closure of a constraint: the constraint itself
151
+ * plus every ancestor reachable through `extends` (transitively). Used to
152
+ * decide whether a DECLARED (given) constraint entails a REQUIRED (wanted)
153
+ * one — e.g. a signature declaring `Applicative f` also provides `Apply f`
154
+ * and `Functor f`.
155
+ */
156
+ superclassClosure(constraintName) {
157
+ const out = new Set();
158
+ const visit = (name) => {
159
+ if (out.has(name))
160
+ return;
161
+ out.add(name);
162
+ const def = this.registry.get(name);
163
+ if (def?.extends) {
164
+ for (const parent of def.extends)
165
+ visit(parent);
166
+ }
167
+ };
168
+ visit(constraintName);
169
+ return out;
170
+ }
171
+ /**
172
+ * Check whether a concrete type satisfies a constraint.
173
+ * A type satisfies a constraint if it has all required methods registered
174
+ * in the method registry. Includes inherited methods.
175
+ */
176
+ checkConstraint(constraintName, typeName) {
177
+ const def = this.registry.get(constraintName);
178
+ if (!def) {
179
+ return { satisfied: false, missing: [] };
180
+ }
181
+ const effectiveMethods = this.getEffectiveMethods(constraintName);
182
+ const missing = [];
183
+ for (const req of effectiveMethods) {
184
+ const entry = (0, methodRegistry_1.lookupMethod)(typeName, req.name);
185
+ if (!entry) {
186
+ missing.push(req.name);
187
+ }
188
+ }
189
+ return { satisfied: missing.length === 0, missing };
190
+ }
191
+ }
192
+ exports.ConstraintRegistry = ConstraintRegistry;
193
+ /** Default global registry instance (backward compatibility). */
194
+ const defaultConstraintRegistry = new ConstraintRegistry();
195
+ // ---------------------------------------------------------------------------
196
+ // Backward-compatible free functions (delegate to defaultConstraintRegistry)
197
+ // ---------------------------------------------------------------------------
198
+ /**
199
+ * Register a constraint definition.
200
+ */
201
+ function registerConstraint(def) {
202
+ defaultConstraintRegistry.register(def);
203
+ }
204
+ /**
205
+ * Look up a constraint definition by name.
206
+ */
207
+ function lookupConstraint(name) {
208
+ return defaultConstraintRegistry.lookup(name);
209
+ }
210
+ /**
211
+ * Get all registered constraint names.
212
+ */
213
+ function getConstraintNames() {
214
+ return defaultConstraintRegistry.getNames();
215
+ }
216
+ /**
217
+ * Get all effective methods for a constraint, including inherited ones.
218
+ */
219
+ function getEffectiveMethods(constraintName) {
220
+ return defaultConstraintRegistry.getEffectiveMethods(constraintName);
221
+ }
222
+ /**
223
+ * Get the superclass closure of a constraint (itself + all `extends`
224
+ * ancestors, transitively).
225
+ */
226
+ function constraintSuperclassClosure(constraintName) {
227
+ return defaultConstraintRegistry.superclassClosure(constraintName);
228
+ }
229
+ /**
230
+ * Clear all constraint definitions.
231
+ * Called at the start of each inference run.
232
+ */
233
+ function clearConstraints() {
234
+ defaultConstraintRegistry.clear();
235
+ }
236
+ /** Save a snapshot of all constraint registrations. */
237
+ function snapshotConstraintRegistry() {
238
+ return defaultConstraintRegistry.snapshot();
239
+ }
240
+ /** Restore constraint registrations from a snapshot. */
241
+ function restoreConstraintRegistry(snap) {
242
+ defaultConstraintRegistry.restore(snap);
243
+ }
244
+ /** Merge a snapshot's registrations into the current registry (non-destructive). */
245
+ function mergeConstraintRegistry(snap) {
246
+ defaultConstraintRegistry.merge(snap);
247
+ }
248
+ /**
249
+ * Check whether a concrete type (by name) satisfies a constraint.
250
+ */
251
+ function checkConstraint(constraintName, typeName) {
252
+ return defaultConstraintRegistry.checkConstraint(constraintName, typeName);
253
+ }
254
+ // ---------------------------------------------------------------------------
255
+ // ::constraint directive parsing — unified syntax
256
+ // ---------------------------------------------------------------------------
257
+ //
258
+ // Single grammar:
259
+ //
260
+ // ::constraint Name p1 p2 … pN { clause, clause, … }
261
+ //
262
+ // clause ::= paramName '::' rhs
263
+ // rhs ::= '{' field, field, … '}' — record (methods if `~>`-shaped, else fields)
264
+ // | UpperIdent — super-constraint reference (extends)
265
+ // | type ('|' type)* — union (structural alternatives)
266
+ // | type — single-type structural equality
267
+ //
268
+ // Internally desugared to the existing ConstraintDef shape:
269
+ // - record clauses whose every field uses `~>` ⇒ `methods[]` (nominal class)
270
+ // - bare-uppercase clauses naming another constraint ⇒ `extends[]`
271
+ // - everything else ⇒ `selfClauses[]` (structural)
272
+ //
273
+ // All clause `paramName`s must appear in the header parameter list.
274
+ // ---------------------------------------------------------------------------
275
+ /**
276
+ * Header pattern:
277
+ * `::constraint Name p1 p2 … pN { … }`
278
+ *
279
+ * Captures: (1) constraint name, (2) header params (one or more
280
+ * space-separated lowercase idents), (3) body between the outermost braces.
281
+ */
282
+ const CONSTRAINT_HEADER_PATTERN = /^[\s*]*::constraint\s+([A-Z]\w*)\s+([a-z]\w*(?:\s+[a-z]\w*)*)\s*\{([\s\S]*)\}\s*$/m;
283
+ /** Split a string on top-level commas (respecting parens/brackets/braces). */
284
+ function splitTopLevelCommas(s) {
285
+ const parts = [];
286
+ let depth = 0;
287
+ let cur = '';
288
+ for (const ch of s) {
289
+ if (ch === '(' || ch === '[' || ch === '{')
290
+ depth++;
291
+ else if (ch === ')' || ch === ']' || ch === '}')
292
+ depth--;
293
+ if (ch === ',' && depth === 0) {
294
+ parts.push(cur);
295
+ cur = '';
296
+ }
297
+ else {
298
+ cur += ch;
299
+ }
300
+ }
301
+ if (cur.trim() !== '')
302
+ parts.push(cur);
303
+ return parts;
304
+ }
305
+ /**
306
+ * Parse a `// ::constraint` comment body into a ConstraintDef using the
307
+ * unified syntax. Returns null if the comment doesn't match.
308
+ */
309
+ function parseConstraintDirective(commentText) {
310
+ const m = CONSTRAINT_HEADER_PATTERN.exec(commentText);
311
+ if (!m)
312
+ return null;
313
+ const name = m[1];
314
+ const headerRaw = m[2];
315
+ const bodyRaw = m[3];
316
+ const headerParams = headerRaw.split(/\s+/).filter(Boolean);
317
+ if (headerParams.length === 0)
318
+ return null;
319
+ const headerSet = new Set(headerParams);
320
+ const clauseTexts = splitTopLevelCommas(bodyRaw);
321
+ if (clauseTexts.length === 0)
322
+ return null;
323
+ const methods = [];
324
+ const selfClauses = [];
325
+ const extendsNames = [];
326
+ for (const raw of clauseTexts) {
327
+ const clause = raw.trim();
328
+ if (!clause)
329
+ continue;
330
+ // `<param> :: <rhs>`
331
+ const cm = /^([a-z]\w*)\s*::\s*([\s\S]+)$/.exec(clause);
332
+ if (!cm)
333
+ return null;
334
+ const param = cm[1];
335
+ const rhs = cm[2].trim();
336
+ if (!headerSet.has(param))
337
+ return null;
338
+ // (1) Record body: `{ field :: sig, ... }` — always treated as a
339
+ // method record (nominal type-class). Methods may use `~>` for
340
+ // instance methods or a plain function/value type for statics.
341
+ const recordBody = stripOuterBraces(rhs);
342
+ if (recordBody !== null) {
343
+ const fields = splitTopLevelCommas(recordBody);
344
+ const fieldDecls = fields
345
+ .map(f => /^(\w+)\s*::\s*([\s\S]+)$/.exec(f.trim()))
346
+ .filter((x) => x !== null);
347
+ if (fieldDecls.length !== fields.length || fieldDecls.length === 0) {
348
+ return null;
349
+ }
350
+ for (const fd of fieldDecls) {
351
+ methods.push({ name: fd[1], signature: fd[2].trim() });
352
+ }
353
+ continue;
354
+ }
355
+ // (2) Bare uppercase identifier: super-constraint reference.
356
+ // Examples: `m :: Chain`, `m :: Applicative`. We match a bare TCon-name
357
+ // that does NOT contain a type application or function arrow — those
358
+ // should still go through structural parsing.
359
+ if (/^[A-Z]\w*$/.test(rhs)) {
360
+ extendsNames.push(rhs);
361
+ continue;
362
+ }
363
+ // (3) Otherwise: structural body (single type or `T1 | T2 | …` union).
364
+ try {
365
+ const body = (0, typeParser_1.parseType)(rhs);
366
+ selfClauses.push({ selfParam: param, body });
367
+ }
368
+ catch {
369
+ return null;
370
+ }
371
+ }
372
+ if (methods.length === 0 && selfClauses.length === 0 && extendsNames.length === 0) {
373
+ return null;
374
+ }
375
+ // typeVar = LAST header param (convention: the "main" constrained var).
376
+ const typeVar = headerParams[headerParams.length - 1];
377
+ // Kind: `* -> *` if the typeVar is applied anywhere (in a method record
378
+ // signature or in a structural body); `*` otherwise.
379
+ const expectedKind = inferKindFromDef(typeVar, methods, selfClauses);
380
+ return {
381
+ name,
382
+ typeVar,
383
+ methods,
384
+ headerParams,
385
+ selfClauses: selfClauses.length > 0 ? selfClauses : undefined,
386
+ extends: extendsNames.length > 0 ? extendsNames : undefined,
387
+ expectedKind,
388
+ bodyText: bodyRaw.trim(),
389
+ };
390
+ }
391
+ /** If `s` is `{ … }` (with balanced outer braces), return the inner content. */
392
+ function stripOuterBraces(s) {
393
+ if (!s.startsWith('{') || !s.endsWith('}'))
394
+ return null;
395
+ let depth = 0;
396
+ for (let i = 0; i < s.length; i++) {
397
+ const ch = s[i];
398
+ if (ch === '{')
399
+ depth++;
400
+ else if (ch === '}') {
401
+ depth--;
402
+ if (depth === 0 && i !== s.length - 1)
403
+ return null;
404
+ }
405
+ }
406
+ return depth === 0 ? s.slice(1, -1).trim() : null;
407
+ }
408
+ /**
409
+ * Infer the expected kind of a constraint's type variable from its method
410
+ * signatures and structural body types. `* -> *` if applied anywhere
411
+ * (e.g. `f a`); `*` otherwise.
412
+ */
413
+ function inferExpectedKind(typeVar, methods) {
414
+ const pattern = new RegExp(`\\b${typeVar}\\s+[a-z(]`);
415
+ for (const m of methods) {
416
+ if (pattern.test(m.signature))
417
+ return '* -> *';
418
+ }
419
+ return '*';
420
+ }
421
+ function inferKindFromDef(typeVar, methods, selfClauses) {
422
+ if (inferExpectedKind(typeVar, methods) === '* -> *')
423
+ return '* -> *';
424
+ // Structural bodies don't currently carry kind information here; the
425
+ // body Types are first-order. We still return '*' for them — kind issues
426
+ // surface at unification time.
427
+ void selfClauses;
428
+ return '*';
429
+ }
430
+ /**
431
+ * Validate a constraint definition for kind consistency and completeness.
432
+ * Returns an array of human-readable warning/error messages (empty if valid).
433
+ */
434
+ function validateConstraintDef(def) {
435
+ const errors = [];
436
+ const { typeVar, methods, name } = def;
437
+ // For pure-structural / pure-extends defs there's nothing to validate
438
+ // beyond what the parser already guarantees (clause params ∈ header).
439
+ if (methods.length === 0) {
440
+ return errors;
441
+ }
442
+ // 1. Check that the type variable appears in at least one method signature
443
+ const barePattern = new RegExp(`\\b${typeVar}\\b`);
444
+ const usedInAny = methods.some(m => barePattern.test(m.signature));
445
+ if (!usedInAny) {
446
+ errors.push(`Type variable '${typeVar}' is not used in any method signature of constraint '${name}'.`);
447
+ }
448
+ // 2. Check for inconsistent kind usage:
449
+ // typeVar used both bare (kind *) and applied (kind * -> *) across methods
450
+ const appliedPattern = new RegExp(`\\b${typeVar}\\s+[a-z(]`);
451
+ const bareOnlyPattern = new RegExp(`\\b${typeVar}(?:\\s*(?:~>|->|,|\\)|$))`);
452
+ const hasApplied = methods.some(m => appliedPattern.test(m.signature));
453
+ const hasBare = methods.some(m => bareOnlyPattern.test(m.signature));
454
+ if (hasApplied && hasBare) {
455
+ errors.push(`Inconsistent kind for '${typeVar}' in constraint '${name}': used as both kind * (concrete type) and kind * -> * (type constructor). ` +
456
+ `If '${typeVar}' is a type constructor, all occurrences should use '${typeVar} a'. ` +
457
+ `If '${typeVar}' is a concrete type, it should not be applied.`);
458
+ }
459
+ return errors;
460
+ }
461
+ // ---------------------------------------------------------------------------
462
+ // Constraint shape matching
463
+ // ---------------------------------------------------------------------------
464
+ /**
465
+ * Check that a registered method's signature shape matches the constraint's
466
+ * required shape. Wherever the constraint's type variable (`f`, `m`, etc.)
467
+ * appears in the constraint signature, the registered method must use the
468
+ * concrete type constructor.
469
+ *
470
+ * Returns a human-readable mismatch description, or null if the shape is OK.
471
+ */
472
+ function checkConstraintMethodShape(constraintTypeVar, constraintMethodSig, concreteName, registeredEntry) {
473
+ try {
474
+ const constraintParsed = (0, typeParser_1.parseMethodTypeSignature)(constraintMethodSig, [constraintTypeVar]);
475
+ const regSig = registeredEntry.signature;
476
+ if (!regSig.includes('~>')) {
477
+ // A method whose registered signature carries no `~>` receiver is a
478
+ // built-in / plain method (e.g. Array's native `reduce`). Validate its
479
+ // shape against the constraint exactly as for `~>`-bearing methods: the
480
+ // registered type must match the constraint method's required form
481
+ // position-for-position. This is a purely structural check — a
482
+ // constraint method such as `(b -> a -> b) -> b -> b` is rejected by a
483
+ // built-in like `((b, a, …) -> b, b) -> b` not because of currying, but
484
+ // because the two shapes simply do not unify.
485
+ let regType;
486
+ try {
487
+ regType = (0, typeParser_1.parseType)(regSig);
488
+ }
489
+ catch {
490
+ return null;
491
+ }
492
+ if (!matchesConstraintShapeAnySlot(constraintParsed.methodType, regType, constraintTypeVar, concreteName)) {
493
+ return `has signature '${regSig}' which cannot be unified with the required '${(0, types_1.typeToString)(constraintParsed.methodType)}'`;
494
+ }
495
+ return null;
496
+ }
497
+ const regParsed = (0, typeParser_1.parseMethodTypeSignature)(regSig);
498
+ if (!matchesConstraintShapeAnySlot(constraintParsed.methodType, regParsed.methodType, constraintTypeVar, concreteName)) {
499
+ return `signature does not match constraint shape`;
500
+ }
501
+ return null;
502
+ }
503
+ catch { /* parse/validation error — constraint shape invalid */
504
+ return null;
505
+ }
506
+ }
507
+ /**
508
+ * Shape-check a *static* constraint method (one whose constraint signature
509
+ * carries no `~>` receiver, e.g. Foldable's `off :: a -> f a`) against a
510
+ * representing local annotation (also receiver-less, e.g. `off :: a -> Array a`).
511
+ *
512
+ * Both sides are plain types. We parse the constraint requirement with the
513
+ * constraint variable known so applied positions like `f a` become kind-var
514
+ * constructors, parse the local signature normally, then run the same
515
+ * structural / linkage check used for instance methods. Returns a
516
+ * human-readable mismatch description, or null if the shape is OK.
517
+ */
518
+ function checkStaticConstraintMethodShape(constraintTypeVar, constraintMethodSig, concreteName, registeredSig) {
519
+ try {
520
+ // Reuse the method-signature parser (which knows how to treat a bare
521
+ // constraint variable applied to args as a kind-variable constructor) by
522
+ // prefixing a synthetic receiver; only `.methodType` is consulted.
523
+ const constraintParsed = (0, typeParser_1.parseMethodTypeSignature)(`${constraintTypeVar} ~> ${constraintMethodSig}`, [constraintTypeVar]);
524
+ const regType = (0, typeParser_1.parseType)(registeredSig);
525
+ if (!matchesConstraintShapeAnySlot(constraintParsed.methodType, regType, constraintTypeVar, concreteName)) {
526
+ return `signature does not match constraint shape`;
527
+ }
528
+ return null;
529
+ }
530
+ catch { /* parse/validation error — constraint shape invalid */
531
+ return null;
532
+ }
533
+ }
534
+ /**
535
+ * Structural equality between two registered sub-types, comparing type
536
+ * variables by identity (id). Used by the linkage check to decide whether a
537
+ * repeated constraint variable maps to the *same* registered type as before.
538
+ */
539
+ function sameRegisteredType(a, b) {
540
+ if (a.tag !== b.tag)
541
+ return false;
542
+ switch (a.tag) {
543
+ case 'TVar':
544
+ return a.id === b.id;
545
+ case 'TCon': {
546
+ const bc = b;
547
+ if (a.name !== bc.name || a.args.length !== bc.args.length)
548
+ return false;
549
+ return a.args.every((x, i) => sameRegisteredType(x, bc.args[i]));
550
+ }
551
+ case 'TFun': {
552
+ const bf = b;
553
+ return sameRegisteredType(a.param, bf.param) && sameRegisteredType(a.result, bf.result);
554
+ }
555
+ default:
556
+ // Records / rows / labels: be conservative and treat them as equal so we
557
+ // never *introduce* a false mismatch for shapes the linkage check does
558
+ // not model precisely.
559
+ return true;
560
+ }
561
+ }
562
+ /**
563
+ * Normalise an optional registered parameter `X | Undefined` down to `X` for
564
+ * constraint-shape matching.
565
+ *
566
+ * Built-in methods model an omittable argument as a union with `Undefined`
567
+ * (e.g. Array#reduce's optional initial value `b | Undefined`, produced by
568
+ * `opt()` in the method registry). In a constraint requirement the same slot
569
+ * is written as the bare type (`b`), so without this normalisation the linkage
570
+ * check compares a plain `TVar b` against a `Union[b, Undefined]` and reports a
571
+ * spurious shape mismatch. An optional parameter is a supertype of its
572
+ * mandatory form in contravariant position, so treating `X | Undefined` as `X`
573
+ * here is sound. Only strips when `Undefined` is actually a member, leaving
574
+ * genuine value unions such as `[a | b]` untouched.
575
+ */
576
+ function stripOptional(t) {
577
+ if (t.tag === 'TCon' && t.name === types_1.T_UNION) {
578
+ const members = t.args.filter(m => !(m.tag === 'TCon' && m.name === 'Undefined'));
579
+ if (members.length !== t.args.length) {
580
+ return members.length === 1 ? members[0] : (0, types_1.tCon)(types_1.T_UNION, members);
581
+ }
582
+ }
583
+ return t;
584
+ }
585
+ /** `Undefined` itself, or a union that admits `Undefined` — i.e. an
586
+ * omittable parameter slot as produced by `opt()` in the method registry. */
587
+ function isOptionalSlot(t) {
588
+ if (t.tag !== 'TCon')
589
+ return false;
590
+ if (t.name === 'Undefined')
591
+ return true;
592
+ return t.name === types_1.T_UNION && t.args.some(m => m.tag === 'TCon' && m.name === 'Undefined');
593
+ }
594
+ /** A registered parameter position that may be omitted ENTIRELY when
595
+ * calling: a single optional slot, or a parameter-group tuple consisting
596
+ * solely of optional slots. */
597
+ function isFullyOptionalParam(t) {
598
+ if (isOptionalSlot(t))
599
+ return true;
600
+ return t.tag === 'TCon' && t.name === types_1.T_TUPLE
601
+ && t.args.length > 0 && t.args.every(isOptionalSlot);
602
+ }
603
+ /**
604
+ * Match a constraint method type against a registered method type, trying the
605
+ * historical rightmost kind-variable alignment first (backward compatible) and
606
+ * then alternative left-anchored slot alignments for wider, multi-parameter
607
+ * registered constructors.
608
+ *
609
+ * Motivation: a constraint's kind variable `f` is unary, but a concrete type
610
+ * may be k-ary (`Arrow a b`). Different constraints operate on different
611
+ * parameters of the same ADT — Functor's `map` on the rightmost (`b`),
612
+ * Contravariant's `contramap` on the leftmost (`a`). The type-variable linkage
613
+ * check inside {@link matchesConstraintShape} rejects every inconsistent
614
+ * alignment, so at most one slot produces a match and there is no ambiguity.
615
+ */
616
+ function matchesConstraintShapeAnySlot(constraintType, registeredType, constraintVar, concreteName) {
617
+ // Rightmost (default) alignment — preserves prior behaviour exactly.
618
+ if (matchesConstraintShape(constraintType, registeredType, constraintVar, concreteName, { varMap: new Map() })) {
619
+ return true;
620
+ }
621
+ // Alternative left-anchored slots (0 = leftmost). Capped generously; real
622
+ // constraint-operated constructors are low arity.
623
+ const MAX_CONSTRAINT_SLOT = 8;
624
+ for (let slot = 0; slot <= MAX_CONSTRAINT_SLOT; slot++) {
625
+ if (matchesConstraintShape(constraintType, registeredType, constraintVar, concreteName, { varMap: new Map(), slotOffset: slot })) {
626
+ return true;
627
+ }
628
+ }
629
+ return false;
630
+ }
631
+ /**
632
+ * Recursively check that wherever the constraint's type variable appears as a
633
+ * type constructor in `constraintType`, the corresponding position in
634
+ * `registeredType` uses `concreteName`.
635
+ *
636
+ * When a {@link ConstraintShapeContext} is supplied, inner type variables are
637
+ * additionally checked for *linkage* consistency (see the interface docs).
638
+ */
639
+ function matchesConstraintShape(constraintType, registeredType, constraintVar, concreteName, ctx, inFunctionParam = false) {
640
+ // An optional registered parameter (`X | Undefined`) satisfies a constraint
641
+ // requirement of `X`; normalise it away before any structural / linkage
642
+ // comparison. Applied on every (recursive) entry so nested optional slots —
643
+ // e.g. Array#reduce's `b | Undefined` initial value inside a parameter tuple
644
+ // — are handled too.
645
+ registeredType = stripOptional(registeredType);
646
+ // `Any` in a constraint's required shape accepts every registered type
647
+ // (a deliberately unconstrained slot, e.g. `value :: m ~> Any`).
648
+ if ((0, types_1.isAnyType)(constraintType))
649
+ return true;
650
+ if (constraintType.tag === 'TCon') {
651
+ const kv = (0, types_1.parseKvName)(constraintType.name);
652
+ if (kv && kv.varName === constraintVar) {
653
+ if (registeredType.tag !== 'TCon' || registeredType.name !== concreteName)
654
+ return false;
655
+ const cArgs = constraintType.args;
656
+ let rArgs = registeredType.args;
657
+ // Functions as a binary constructor (Profunctor): `p b c` reads
658
+ // `Function [b] c` — the single-parameter list `[b]` IS the slot `b`.
659
+ if (concreteName === types_1.T_FUNCTION && cArgs.length === 2 && rArgs.length === 2) {
660
+ const params = (0, types_1.functionParamList)(rArgs[0]);
661
+ if (params && params.length === 1)
662
+ rArgs = [params[0], rArgs[1]];
663
+ }
664
+ if (rArgs.length < cArgs.length)
665
+ return false;
666
+ const extra = rArgs.length - cArgs.length;
667
+ // The constraint applies its kind variable to `cArgs.length` argument(s);
668
+ // the registered constructor may carry MORE parameters (a multi-param
669
+ // ADT viewed through a unary constraint). By default the constraint's
670
+ // argument aligns with the RIGHTMOST slots (the Functor convention). A
671
+ // caller may instead pin a specific left-anchored slot via
672
+ // `ctx.slotOffset` — used to match constraints (e.g. Contravariant) whose
673
+ // operated parameter is not the rightmost. An out-of-range pin fails the
674
+ // attempt so slot enumeration stays consistent across occurrences.
675
+ let offset = extra;
676
+ if (ctx && ctx.slotOffset !== undefined) {
677
+ if (ctx.slotOffset > extra)
678
+ return false;
679
+ offset = ctx.slotOffset;
680
+ }
681
+ for (let i = 0; i < cArgs.length; i++) {
682
+ if (!matchesConstraintShape(cArgs[i], rArgs[offset + i], constraintVar, concreteName, ctx))
683
+ return false;
684
+ }
685
+ return true;
686
+ }
687
+ // Any other kind-variable constructor — an INNER constructor var of the
688
+ // constraint method signature (e.g. `f` from `traverse`'s own
689
+ // `Applicative f =>` prefix). The registered signature declares its own
690
+ // `f` with an unrelated kv id, so name equality can never hold; match a
691
+ // registered kv application structurally, linking the pair of heads for
692
+ // consistency across occurrences (`f b` and `f (t b)` must meet the SAME
693
+ // registered constructor var).
694
+ if (kv) {
695
+ if (registeredType.tag !== 'TCon')
696
+ return false;
697
+ const rkv = (0, types_1.parseKvName)(registeredType.name);
698
+ if (!rkv)
699
+ return false;
700
+ if (constraintType.args.length !== registeredType.args.length)
701
+ return false;
702
+ if (ctx) {
703
+ const prev = ctx.kvHeadMap?.get(kv.varId);
704
+ if (prev === undefined) {
705
+ (ctx.kvHeadMap ?? (ctx.kvHeadMap = new Map())).set(kv.varId, registeredType.name);
706
+ }
707
+ else if (prev !== registeredType.name) {
708
+ return false;
709
+ }
710
+ }
711
+ return constraintType.args.every((a, i) => matchesConstraintShape(a, registeredType.args[i], constraintVar, concreteName, ctx));
712
+ }
713
+ // Any other concrete constructor (including `Tuple`, which represents a
714
+ // multi-parameter parameter group `(a, b) -> r`): the registered side must
715
+ // use the SAME constructor with the SAME arity at this position. This is
716
+ // what makes the check form-exact, e.g. a tuple parameter group
717
+ // `(b, a) -> b` (TFun(Tuple[b,a], b)) does NOT match a curried
718
+ // `b -> a -> b` (TFun(b, TFun(a, b))), and vice versa.
719
+ if (registeredType.tag !== 'TCon')
720
+ return false;
721
+ if (constraintType.name !== registeredType.name)
722
+ return false;
723
+ // Function parameter-group tuples tolerate surplus trailing parameters on
724
+ // either side — a JS callback may ignore the extra arguments it is passed
725
+ // (e.g. a native `Array#reduce` 4-arg callback satisfying a 2-arg
726
+ // `reduce`). Only the leading (shared) positions need to match; the
727
+ // tupled-vs-curried distinction is still enforced by the constructor-form
728
+ // check above, so this stays sound.
729
+ if (inFunctionParam && constraintType.name === types_1.T_TUPLE) {
730
+ const n = Math.min(constraintType.args.length, registeredType.args.length);
731
+ for (let i = 0; i < n; i++) {
732
+ if (!matchesConstraintShape(constraintType.args[i], registeredType.args[i], constraintVar, concreteName, ctx))
733
+ return false;
734
+ }
735
+ return true;
736
+ }
737
+ if (constraintType.args.length !== registeredType.args.length)
738
+ return false;
739
+ return constraintType.args.every((a, i) => matchesConstraintShape(a, registeredType.args[i], constraintVar, concreteName, ctx));
740
+ }
741
+ if (constraintType.tag === 'TFun') {
742
+ if (registeredType.tag !== 'TFun')
743
+ return false;
744
+ // A NULLARY constraint method (`() -> r`, parameter `Void`) is satisfied
745
+ // by a registered method whose parameters are ALL optional
746
+ // (`X | Undefined`, the method registry's `opt()` encoding): such a
747
+ // method is callable with zero arguments, exactly what the constraint
748
+ // promises. E.g. `Number#toString :: (Number | Undefined) -> String`
749
+ // satisfies Showable's `toString :: () -> String`. Decided BEFORE the
750
+ // stripOptional normalisation below, which erases precisely the
751
+ // optionality that makes this sound (leaving `Void` vs `Number`).
752
+ if (constraintType.param.tag === 'TCon' && constraintType.param.name === 'Void'
753
+ && isFullyOptionalParam(registeredType.param)) {
754
+ return matchesConstraintShape(constraintType.result, registeredType.result, constraintVar, concreteName, ctx);
755
+ }
756
+ let cParam = constraintType.param;
757
+ let rParam = stripOptional(registeredType.param);
758
+ // Surplus-trailing-parameter tolerance for the BARE (1-arity) parameter
759
+ // form: a constraint callback written as a single parameter (`a -> Boolean`)
760
+ // is satisfied by a registered multi-parameter group
761
+ // (`(a, Number, [a]) -> Boolean`, e.g. native `Array#filter`) — the extra
762
+ // arguments are simply ignored by a 1-arg JS callback. A single parameter
763
+ // is not represented as a `Tuple`, so the Tuple-vs-Tuple tolerance below
764
+ // (in the TCon branch) never sees this case; align the bare side with the
765
+ // FIRST element of the wider group instead. Mirrored for the reverse
766
+ // direction (constraint group vs bare registered parameter).
767
+ const isParamGroup = (t) => t.tag === 'TCon' && t.name === types_1.T_TUPLE;
768
+ if (!isParamGroup(cParam) && isParamGroup(rParam) && rParam.args.length >= 1) {
769
+ rParam = rParam.args[0];
770
+ }
771
+ else if (isParamGroup(cParam) && !isParamGroup(rParam) && cParam.args.length >= 1) {
772
+ cParam = cParam.args[0];
773
+ }
774
+ return matchesConstraintShape(cParam, rParam, constraintVar, concreteName, ctx, true) &&
775
+ matchesConstraintShape(constraintType.result, registeredType.result, constraintVar, concreteName, ctx);
776
+ }
777
+ // A polymorphic variable in the constraint signature (other than the
778
+ // constraint's own type-constructor var) is a wildcard — but, when a linkage
779
+ // context is supplied, each distinct *inner* constraint variable must map to
780
+ // a consistent registered sub-type across all of its occurrences. This is
781
+ // what catches return-position variable swaps such as `f b` vs `f a`.
782
+ //
783
+ // The constraint's *own* variable (e.g. `s` in `Semigroup s`) is deliberately
784
+ // excluded: when it has kind `*` it is parsed as a bare `TVar` here, and it
785
+ // legitimately matches *different* concrete shapes across positions — e.g.
786
+ // `Semigroup`'s `concat :: s ~> s -> s` is satisfied by Array's widening
787
+ // `[a] ~> [b] -> [a | b]`, where the input `s` is `[b]` but the output `s`
788
+ // is `[a | b]`. Treating it as a wildcard preserves that.
789
+ if (constraintType.tag === 'TVar') {
790
+ if (ctx && constraintType.name !== constraintVar) {
791
+ const prev = ctx.varMap.get(constraintType.id);
792
+ if (prev === undefined) {
793
+ ctx.varMap.set(constraintType.id, registeredType);
794
+ }
795
+ else if (!sameRegisteredType(prev, registeredType)) {
796
+ return false;
797
+ }
798
+ }
799
+ return true;
800
+ }
801
+ return true;
802
+ }
803
+ //# sourceMappingURL=constraintRegistry.js.map