yukigo 0.2.3 → 0.3.2

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 (266) hide show
  1. package/.mocharc.json +3 -3
  2. package/CHANGELOG.md +105 -40
  3. package/README.md +193 -193
  4. package/dist/analyzer/GraphBuilder.d.ts +1 -0
  5. package/dist/analyzer/GraphBuilder.js +2 -1
  6. package/dist/analyzer/index.d.ts +0 -7
  7. package/dist/analyzer/index.js +3 -3
  8. package/dist/analyzer/inspections/functional/functional.d.ts +1 -1
  9. package/dist/analyzer/inspections/functional/functional.js +1 -1
  10. package/dist/analyzer/inspections/functional/smells.d.ts +3 -3
  11. package/dist/analyzer/inspections/functional/smells.js +27 -35
  12. package/dist/analyzer/inspections/generic/generic.d.ts +22 -14
  13. package/dist/analyzer/inspections/generic/generic.js +82 -60
  14. package/dist/analyzer/inspections/generic/smells.d.ts +2 -0
  15. package/dist/analyzer/inspections/generic/smells.js +55 -64
  16. package/dist/analyzer/inspections/imperative/imperative.d.ts +3 -3
  17. package/dist/analyzer/inspections/imperative/imperative.js +3 -3
  18. package/dist/analyzer/inspections/imperative/smells.d.ts +1 -0
  19. package/dist/analyzer/inspections/imperative/smells.js +8 -5
  20. package/dist/analyzer/inspections/logic/logic.d.ts +8 -8
  21. package/dist/analyzer/inspections/logic/logic.js +5 -5
  22. package/dist/analyzer/inspections/logic/smells.js +2 -2
  23. package/dist/analyzer/inspections/object/object.d.ts +5 -5
  24. package/dist/analyzer/inspections/object/object.js +22 -21
  25. package/dist/analyzer/inspections/object/smells.js +11 -23
  26. package/dist/analyzer/utils.d.ts +6 -2
  27. package/dist/analyzer/utils.js +6 -2
  28. package/dist/interpreter/components/EnvBuilder.d.ts +20 -1
  29. package/dist/interpreter/components/EnvBuilder.js +211 -66
  30. package/dist/interpreter/components/EqualityComparer.d.ts +15 -0
  31. package/dist/interpreter/components/EqualityComparer.js +69 -0
  32. package/dist/interpreter/components/Operations.d.ts +17 -14
  33. package/dist/interpreter/components/Operations.js +61 -62
  34. package/dist/interpreter/components/PatternMatcher.d.ts +19 -58
  35. package/dist/interpreter/components/PatternMatcher.js +185 -286
  36. package/dist/interpreter/components/RuntimeContext.d.ts +24 -15
  37. package/dist/interpreter/components/RuntimeContext.js +43 -4
  38. package/dist/interpreter/components/TestRunner.d.ts +15 -13
  39. package/dist/interpreter/components/TestRunner.js +86 -53
  40. package/dist/interpreter/components/evaluators/BaseEvaluator.d.ts +19 -0
  41. package/dist/interpreter/components/evaluators/BaseEvaluator.js +20 -0
  42. package/dist/interpreter/components/evaluators/ExpressionEvaluator.d.ts +34 -0
  43. package/dist/interpreter/components/evaluators/ExpressionEvaluator.js +298 -0
  44. package/dist/interpreter/components/evaluators/OperationEvaluator.d.ts +25 -0
  45. package/dist/interpreter/components/evaluators/OperationEvaluator.js +226 -0
  46. package/dist/interpreter/components/evaluators/PrimitiveEvaluator.d.ts +19 -0
  47. package/dist/interpreter/components/evaluators/PrimitiveEvaluator.js +50 -0
  48. package/dist/interpreter/components/evaluators/StatementEvaluator.d.ts +28 -0
  49. package/dist/interpreter/components/evaluators/StatementEvaluator.js +240 -0
  50. package/dist/interpreter/components/evaluators/TestingEvaluator.d.ts +15 -0
  51. package/dist/interpreter/components/evaluators/TestingEvaluator.js +14 -0
  52. package/dist/interpreter/components/evaluators/index.d.ts +110 -0
  53. package/dist/interpreter/components/evaluators/index.js +21 -0
  54. package/dist/interpreter/components/evaluators/utils.d.ts +7 -0
  55. package/dist/interpreter/components/evaluators/utils.js +50 -0
  56. package/dist/interpreter/components/hooks/YukigoHook.d.ts +27 -0
  57. package/dist/interpreter/components/hooks/YukigoHook.js +1 -0
  58. package/dist/interpreter/components/kernel/commands.d.ts +122 -0
  59. package/dist/interpreter/components/kernel/commands.js +203 -0
  60. package/dist/interpreter/components/kernel/index.d.ts +51 -0
  61. package/dist/interpreter/components/kernel/index.js +176 -0
  62. package/dist/interpreter/components/logic/LogicEngine.d.ts +26 -23
  63. package/dist/interpreter/components/logic/LogicEngine.js +234 -221
  64. package/dist/interpreter/components/logic/LogicResolver.d.ts +22 -51
  65. package/dist/interpreter/components/logic/LogicResolver.js +73 -440
  66. package/dist/interpreter/components/logic/LogicTerm.d.ts +104 -0
  67. package/dist/interpreter/components/logic/LogicTerm.js +423 -0
  68. package/dist/interpreter/components/logic/LogicTranslator.d.ts +25 -9
  69. package/dist/interpreter/components/logic/LogicTranslator.js +211 -74
  70. package/dist/interpreter/components/runtimes/FunctionRuntime.d.ts +6 -4
  71. package/dist/interpreter/components/runtimes/FunctionRuntime.js +82 -84
  72. package/dist/interpreter/components/runtimes/LazyRuntime.d.ts +13 -14
  73. package/dist/interpreter/components/runtimes/LazyRuntime.js +112 -239
  74. package/dist/interpreter/components/runtimes/ObjectRuntime.d.ts +17 -14
  75. package/dist/interpreter/components/runtimes/ObjectRuntime.js +105 -74
  76. package/dist/interpreter/errors.d.ts +10 -0
  77. package/dist/interpreter/errors.js +17 -0
  78. package/dist/interpreter/index.d.ts +9 -5
  79. package/dist/interpreter/index.js +11 -13
  80. package/dist/interpreter/primitives/YuValue.d.ts +21 -0
  81. package/dist/interpreter/primitives/YuValue.js +40 -0
  82. package/dist/interpreter/primitives/capabilities.d.ts +90 -0
  83. package/dist/interpreter/primitives/capabilities.js +1 -0
  84. package/dist/interpreter/primitives/entities/LazyList.d.ts +48 -0
  85. package/dist/interpreter/primitives/entities/LazyList.js +164 -0
  86. package/dist/interpreter/primitives/entities/LogicResult.d.ts +51 -0
  87. package/dist/interpreter/primitives/entities/LogicResult.js +101 -0
  88. package/dist/interpreter/primitives/entities/RuntimeClass.d.ts +24 -0
  89. package/dist/interpreter/primitives/entities/RuntimeClass.js +57 -0
  90. package/dist/interpreter/primitives/entities/RuntimeFunction.d.ts +40 -0
  91. package/dist/interpreter/primitives/entities/RuntimeFunction.js +73 -0
  92. package/dist/interpreter/primitives/entities/RuntimeObject.d.ts +27 -0
  93. package/dist/interpreter/primitives/entities/RuntimeObject.js +82 -0
  94. package/dist/interpreter/primitives/entities/RuntimePredicate.d.ts +19 -0
  95. package/dist/interpreter/primitives/entities/RuntimePredicate.js +59 -0
  96. package/dist/interpreter/primitives/index.d.ts +14 -0
  97. package/dist/interpreter/primitives/index.js +14 -0
  98. package/dist/interpreter/primitives/scalars/YuBoolean.d.ts +24 -0
  99. package/dist/interpreter/primitives/scalars/YuBoolean.js +69 -0
  100. package/dist/interpreter/primitives/scalars/YuChar.d.ts +28 -0
  101. package/dist/interpreter/primitives/scalars/YuChar.js +78 -0
  102. package/dist/interpreter/primitives/scalars/YuNil.d.ts +25 -0
  103. package/dist/interpreter/primitives/scalars/YuNil.js +73 -0
  104. package/dist/interpreter/primitives/scalars/YuNumber.d.ts +49 -0
  105. package/dist/interpreter/primitives/scalars/YuNumber.js +165 -0
  106. package/dist/interpreter/primitives/sequences/YuArray.d.ts +33 -0
  107. package/dist/interpreter/primitives/sequences/YuArray.js +150 -0
  108. package/dist/interpreter/primitives/sequences/YuString.d.ts +40 -0
  109. package/dist/interpreter/primitives/sequences/YuString.js +130 -0
  110. package/dist/interpreter/utils.d.ts +23 -10
  111. package/dist/interpreter/utils.js +25 -30
  112. package/dist/tester/index.d.ts +3 -3
  113. package/dist/tester/index.js +39 -28
  114. package/dist/utils/helpers.d.ts +13 -5
  115. package/dist/utils/helpers.js +38 -85
  116. package/package.json +3 -16
  117. package/src/analyzer/GraphBuilder.ts +143 -142
  118. package/src/analyzer/index.ts +185 -194
  119. package/src/analyzer/inspections/functional/functional.ts +121 -121
  120. package/src/analyzer/inspections/functional/smells.ts +88 -102
  121. package/src/analyzer/inspections/generic/generic.ts +610 -577
  122. package/src/analyzer/inspections/generic/smells.ts +355 -365
  123. package/src/analyzer/inspections/imperative/imperative.ts +104 -101
  124. package/src/analyzer/inspections/imperative/smells.ts +58 -54
  125. package/src/analyzer/inspections/logic/logic.ts +84 -90
  126. package/src/analyzer/inspections/logic/smells.ts +54 -54
  127. package/src/analyzer/inspections/object/object.ts +295 -264
  128. package/src/analyzer/inspections/object/smells.ts +130 -144
  129. package/src/analyzer/utils.ts +115 -109
  130. package/src/index.ts +3 -3
  131. package/src/interpreter/components/EnvBuilder.ts +405 -202
  132. package/src/interpreter/components/EqualityComparer.ts +107 -0
  133. package/src/interpreter/components/Operations.ts +126 -99
  134. package/src/interpreter/components/PatternMatcher.ts +375 -475
  135. package/src/interpreter/components/RuntimeContext.ts +181 -119
  136. package/src/interpreter/components/TestRunner.ts +223 -151
  137. package/src/interpreter/components/evaluators/BaseEvaluator.ts +36 -0
  138. package/src/interpreter/components/evaluators/ExpressionEvaluator.ts +475 -0
  139. package/src/interpreter/components/evaluators/OperationEvaluator.ts +477 -0
  140. package/src/interpreter/components/evaluators/PrimitiveEvaluator.ts +80 -0
  141. package/src/interpreter/components/evaluators/StatementEvaluator.ts +372 -0
  142. package/src/interpreter/components/evaluators/TestingEvaluator.ts +26 -0
  143. package/src/interpreter/components/evaluators/index.ts +34 -0
  144. package/src/interpreter/components/evaluators/utils.ts +64 -0
  145. package/src/interpreter/components/hooks/YukigoHook.ts +45 -0
  146. package/src/interpreter/components/kernel/commands.ts +255 -0
  147. package/src/interpreter/components/kernel/index.ts +222 -0
  148. package/src/interpreter/components/logic/LogicEngine.ts +509 -519
  149. package/src/interpreter/components/logic/LogicResolver.ts +209 -858
  150. package/src/interpreter/components/logic/LogicTerm.ts +477 -0
  151. package/src/interpreter/components/logic/LogicTranslator.ts +362 -149
  152. package/src/interpreter/components/runtimes/FunctionRuntime.ts +249 -227
  153. package/src/interpreter/components/runtimes/LazyRuntime.ts +226 -334
  154. package/src/interpreter/components/runtimes/ObjectRuntime.ts +262 -224
  155. package/src/interpreter/errors.ts +68 -47
  156. package/src/interpreter/index.ts +50 -52
  157. package/src/interpreter/primitives/YuValue.ts +64 -0
  158. package/src/interpreter/primitives/capabilities.ts +111 -0
  159. package/src/interpreter/primitives/entities/LazyList.ts +225 -0
  160. package/src/interpreter/primitives/entities/LogicResult.ts +133 -0
  161. package/src/interpreter/primitives/entities/RuntimeClass.ts +70 -0
  162. package/src/interpreter/primitives/entities/RuntimeFunction.ts +108 -0
  163. package/src/interpreter/primitives/entities/RuntimeObject.ts +110 -0
  164. package/src/interpreter/primitives/entities/RuntimePredicate.ts +77 -0
  165. package/src/interpreter/primitives/index.ts +17 -0
  166. package/src/interpreter/primitives/scalars/YuBoolean.ts +79 -0
  167. package/src/interpreter/primitives/scalars/YuChar.ts +94 -0
  168. package/src/interpreter/primitives/scalars/YuNil.ts +84 -0
  169. package/src/interpreter/primitives/scalars/YuNumber.ts +187 -0
  170. package/src/interpreter/primitives/sequences/YuArray.ts +178 -0
  171. package/src/interpreter/primitives/sequences/YuString.ts +165 -0
  172. package/src/interpreter/utils.ts +105 -84
  173. package/src/tester/index.ts +157 -128
  174. package/src/utils/helpers.ts +113 -169
  175. package/tests/analyzer/functional.spec.ts +221 -207
  176. package/tests/analyzer/generic.spec.ts +178 -178
  177. package/tests/analyzer/helpers.spec.ts +83 -89
  178. package/tests/analyzer/logic.spec.ts +237 -237
  179. package/tests/analyzer/oop.spec.ts +320 -323
  180. package/tests/analyzer/transitive.spec.ts +166 -166
  181. package/tests/interpreter/EnvBuilder.spec.ts +181 -183
  182. package/tests/interpreter/FunctionRuntime.spec.ts +224 -223
  183. package/tests/interpreter/LazyRuntime.spec.ts +227 -225
  184. package/tests/interpreter/LogicEngine.spec.ts +371 -327
  185. package/tests/interpreter/LogicSubstitution.spec.ts +90 -80
  186. package/tests/interpreter/ObjectRuntime.spec.ts +431 -606
  187. package/tests/interpreter/Operations.spec.ts +312 -220
  188. package/tests/interpreter/PatternSystem.spec.ts +254 -213
  189. package/tests/interpreter/Tests.spec.ts +122 -122
  190. package/tests/interpreter/interpreter.spec.ts +1143 -991
  191. package/tests/kernel/YukigoKernel.spec.ts +112 -0
  192. package/tests/tester/Tester.spec.ts +156 -152
  193. package/tsconfig.build.json +16 -15
  194. package/tsconfig.json +27 -25
  195. package/dist/interpreter/components/Visitor.d.ts +0 -70
  196. package/dist/interpreter/components/Visitor.js +0 -634
  197. package/dist/interpreter/entities.d.ts +0 -105
  198. package/dist/interpreter/entities.js +0 -96
  199. package/dist/interpreter/trampoline.d.ts +0 -17
  200. package/dist/interpreter/trampoline.js +0 -38
  201. package/dist/src/analyzer/GraphBuilder.d.ts +0 -30
  202. package/dist/src/analyzer/GraphBuilder.js +0 -100
  203. package/dist/src/analyzer/index.d.ts +0 -59
  204. package/dist/src/analyzer/index.js +0 -152
  205. package/dist/src/analyzer/inspections/functional/functional.d.ts +0 -44
  206. package/dist/src/analyzer/inspections/functional/functional.js +0 -149
  207. package/dist/src/analyzer/inspections/functional/smells.d.ts +0 -16
  208. package/dist/src/analyzer/inspections/functional/smells.js +0 -98
  209. package/dist/src/analyzer/inspections/generic/generic.d.ts +0 -178
  210. package/dist/src/analyzer/inspections/generic/generic.js +0 -604
  211. package/dist/src/analyzer/inspections/generic/smells.d.ts +0 -61
  212. package/dist/src/analyzer/inspections/generic/smells.js +0 -349
  213. package/dist/src/analyzer/inspections/imperative/imperative.d.ts +0 -35
  214. package/dist/src/analyzer/inspections/imperative/imperative.js +0 -109
  215. package/dist/src/analyzer/inspections/imperative/smells.d.ts +0 -16
  216. package/dist/src/analyzer/inspections/imperative/smells.js +0 -58
  217. package/dist/src/analyzer/inspections/logic/logic.d.ts +0 -32
  218. package/dist/src/analyzer/inspections/logic/logic.js +0 -96
  219. package/dist/src/analyzer/inspections/logic/smells.d.ts +0 -15
  220. package/dist/src/analyzer/inspections/logic/smells.js +0 -60
  221. package/dist/src/analyzer/inspections/object/object.d.ts +0 -90
  222. package/dist/src/analyzer/inspections/object/object.js +0 -321
  223. package/dist/src/analyzer/inspections/object/smells.d.ts +0 -30
  224. package/dist/src/analyzer/inspections/object/smells.js +0 -135
  225. package/dist/src/analyzer/utils.d.ts +0 -30
  226. package/dist/src/analyzer/utils.js +0 -78
  227. package/dist/src/index.d.ts +0 -4
  228. package/dist/src/index.js +0 -4
  229. package/dist/src/interpreter/components/EnvBuilder.d.ts +0 -21
  230. package/dist/src/interpreter/components/EnvBuilder.js +0 -155
  231. package/dist/src/interpreter/components/Operations.d.ts +0 -14
  232. package/dist/src/interpreter/components/Operations.js +0 -84
  233. package/dist/src/interpreter/components/PatternMatcher.d.ts +0 -73
  234. package/dist/src/interpreter/components/PatternMatcher.js +0 -358
  235. package/dist/src/interpreter/components/RuntimeContext.d.ts +0 -35
  236. package/dist/src/interpreter/components/RuntimeContext.js +0 -93
  237. package/dist/src/interpreter/components/TestRunner.d.ts +0 -19
  238. package/dist/src/interpreter/components/TestRunner.js +0 -110
  239. package/dist/src/interpreter/components/Visitor.d.ts +0 -71
  240. package/dist/src/interpreter/components/Visitor.js +0 -638
  241. package/dist/src/interpreter/components/logic/LogicEngine.d.ts +0 -29
  242. package/dist/src/interpreter/components/logic/LogicEngine.js +0 -259
  243. package/dist/src/interpreter/components/logic/LogicResolver.d.ts +0 -53
  244. package/dist/src/interpreter/components/logic/LogicResolver.js +0 -484
  245. package/dist/src/interpreter/components/logic/LogicTranslator.d.ts +0 -14
  246. package/dist/src/interpreter/components/logic/LogicTranslator.js +0 -99
  247. package/dist/src/interpreter/components/runtimes/FunctionRuntime.d.ts +0 -12
  248. package/dist/src/interpreter/components/runtimes/FunctionRuntime.js +0 -149
  249. package/dist/src/interpreter/components/runtimes/LazyRuntime.d.ts +0 -19
  250. package/dist/src/interpreter/components/runtimes/LazyRuntime.js +0 -269
  251. package/dist/src/interpreter/components/runtimes/ObjectRuntime.d.ts +0 -35
  252. package/dist/src/interpreter/components/runtimes/ObjectRuntime.js +0 -126
  253. package/dist/src/interpreter/errors.d.ts +0 -19
  254. package/dist/src/interpreter/errors.js +0 -36
  255. package/dist/src/interpreter/index.d.ts +0 -24
  256. package/dist/src/interpreter/index.js +0 -41
  257. package/dist/src/interpreter/trampoline.d.ts +0 -17
  258. package/dist/src/interpreter/trampoline.js +0 -38
  259. package/dist/src/interpreter/utils.d.ts +0 -11
  260. package/dist/src/interpreter/utils.js +0 -65
  261. package/dist/src/tester/index.d.ts +0 -25
  262. package/dist/src/tester/index.js +0 -113
  263. package/dist/src/utils/helpers.d.ts +0 -13
  264. package/dist/src/utils/helpers.js +0 -52
  265. package/src/interpreter/components/Visitor.ts +0 -1065
  266. package/src/interpreter/trampoline.ts +0 -71
@@ -1,519 +1,509 @@
1
- import {
2
- Exist,
3
- Expression,
4
- Findall,
5
- Forall,
6
- Goal,
7
- Pattern,
8
- PrimitiveValue,
9
- Query,
10
- EnvStack,
11
- LogicResult,
12
- Statement,
13
- Not,
14
- LogicConstraint,
15
- Sequence,
16
- SymbolPrimitive,
17
- VariablePattern,
18
- } from "yukigo-ast";
19
- import {
20
- solveFindallCPS,
21
- solveGoalCPS,
22
- Substitution,
23
- unify,
24
- instantiate,
25
- SuccessCont,
26
- FailureCont,
27
- } from "./LogicResolver.js";
28
- import { createStream, ExpressionEvaluator } from "../../utils.js";
29
- import { InterpreterVisitor } from "../Visitor.js";
30
- import { LogicTranslator } from "./LogicTranslator.js";
31
- import { trampoline, Continuation, Thunk } from "../../trampoline.js";
32
- import { RuntimeContext, LogicSearchMode } from "../RuntimeContext.js";
33
- import { inspect } from "util";
34
- import { PatternResolver } from "../PatternMatcher.js";
35
-
36
- export type LogicExecutable = Expression | Statement | Goal | Exist | Findall;
37
-
38
- export class LogicEngine {
39
- private translator: LogicTranslator;
40
-
41
- constructor(
42
- evaluator: ExpressionEvaluator,
43
- private context: RuntimeContext,
44
- ) {
45
- this.translator = new LogicTranslator(evaluator, this.context);
46
- }
47
-
48
- public unifyExpr(
49
- left: Expression,
50
- right: Expression,
51
- k: Continuation<PrimitiveValue>,
52
- ): Thunk<PrimitiveValue> {
53
- return this.translator.instantiateExpressionAsPattern(
54
- left,
55
- new Map(),
56
- (p1) => {
57
- return () =>
58
- this.translator.instantiateExpressionAsPattern(
59
- right,
60
- new Map(),
61
- (p2) => {
62
- return k(unify(p1, p2, new Map()) !== null);
63
- },
64
- );
65
- },
66
- );
67
- }
68
-
69
- public solveQuery(
70
- node: Query,
71
- k: Continuation<PrimitiveValue>,
72
- modeOverride?: LogicSearchMode,
73
- ): Thunk<PrimitiveValue> {
74
- const mode = modeOverride || this.context.config.outputMode || "first";
75
- if (mode === "all") {
76
- return this.collectAllResults(node.expressions, new Map(), (results) =>
77
- k(results.map((s) => this.formatLogicResult(s))),
78
- );
79
- } else if (mode === "stream") {
80
- return k(this.createLazyStream(node.expressions, new Map()));
81
- }
82
- // "first" mode
83
- return this.solveConjunction(
84
- node.expressions,
85
- new Map(),
86
- (s) => k(this.formatLogicResult(s)),
87
- () => k(false),
88
- );
89
- }
90
-
91
- public solveGoal(
92
- node: Goal,
93
- k: Continuation<PrimitiveValue>,
94
- modeOverride?: LogicSearchMode,
95
- ): Thunk<PrimitiveValue> {
96
- return this.prepareLogicTargetCPS(node, new Map(), ({ id, patterns }) => {
97
- // Goals evaluated as expressions should usually default to "first"
98
- // to avoid combinatorial explosion when they are part of a sequence.
99
- const mode = modeOverride || this.context.config.outputMode || "first";
100
- if (mode === "all") {
101
- return this.collectAllResultsForGoal(
102
- id,
103
- patterns,
104
- new Map(),
105
- (results) => k(results.map((s) => this.formatLogicResult(s))),
106
- );
107
- } else if (mode === "stream") {
108
- return k(this.createLazyStreamForGoal(id, patterns, new Map()));
109
- }
110
- return solveGoalCPS(
111
- this.context,
112
- id,
113
- patterns,
114
- (body, s, onSucc, onFail) =>
115
- this.solveConjunction(body, s, onSucc, onFail),
116
- new Map(),
117
- (s) => k(this.formatLogicResult(s)),
118
- () => k(false),
119
- );
120
- });
121
- }
122
-
123
- public solveNot(
124
- node: Not,
125
- k: Continuation<PrimitiveValue>,
126
- ): Thunk<PrimitiveValue> {
127
- return () =>
128
- this.solveConjunction(
129
- [node.expression],
130
- new Map(),
131
- () => k(false),
132
- () => k(true),
133
- );
134
- }
135
-
136
- public solveFindall(
137
- node: Findall,
138
- k: Continuation<PrimitiveValue>,
139
- ): Thunk<PrimitiveValue> {
140
- return solveFindallCPS(
141
- node,
142
- new Map(),
143
- (body, substs, onSuccess, onFailure) =>
144
- this.solveConjunction(body, substs, onSuccess, onFailure),
145
- (finalSubsts) => {
146
- const pat = finalSubsts.get((node.bag as any).name.value);
147
- const val = this.translator.patternToPrimitive(pat!);
148
- return k(val!);
149
- },
150
- () => k([]),
151
- );
152
- }
153
-
154
- public solveForall(
155
- node: Forall,
156
- k: Continuation<PrimitiveValue>,
157
- ): Thunk<any> {
158
- return this.solveConjunction(
159
- [node.condition],
160
- new Map(),
161
- (condSubsts, nextCond) => {
162
- return this.solveConjunction(
163
- [node.action],
164
- condSubsts,
165
- () => nextCond,
166
- () => k(false),
167
- );
168
- },
169
- () => k(true),
170
- );
171
- }
172
-
173
- public solveExist(
174
- node: Exist,
175
- k: Continuation<PrimitiveValue>,
176
- modeOverride?: LogicSearchMode,
177
- ): Thunk<PrimitiveValue> {
178
- return this.prepareLogicTargetCPS(node, new Map(), ({ id, patterns }) => {
179
- // Exists evaluated as expressions should usually default to "first"
180
- const mode = modeOverride || this.context.config.outputMode || "first";
181
- if (mode === "all") {
182
- return this.collectAllResultsForGoal(
183
- id,
184
- patterns,
185
- new Map(),
186
- (results) => k(results.map((s) => this.formatLogicResult(s))),
187
- );
188
- } else if (mode === "stream") {
189
- return k(this.createLazyStreamForGoal(id, patterns, new Map()));
190
- }
191
- return solveGoalCPS(
192
- this.context,
193
- id,
194
- patterns,
195
- (body, s, onSucc, onFail) =>
196
- this.solveConjunction(body, s, onSucc, onFail),
197
- new Map(),
198
- (s) => k(this.formatLogicResult(s)),
199
- () => k(false),
200
- );
201
- });
202
- }
203
-
204
- private solveConjunction(
205
- nodes: LogicExecutable[],
206
- substs: Substitution,
207
- onSuccess: SuccessCont,
208
- onFailure: FailureCont,
209
- ): Thunk<any> {
210
- if (this.context.config.debug)
211
- console.log(`[LogicEngine] Solving conjunction.`);
212
- if (nodes.length === 0) {
213
- if (this.context.config.debug)
214
- console.log(`[LogicEngine] Nothing else to solve. Success.`);
215
- return onSuccess(substs, onFailure);
216
- }
217
-
218
- const [head, ...tail] = nodes;
219
-
220
- return () =>
221
- this.solveSingle(
222
- head,
223
- substs,
224
- (newSubsts, next) => {
225
- return this.solveConjunction(tail, newSubsts, onSuccess, next);
226
- },
227
- onFailure,
228
- );
229
- }
230
-
231
- private solveSingle(
232
- node: LogicExecutable,
233
- substs: Substitution,
234
- onSuccess: SuccessCont,
235
- onFailure: FailureCont,
236
- ): Thunk<any> {
237
- if (this.isLogicGoal(node))
238
- return () => this.solveLogicGoal(node, substs, onSuccess, onFailure);
239
- return () => this.solveCondition(node, substs, onSuccess, onFailure);
240
- }
241
-
242
- private solveLogicGoal(
243
- goal: Goal | Exist | Findall | LogicConstraint | Sequence,
244
- substs: Substitution,
245
- onSuccess: SuccessCont,
246
- onFailure: FailureCont,
247
- ): Thunk<any> {
248
- if (goal instanceof LogicConstraint) {
249
- return () =>
250
- this.solveConjunction([goal.expression], substs, onSuccess, onFailure);
251
- }
252
-
253
- if (goal instanceof Sequence) {
254
- return () =>
255
- this.solveConjunction(goal.statements, substs, onSuccess, onFailure);
256
- }
257
-
258
- if (goal instanceof Findall) {
259
- return solveFindallCPS(
260
- goal,
261
- substs,
262
- (body, s, onSucc, onFail) =>
263
- this.solveConjunction(body, s, onSucc, onFail),
264
- onSuccess,
265
- onFailure,
266
- );
267
- }
268
- if (this.context.config.debug) {
269
- console.log(
270
- `[LogicEngine] Solving logic goal: ${goal.identifier.value}.`,
271
- );
272
- }
273
-
274
- return this.prepareLogicTargetCPS(goal, substs, ({ id, patterns }) => {
275
- return solveGoalCPS(
276
- this.context,
277
- id,
278
- patterns,
279
- (body, s, onSucc, onFail) =>
280
- this.solveConjunction(body, s, onSucc, onFail),
281
- substs,
282
- onSuccess,
283
- onFailure,
284
- );
285
- });
286
- }
287
-
288
- private solveCondition(
289
- expr: Expression | Statement,
290
- substs: Substitution,
291
- onSuccess: SuccessCont,
292
- onFailure: FailureCont,
293
- ): Thunk<any> {
294
- this.createLocalEnv(substs);
295
- const localEvaluator = new InterpreterVisitor(this.context);
296
-
297
- return localEvaluator.evaluate(expr, (result) => {
298
- if (result !== undefined && result !== false) {
299
- let currentSubsts = new Map(substs);
300
- for (const [name, val] of this.context.env.head) {
301
- const pat = this.translator.primitiveToPattern(val);
302
- const unified = unify(
303
- new VariablePattern(new SymbolPrimitive(name)),
304
- pat,
305
- currentSubsts,
306
- );
307
- if (unified) {
308
- currentSubsts = unified;
309
- } else {
310
- return onFailure();
311
- }
312
- }
313
- return onSuccess(currentSubsts, onFailure);
314
- }
315
- return onFailure();
316
- });
317
- }
318
-
319
- private isLogicGoal(
320
- node: LogicExecutable,
321
- ): node is Goal | Exist | Findall | LogicConstraint | Sequence {
322
- return (
323
- node instanceof Goal ||
324
- node instanceof Exist ||
325
- node instanceof Findall ||
326
- node instanceof LogicConstraint ||
327
- node instanceof Sequence
328
- );
329
- }
330
-
331
- private createLocalEnv(substs: Substitution) {
332
- this.context.pushEnv(new Map());
333
- for (const [name, pattern] of substs) {
334
- const resolvedPattern = instantiate(pattern, substs);
335
- const value = this.translator.patternToPrimitive(resolvedPattern);
336
-
337
- this.context.define(name, value);
338
-
339
- // map base name if it was standardized apart ("X_1" -> "X")
340
- const baseNameMatch = name.match(/^(.*)_\d+$/);
341
- if (baseNameMatch) {
342
- const baseName = baseNameMatch[1];
343
- if (!this.context.env.head.has(baseName)) {
344
- this.context.define(baseName, value);
345
- }
346
- }
347
- }
348
- }
349
-
350
- private prepareLogicTargetCPS(
351
- node: Goal | Exist,
352
- substs: Substitution,
353
- k: (res: { id: string; patterns: Pattern[] }) => Thunk<any>,
354
- ): Thunk<any> {
355
- const id = node.identifier.value;
356
- if (node instanceof Goal) {
357
- const patterns: Pattern[] = [];
358
- const next = (index: number): Thunk<any> => {
359
- if (index >= node.args.length) return k({ id, patterns });
360
- return this.translator.instantiateExpressionAsPattern(
361
- node.args[index],
362
- substs,
363
- (p) => {
364
- patterns.push(p);
365
- return () => next(index + 1);
366
- },
367
- );
368
- };
369
- return () => next(0);
370
- } else {
371
- const patterns = node.patterns.map((pat) => instantiate(pat, substs));
372
- return k({ id, patterns });
373
- }
374
- }
375
-
376
- private collectAllResults(
377
- nodes: LogicExecutable[],
378
- substs: Substitution,
379
- k: (results: Substitution[]) => Thunk<any>,
380
- ): Thunk<any> {
381
- const results: Substitution[] = [];
382
- return this.solveConjunction(
383
- nodes,
384
- substs,
385
- (s, next) => {
386
- if (this.context.config.debug)
387
- console.log(
388
- `[LogicEngine] Pushing { ${Array.from(s).map(([k, pat]) => `${k} -> ${pat.accept(new PatternResolver())}`)} } to results`,
389
- );
390
- results.push(s);
391
- if (this.context.config.debug)
392
- console.log(
393
- `[LogicEngine] Collected results: ${results.map((s) => `{ ${Array.from(s).map(([k, pat]) => `${k} -> ${pat.accept(new PatternResolver())}`)} }`)}`,
394
- );
395
- return next;
396
- },
397
- () => k(results),
398
- );
399
- }
400
-
401
- private collectAllResultsForGoal(
402
- id: string,
403
- patterns: Pattern[],
404
- substs: Substitution,
405
- k: (results: Substitution[]) => Thunk<any>,
406
- ): Thunk<any> {
407
- const results: Substitution[] = [];
408
- return solveGoalCPS(
409
- this.context,
410
- id,
411
- patterns,
412
- (body, s, onSucc, onFail) =>
413
- this.solveConjunction(body, s, onSucc, onFail),
414
- substs,
415
- (s, next) => {
416
- results.push(s);
417
- return next;
418
- },
419
- () => k(results),
420
- );
421
- }
422
-
423
- private createLazyStream(
424
- nodes: LogicExecutable[],
425
- substs: Substitution,
426
- ): any {
427
- let currentSubst: Substitution | null = null;
428
- let currentNext: (() => Thunk<any>) | null = null;
429
-
430
- let thunk = this.solveConjunction(
431
- nodes,
432
- substs,
433
- (s, next) => {
434
- currentSubst = s;
435
- currentNext = next;
436
- return null;
437
- },
438
- () => {
439
- currentSubst = null;
440
- return null;
441
- },
442
- );
443
-
444
- return createStream(() => {
445
- return {
446
- next: () => {
447
- trampoline(thunk);
448
- if (currentSubst) {
449
- const res = this.formatLogicResult(currentSubst);
450
- thunk = currentNext!();
451
- return { value: res, done: false };
452
- }
453
- return { value: undefined, done: true };
454
- },
455
- } as any;
456
- });
457
- }
458
-
459
- private createLazyStreamForGoal(
460
- id: string,
461
- patterns: Pattern[],
462
- substs: Substitution,
463
- ): any {
464
- let currentSubst: Substitution | null = null;
465
- let currentNext: (() => Thunk<any>) | null = null;
466
-
467
- let thunk = solveGoalCPS(
468
- this.context,
469
- id,
470
- patterns,
471
- (body, s, onSucc, onFail) =>
472
- this.solveConjunction(body, s, onSucc, onFail),
473
- substs,
474
- (s, next) => {
475
- currentSubst = s;
476
- currentNext = next;
477
- return null;
478
- },
479
- () => {
480
- currentSubst = null;
481
- return null;
482
- },
483
- );
484
-
485
- return createStream(() => {
486
- return {
487
- next: () => {
488
- trampoline(thunk);
489
- if (currentSubst) {
490
- const res = this.formatLogicResult(currentSubst);
491
- thunk = currentNext!();
492
- return { value: res, done: false };
493
- }
494
- return { value: undefined, done: true };
495
- },
496
- } as any;
497
- });
498
- }
499
-
500
- private formatLogicResult(substs: Substitution): LogicResult {
501
- const solutions = new Map<string, PrimitiveValue>();
502
- substs.forEach((pattern, key) => {
503
- const val = this.translator.patternToPrimitive(pattern);
504
- if (val !== undefined) {
505
- solutions.set(key, val);
506
-
507
- // Also map base name if it was standardized apart (e.g., "X_1" -> "X")
508
- const baseNameMatch = key.match(/^(.*)_\d+$/);
509
- if (baseNameMatch) {
510
- const baseName = baseNameMatch[1];
511
- if (!solutions.has(baseName)) {
512
- solutions.set(baseName, val);
513
- }
514
- }
515
- }
516
- });
517
- return { success: true, solutions };
518
- }
519
- }
1
+ import {
2
+ Exist,
3
+ Expression,
4
+ Findall,
5
+ Forall,
6
+ Goal,
7
+ Query,
8
+ Statement,
9
+ Not,
10
+ LogicConstraint,
11
+ Sequence,
12
+ UnifyOperation,
13
+ AssignOperation,
14
+ Assert,
15
+ Call,
16
+ If,
17
+ } from "yukigo-ast";
18
+ import { solveGoalKernel } from "./LogicResolver.js";
19
+ import { LogicTranslator } from "./LogicTranslator.js";
20
+ import { RuntimeContext } from "../RuntimeContext.js";
21
+ import {
22
+ ExecutionCommand,
23
+ StepCommand,
24
+ BindCommand,
25
+ ChoiceCommand,
26
+ NotCommand,
27
+ FindallCommand,
28
+ BacktrackCommand,
29
+ } from "../kernel/commands.js";
30
+ import { VariableTerm, CompoundTerm, ConstantTerm } from "./LogicTerm.js";
31
+ import { error, raise } from "../../utils.js";
32
+ import { YuValue } from "../../primitives/YuValue.js";
33
+ import {
34
+ Substitution,
35
+ YuArray,
36
+ LogicTerm,
37
+ LogicResult,
38
+ LogicAnswer,
39
+ isLogicTerm,
40
+ YuBoolean,
41
+ isLogicResult,
42
+ YuNil,
43
+ YuString,
44
+ } from "../../primitives/index.js";
45
+ import { Evaluator } from "../evaluators/BaseEvaluator.js";
46
+ import { InterpreterVisitor } from "../evaluators/index.js";
47
+
48
+ export type LogicExecutable =
49
+ | Expression
50
+ | Statement
51
+ | Goal
52
+ | Exist
53
+ | Findall
54
+ | Forall
55
+ | Not
56
+ | Assert
57
+ | Call
58
+ | If;
59
+
60
+ export type Scope = Map<string, VariableTerm>;
61
+
62
+ type NodeSolver = (
63
+ node: LogicExecutable,
64
+ substs: Substitution,
65
+ scope?: Scope,
66
+ ) => ExecutionCommand;
67
+
68
+ export class LogicEngine {
69
+ private translator: LogicTranslator;
70
+ private readonly dispatch: Map<string, NodeSolver>;
71
+
72
+ constructor(
73
+ evaluator: Evaluator,
74
+ private context: RuntimeContext,
75
+ ) {
76
+ if (!this.context.logicState) {
77
+ this.context.logicState = {
78
+ variableCounter: 0,
79
+ idToName: new Map<number, string>(),
80
+ };
81
+ }
82
+ this.translator = new LogicTranslator(evaluator, this.context);
83
+ this.dispatch = this.buildDispatch();
84
+ }
85
+
86
+ private buildDispatch(): Map<string, NodeSolver> {
87
+ const goalKernel = (
88
+ node: Goal | Exist,
89
+ substs: Substitution,
90
+ scope?: Scope,
91
+ ) =>
92
+ new BindCommand(
93
+ this.resolveTerms(node, substs, scope),
94
+ (termsRes: YuValue) => {
95
+ const terms = termsRes.asSequence;
96
+ if (!terms || !(terms instanceof YuArray))
97
+ return raise(error("LogicEngine", "Expected array of terms"));
98
+ return this.runKernel(node, terms.items as LogicTerm[], substs);
99
+ },
100
+ );
101
+
102
+ return new Map<string, NodeSolver>([
103
+ [
104
+ "Sequence",
105
+ (node, substs, scope) =>
106
+ this.solveConjunction((node as Sequence).statements, substs, scope),
107
+ ],
108
+ [
109
+ "LogicConstraint",
110
+ (node, substs, scope) =>
111
+ this.solveConjunction(
112
+ [(node as LogicConstraint).expression],
113
+ substs,
114
+ scope,
115
+ ),
116
+ ],
117
+ [
118
+ "UnifyOperation",
119
+ (node, substs, scope) => {
120
+ const op = node as UnifyOperation;
121
+ return new BindCommand(
122
+ this.unifyExpr(op.left, op.right, substs, scope),
123
+ (res) => {
124
+ const isMatch = res instanceof YuBoolean && res.value;
125
+ if (isMatch)
126
+ return new StepCommand(
127
+ new LogicResult([new LogicAnswer(true, substs)]),
128
+ );
129
+ return new BacktrackCommand();
130
+ },
131
+ );
132
+ },
133
+ ],
134
+ [
135
+ "AssignOperation",
136
+ (node, substs, scope) =>
137
+ this.solveAssign(node as AssignOperation, substs, scope),
138
+ ],
139
+ [
140
+ "Findall",
141
+ (node, substs, scope) =>
142
+ this.solveFindall(node as Findall, substs, scope),
143
+ ],
144
+ [
145
+ "Forall",
146
+ (node, substs, scope) =>
147
+ this.solveForall(node as Forall, substs, scope),
148
+ ],
149
+ ["Not", (node, substs, scope) => this.solveNot(node as Not, substs, scope)],
150
+ ["Goal", (node, substs, scope) => goalKernel(node as Goal, substs, scope)],
151
+ [
152
+ "Exist",
153
+ (node, substs, scope) => goalKernel(node as Exist, substs, scope),
154
+ ],
155
+ ["If", (node, substs, scope) => this.solveIf(node as If, substs, scope)],
156
+ [
157
+ "Call",
158
+ (node, substs, scope) => {
159
+ const callNode = node as Call;
160
+ return new BindCommand(
161
+ this.translator.expressionToTerm(callNode.callee, scope),
162
+ (calleeTermVal) => {
163
+ const calleeTerm = (calleeTermVal as LogicTerm)
164
+ .instantiate(substs)
165
+ .resolve(substs);
166
+ return new BindCommand(
167
+ this.resolveArgSequentially(callNode.args, substs, scope),
168
+ (argsRes) => {
169
+ const resolvedArgs = (argsRes as YuArray)
170
+ .items as LogicTerm[];
171
+ let targetPredicate: string;
172
+ let targetArgs: LogicTerm[];
173
+
174
+ if (calleeTerm.logicTermType === "Compound") {
175
+ const comp = calleeTerm as CompoundTerm;
176
+ targetPredicate = comp.functor;
177
+ targetArgs = [...comp.args, ...resolvedArgs];
178
+ } else if (calleeTerm.logicTermType === "Constant") {
179
+ const constTerm = calleeTerm as ConstantTerm;
180
+ const val = constTerm.value;
181
+ if (val instanceof YuString) {
182
+ targetPredicate = val.value;
183
+ targetArgs = resolvedArgs;
184
+ } else {
185
+ return new BacktrackCommand();
186
+ }
187
+ } else {
188
+ return new BacktrackCommand();
189
+ }
190
+
191
+ return solveGoalKernel(
192
+ this.context,
193
+ targetPredicate,
194
+ targetArgs,
195
+ (body, s, scp) => this.solveConjunction(body, s, scp),
196
+ substs,
197
+ this.translator,
198
+ );
199
+ },
200
+ );
201
+ },
202
+ );
203
+ },
204
+ ],
205
+ ]);
206
+ }
207
+
208
+ public unifyExpr(
209
+ left: Expression,
210
+ right: Expression,
211
+ substs: Substitution = new Map(),
212
+ scope?: Scope,
213
+ ): ExecutionCommand {
214
+ return new BindCommand(
215
+ this.translator.expressionToTerm(left, scope),
216
+ (leftTerm: YuValue) => {
217
+ if (!isLogicTerm(leftTerm)) return new BacktrackCommand();
218
+ return new BindCommand(
219
+ this.translator.expressionToTerm(right, scope),
220
+ (rightTerm: YuValue) => {
221
+ if (!isLogicTerm(rightTerm)) return new BacktrackCommand();
222
+
223
+ return leftTerm.unify(rightTerm, substs);
224
+ },
225
+ );
226
+ },
227
+ );
228
+ }
229
+
230
+ public solveQuery(node: Query): ExecutionCommand {
231
+ const scope: Scope = new Map();
232
+ const compiled = this.solveConjunction(node.expressions, new Map(), scope);
233
+ return this.aggregateResults(compiled, scope);
234
+ }
235
+
236
+ public solveGoalLike(
237
+ node: Goal | Exist,
238
+ outerSubsts?: Substitution,
239
+ outerScope?: Scope,
240
+ ): ExecutionCommand {
241
+ const scope: Scope = outerScope ?? new Map();
242
+ const substs: Substitution = outerSubsts ?? new Map();
243
+ return new BindCommand(
244
+ this.resolveTerms(node, substs, scope),
245
+ (termsRes: YuValue) => {
246
+ const termsSeq = termsRes.asSequence;
247
+ if (!(termsSeq instanceof YuArray)) return new BacktrackCommand();
248
+ const terms = termsSeq.items;
249
+ if (!terms.every(isLogicTerm)) return new BacktrackCommand();
250
+ return this.runKernel(node, terms, substs);
251
+ },
252
+ );
253
+ }
254
+
255
+ public solveNot(
256
+ node: Not,
257
+ substs: Substitution = new Map(),
258
+ scope: Scope = new Map(),
259
+ ): ExecutionCommand {
260
+ const clonedSubsts = new Map(substs);
261
+ const innerGoalCmd = this.solveConjunction(
262
+ [node.expression],
263
+ clonedSubsts,
264
+ scope,
265
+ );
266
+ return new NotCommand(innerGoalCmd, substs);
267
+ }
268
+
269
+ public solveFindall(
270
+ node: Findall,
271
+ substs: Substitution = new Map(),
272
+ scope: Scope = new Map(),
273
+ ): ExecutionCommand {
274
+ const clonedSubsts = new Map(substs);
275
+ const innerGoalCmd = this.solveConjunction(
276
+ [node.goal],
277
+ clonedSubsts,
278
+ scope,
279
+ );
280
+ return new FindallCommand(
281
+ node.template,
282
+ node.bag,
283
+ innerGoalCmd,
284
+ substs,
285
+ scope,
286
+ this.translator,
287
+ );
288
+ }
289
+
290
+ private solveAssign(
291
+ op: AssignOperation,
292
+ substs: Substitution,
293
+ scope?: Scope,
294
+ ): ExecutionCommand {
295
+ const localEnv = this.createLocalEnv(substs);
296
+ const isolatedContext = new RuntimeContext(this.context.config);
297
+ isolatedContext.logicState = this.context.logicState;
298
+ isolatedContext.setEnv({ head: localEnv, tail: this.context.env });
299
+ const localEvaluator = new InterpreterVisitor(isolatedContext);
300
+
301
+ return new BindCommand(localEvaluator.evaluate(op.right), (val) => {
302
+ const resultTerm = this.translator.primitiveToTerm(val);
303
+ return new BindCommand(
304
+ this.translator.expressionToTerm(op.left, scope),
305
+ (leftTerm: YuValue) => {
306
+ if (!isLogicTerm(leftTerm)) return new BacktrackCommand();
307
+ if (leftTerm.unify(resultTerm, substs)) {
308
+ return new StepCommand(
309
+ new LogicResult([new LogicAnswer(true, substs)]),
310
+ );
311
+ }
312
+ return new BacktrackCommand();
313
+ },
314
+ );
315
+ });
316
+ }
317
+
318
+ public solveForall(
319
+ node: Forall,
320
+ substs: Substitution = new Map(),
321
+ scope: Scope = new Map(),
322
+ ): ExecutionCommand {
323
+ // a forall(Cond, Action) is equivalent to \+ (Cond, \+ Action)
324
+ return this.solveNot(
325
+ new Not(new Sequence([node.condition, new Not(node.action)])),
326
+ substs,
327
+ scope,
328
+ );
329
+ }
330
+
331
+ private aggregateResults(
332
+ command: ExecutionCommand,
333
+ scope: Scope,
334
+ ): ExecutionCommand {
335
+ return new BindCommand(command, (res: YuValue) => {
336
+ if (!isLogicResult(res)) return new StepCommand(res);
337
+ const mappedAnswers = res.allAnswers.map((ans) =>
338
+ this.finalizeUserResult(ans, scope),
339
+ );
340
+ return new StepCommand(new LogicResult(mappedAnswers));
341
+ });
342
+ }
343
+
344
+ private branchSolutions(
345
+ solutions: Substitution[],
346
+ tail: LogicExecutable[],
347
+ scope?: Scope,
348
+ ): ExecutionCommand {
349
+ if (solutions.length === 0) return new BacktrackCommand();
350
+
351
+ if (solutions.length === 1) {
352
+ return this.solveConjunction(tail, solutions[0], scope);
353
+ }
354
+ return new ChoiceCommand(
355
+ solutions.map((s) => this.solveConjunction(tail, s, scope)),
356
+ );
357
+ }
358
+
359
+ public solveConjunction(
360
+ nodes: LogicExecutable[],
361
+ substs: Substitution,
362
+ scope?: Scope,
363
+ ): ExecutionCommand {
364
+ if (nodes.length === 0) {
365
+ return new StepCommand(new LogicResult([new LogicAnswer(true, substs)]));
366
+ }
367
+
368
+ const [head, ...tail] = nodes;
369
+ const solver: NodeSolver =
370
+ this.dispatch.get(head.constructor.name) ??
371
+ ((node, s) => this.solveCondition(node as Expression | Statement, s));
372
+
373
+ const currentSubst = new Map(substs);
374
+
375
+ return new BindCommand(
376
+ solver(head, currentSubst, scope),
377
+ (res: YuValue) => {
378
+ // fail if result not a LogicResult or if some conditionfail
379
+ if (!isLogicResult(res) || !res.allSuccessful())
380
+ return new BacktrackCommand();
381
+
382
+ return this.branchSolutions(res.getSuccessfulSolutions(), tail, scope);
383
+ },
384
+ );
385
+ }
386
+
387
+ private solveCondition(
388
+ expr: Expression | Statement | Assert,
389
+ substs: Substitution,
390
+ ): ExecutionCommand {
391
+ const localEnv = this.createLocalEnv(substs);
392
+ const isolatedContext = new RuntimeContext(this.context.config);
393
+ isolatedContext.logicState = this.context.logicState;
394
+ isolatedContext.setEnv({ head: localEnv, tail: this.context.env });
395
+ const localEvaluator = new InterpreterVisitor(isolatedContext);
396
+
397
+ return new BindCommand(localEvaluator.evaluate(expr), (result: YuValue) => {
398
+ // fail if result is falsy
399
+ const isTrue =
400
+ (result instanceof YuBoolean && result.value) ||
401
+ (result instanceof LogicResult && result.success) ||
402
+ result instanceof YuNil;
403
+ if (!isTrue) return new BacktrackCommand();
404
+
405
+ return new StepCommand(new LogicResult([new LogicAnswer(true, substs)]));
406
+ });
407
+ }
408
+
409
+ private createLocalEnv(substs: Substitution): Map<string, YuValue> {
410
+ const env = new Map<string, YuValue>();
411
+ for (const [id, term] of substs) {
412
+ const name = typeof id === "string" ? id : this.translator.getName(id);
413
+ if (name) env.set(name, term.instantiate(substs).toPrimitive(substs));
414
+ }
415
+ return env;
416
+ }
417
+
418
+ private finalizeUserResult(ans: LogicAnswer, scope: Scope): LogicAnswer {
419
+ const solution = ans.getSolution();
420
+
421
+ const fromScope: [string, LogicTerm][] = Array.from(scope.entries()).map(
422
+ ([name, term]) => [name, term.instantiate(solution)],
423
+ );
424
+
425
+ const fromSolution: [string, LogicTerm][] = Array.from(
426
+ solution.entries(),
427
+ ).map(([id, term]) => [
428
+ typeof id === "number" ? this.translator.getName(id)! : (id as string),
429
+ term.instantiate(solution),
430
+ ]);
431
+
432
+ const userMapped: Substitution = new Map(
433
+ [fromSolution, fromScope].flatMap((s) => [...s]),
434
+ );
435
+
436
+ return new LogicAnswer(ans.isSuccessful(), userMapped);
437
+ }
438
+
439
+ private resolveTerms(
440
+ node: Goal | Exist,
441
+ substs: Substitution,
442
+ scope?: Scope,
443
+ ): ExecutionCommand {
444
+ if (node.is(Goal))
445
+ return this.resolveArgSequentially(node.args, substs, scope);
446
+
447
+ const terms = node.patterns.map((pat) =>
448
+ this.translator.patternToTerm(pat, scope).instantiate(substs),
449
+ );
450
+ return new StepCommand(new YuArray(terms));
451
+ }
452
+ private resolveArgSequentially(
453
+ args: Expression[],
454
+ substs: Substitution,
455
+ scope?: Scope,
456
+ ): ExecutionCommand {
457
+ const terms: LogicTerm[] = [];
458
+ const next = (index: number): ExecutionCommand => {
459
+ if (index >= args.length) {
460
+ return new StepCommand(new YuArray(terms));
461
+ }
462
+ return new BindCommand(
463
+ this.translator.instantiateExpressionAsTerm(args[index], substs, scope),
464
+ (t) => {
465
+ if (isLogicTerm(t)) terms.push(t);
466
+ return next(index + 1);
467
+ },
468
+ );
469
+ };
470
+ return next(0);
471
+ }
472
+
473
+ private runKernel(
474
+ node: Goal | Exist,
475
+ terms: LogicTerm[],
476
+ substs: Substitution,
477
+ ): ExecutionCommand {
478
+ return solveGoalKernel(
479
+ this.context,
480
+ node.identifier.value,
481
+ terms,
482
+ (body, s, scp) => this.solveConjunction(body, s, scp),
483
+ substs,
484
+ this.translator,
485
+ );
486
+ }
487
+
488
+ private solveIf(
489
+ node: If,
490
+ substs: Substitution,
491
+ scope?: Scope,
492
+ ): ExecutionCommand {
493
+ return new BindCommand(
494
+ this.solveConjunction([node.condition], substs, scope),
495
+ (res: YuValue) => {
496
+ if (isLogicResult(res) && res.allSuccessful()) {
497
+ const solutions = res.getSuccessfulSolutions();
498
+ if (solutions.length === 1) {
499
+ return this.solveConjunction([node.then], solutions[0], scope);
500
+ }
501
+ return new ChoiceCommand(
502
+ solutions.map((s) => this.solveConjunction([node.then], s, scope)),
503
+ );
504
+ }
505
+ return this.solveConjunction([node.elseExpr], substs, scope);
506
+ },
507
+ );
508
+ }
509
+ }