@suss/datalog 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,205 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable by
79
+ such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do not
117
+ modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor has
163
+ been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format please. Also add information on
185
+ how to contact you by electronic and paper mail.
186
+
187
+ If the program does not interact with users remotely through a computer
188
+ network, then your name and employer's name (e.g., your institution)
189
+ is sufficient to fill in the "name of copyright owner" field. Feel
190
+ free to omit the "name of employer" line if you are in no way affiliated
191
+ with any institution.
192
+
193
+ Copyright 2026 Nimbus Cloud AI LLC
194
+
195
+ Licensed under the Apache License, Version 2.0 (the "License");
196
+ you may not use this file except in compliance with the License.
197
+ You may obtain a copy of the License at
198
+
199
+ http://www.apache.org/licenses/LICENSE-2.0
200
+
201
+ Unless required by applicable law or agreed to in writing, software
202
+ distributed under the License is distributed on an "AS IS" BASIS,
203
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
204
+ See the License for the specific language governing permissions and
205
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,84 @@
1
+ # @suss/datalog
2
+
3
+ A small semi-naïve Datalog evaluator with stratified negation. This is
4
+ the rules engine behind suss's derived program facts.
5
+
6
+ ## Why suss carries a Datalog engine
7
+
8
+ Extraction keeps meeting problems that are naturally *fixpoints*: which
9
+ functions are reachable from an entry point, what a bare `throw err`
10
+ re-throw can actually raise (the union of what everything in the `try`
11
+ block throws, transitively), how a wrapper-of-a-wrapper resolves to its
12
+ underlying route. Expressed as rules over base facts, each analysis is
13
+ a few auditable lines:
14
+
15
+ ```ts
16
+ import { Database, evaluate, lit, rule, variable as v } from "@suss/datalog";
17
+
18
+ const db = new Database();
19
+ db.add("entry", ["main"]);
20
+ db.add("calls", ["main", "helper"]);
21
+ db.add("calls", ["helper", "util"]);
22
+
23
+ evaluate(db, [
24
+ rule("reachable", [v("f")], [lit("entry", v("f"))]),
25
+ rule(
26
+ "reachable",
27
+ [v("g")],
28
+ [lit("reachable", v("f")), lit("calls", v("f"), v("g"))],
29
+ ),
30
+ ]);
31
+
32
+ db.facts("reachable"); // [["main"], ["helper"], ["util"]]
33
+ ```
34
+
35
+ Termination and soundness are the engine's job, proven once. Negation
36
+ (`notLit`) is *stratified*: a rule set with a negation cycle is a hard
37
+ error at evaluation time, the property that makes rules safe to audit
38
+ independently of any engine.
39
+
40
+ Because rules are plain data (no DSL strings, no embedded code), the
41
+ same rule set can later run on a faster external engine, and (the
42
+ longer game) analyses written against fact shapes (`calls`, `throws`,
43
+ `handles`, …) are language-independent: a second language adapter only
44
+ has to emit the same facts.
45
+
46
+ ## Design constraints
47
+
48
+ 1. **Pure TypeScript, zero dependencies.** The npm-shipped CLI cannot
49
+ require a native binary.
50
+ 2. **Rules are data.** `Rule` / `Literal` / `Term` objects, built with
51
+ `rule` / `lit` / `notLit` / `variable` / `constant`.
52
+ 3. **Sound negation only.** Stratification is checked; negated literals
53
+ must ground all variables from earlier positive literals.
54
+
55
+ ## What it does to stay quick
56
+
57
+ Semi-naïve iteration keeps per-round work proportional to newly derived
58
+ facts rather than to everything known.
59
+
60
+ Joins narrow before they scan. Once a literal has any term fixed, either
61
+ written as a constant or bound by an earlier literal, the join looks the
62
+ value up in a per-column index instead of walking the relation. A column
63
+ gets indexed the first time something asks for it and stays current
64
+ after that, so a relation nobody joins on that way carries no index.
65
+
66
+ `evaluate` picks up where it left off. Call it again with the same rules
67
+ after adding facts and it seeds from the facts you added rather than
68
+ starting the fixpoint over. Callers that interleave "add some facts, ask
69
+ a question" get this without doing anything. Positive rules are monotone,
70
+ so everything derived before still holds.
71
+
72
+ Negated rules work differently. A new fact can make a negated literal
73
+ stop matching, and the conclusion that rested on it has to go. So a
74
+ re-run with negated rules takes back what the previous pass derived and
75
+ works the answer out again from the base facts. Both paths leave the
76
+ database holding the answer for the facts it has now.
77
+
78
+ Keep the facts you add and the facts rules derive in separate relations.
79
+ Taking a conclusion back cannot tell one from the other, and the
80
+ separation is how Datalog is normally written anyway.
81
+
82
+ Extraction-scale fact sets are thousands of tuples. If that changes, the
83
+ rule data model is the stable seam and this evaluator is the replaceable
84
+ part.
package/dist/index.cjs ADDED
@@ -0,0 +1,450 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Database: () => Database,
24
+ constant: () => constant,
25
+ evaluate: () => evaluate,
26
+ lit: () => lit,
27
+ notLit: () => notLit,
28
+ rule: () => rule,
29
+ stratify: () => stratify,
30
+ variable: () => variable
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+ var variable = (name) => ({ type: "variable", name });
34
+ var constant = (value) => ({ type: "constant", value });
35
+ var lit = (relation, ...terms) => ({
36
+ relation,
37
+ terms,
38
+ negated: false
39
+ });
40
+ var notLit = (relation, ...terms) => ({
41
+ relation,
42
+ terms,
43
+ negated: true
44
+ });
45
+ var rule = (relation, terms, body) => ({ head: { relation, terms }, body });
46
+ var SEP = "\0";
47
+ var atomKey = (a) => `${typeof a === "number" ? "n" : "s"}${a}`;
48
+ var keyOf = (tuple) => tuple.map(atomKey).join(SEP);
49
+ function addToBucket(index, key, tuple) {
50
+ const bucket = index.get(key);
51
+ if (bucket === void 0) {
52
+ index.set(key, [tuple]);
53
+ } else {
54
+ bucket.push(tuple);
55
+ }
56
+ }
57
+ var Database = class {
58
+ store = /* @__PURE__ */ new Map();
59
+ relation(name) {
60
+ const existing = this.store.get(name);
61
+ if (existing !== void 0) {
62
+ return existing;
63
+ }
64
+ const created = {
65
+ keys: /* @__PURE__ */ new Set(),
66
+ tuples: [],
67
+ indexes: /* @__PURE__ */ new Map()
68
+ };
69
+ this.store.set(name, created);
70
+ return created;
71
+ }
72
+ /** Add a fact; returns true when the tuple is new. */
73
+ add(relationName, tuple) {
74
+ const relation = this.relation(relationName);
75
+ const key = keyOf(tuple);
76
+ if (relation.keys.has(key)) {
77
+ if (!isDeriving(this)) {
78
+ claimFact(this, relationName, key);
79
+ }
80
+ return false;
81
+ }
82
+ relation.keys.add(key);
83
+ relation.tuples.push(tuple);
84
+ for (const [column, index] of relation.indexes) {
85
+ const value = tuple[column];
86
+ if (value !== void 0) {
87
+ addToBucket(index, atomKey(value), tuple);
88
+ }
89
+ }
90
+ return true;
91
+ }
92
+ has(relationName, tuple) {
93
+ return this.store.get(relationName)?.keys.has(keyOf(tuple)) ?? false;
94
+ }
95
+ facts(relationName) {
96
+ return this.store.get(relationName)?.tuples ?? [];
97
+ }
98
+ /**
99
+ * The facts holding `value` at `column`. A join reaches for this
100
+ * instead of scanning the whole relation once one of its terms is
101
+ * already bound.
102
+ *
103
+ * A column is indexed the first time somebody asks for it and stays
104
+ * up to date after that, so a relation nobody joins on this way
105
+ * carries no index at all.
106
+ */
107
+ lookup(relationName, column, value) {
108
+ const relation = this.store.get(relationName);
109
+ if (relation === void 0) {
110
+ return [];
111
+ }
112
+ let index = relation.indexes.get(column);
113
+ if (index === void 0) {
114
+ index = /* @__PURE__ */ new Map();
115
+ for (const tuple of relation.tuples) {
116
+ const at = tuple[column];
117
+ if (at !== void 0) {
118
+ addToBucket(index, atomKey(at), tuple);
119
+ }
120
+ }
121
+ relation.indexes.set(column, index);
122
+ }
123
+ return index.get(atomKey(value)) ?? [];
124
+ }
125
+ /**
126
+ * Remove facts from a relation. Returns how many were actually there.
127
+ *
128
+ * Evaluation uses this to take back what it derived last time when a
129
+ * rule set uses negation, where a new fact can invalidate an old
130
+ * conclusion. Callers rarely need it.
131
+ */
132
+ retract(relationName, tuples) {
133
+ const relation = this.store.get(relationName);
134
+ if (relation === void 0) {
135
+ return 0;
136
+ }
137
+ const going = /* @__PURE__ */ new Set();
138
+ for (const tuple of tuples) {
139
+ const key = keyOf(tuple);
140
+ if (relation.keys.has(key)) {
141
+ going.add(key);
142
+ }
143
+ }
144
+ if (going.size === 0) {
145
+ return 0;
146
+ }
147
+ for (const key of going) {
148
+ relation.keys.delete(key);
149
+ }
150
+ relation.tuples = relation.tuples.filter(
151
+ (tuple) => !going.has(keyOf(tuple))
152
+ );
153
+ relation.indexes.clear();
154
+ forgetFacts(this, relationName, going);
155
+ return going.size;
156
+ }
157
+ size(relationName) {
158
+ return this.store.get(relationName)?.tuples.length ?? 0;
159
+ }
160
+ relationNames() {
161
+ return [...this.store.keys()];
162
+ }
163
+ };
164
+ function stratify(rules) {
165
+ const derived = new Set(rules.map((r) => r.head.relation));
166
+ const stratum = /* @__PURE__ */ new Map();
167
+ for (const name of derived) {
168
+ stratum.set(name, 0);
169
+ }
170
+ const bound = derived.size + 1;
171
+ let changed = true;
172
+ while (changed) {
173
+ changed = false;
174
+ for (const r of rules) {
175
+ const head = r.head.relation;
176
+ for (const body of r.body) {
177
+ if (!derived.has(body.relation)) {
178
+ continue;
179
+ }
180
+ const required = (stratum.get(body.relation) ?? 0) + (body.negated ? 1 : 0);
181
+ if ((stratum.get(head) ?? 0) < required) {
182
+ if (required > bound) {
183
+ throw new Error(
184
+ `rules are not stratifiable: negation cycle through "${head}"`
185
+ );
186
+ }
187
+ stratum.set(head, required);
188
+ changed = true;
189
+ }
190
+ }
191
+ }
192
+ }
193
+ const maxStratum = Math.max(0, ...stratum.values());
194
+ const strata = Array.from({ length: maxStratum + 1 }, () => []);
195
+ for (const r of rules) {
196
+ strata[stratum.get(r.head.relation) ?? 0].push(r);
197
+ }
198
+ return strata.filter((s) => s.length > 0);
199
+ }
200
+ function unify(literal, tuple, bindings) {
201
+ if (literal.terms.length !== tuple.length) {
202
+ return null;
203
+ }
204
+ let next = null;
205
+ for (let i = 0; i < literal.terms.length; i++) {
206
+ const term = literal.terms[i];
207
+ const value = tuple[i];
208
+ if (term.type === "constant") {
209
+ if (term.value !== value) {
210
+ return null;
211
+ }
212
+ continue;
213
+ }
214
+ const bound = (next ?? bindings).get(term.name);
215
+ if (bound === void 0) {
216
+ next = next ?? new Map(bindings);
217
+ next.set(term.name, value);
218
+ continue;
219
+ }
220
+ if (bound !== value) {
221
+ return null;
222
+ }
223
+ }
224
+ return next ?? bindings;
225
+ }
226
+ function groundNegated(literal, bindings) {
227
+ return literal.terms.map((term) => {
228
+ if (term.type === "constant") {
229
+ return term.value;
230
+ }
231
+ const bound = bindings.get(term.name);
232
+ if (bound === void 0) {
233
+ throw new Error(
234
+ `unbound variable "${term.name}" in negated literal "${literal.relation}" \u2014 negated literals may only use variables bound by earlier positive literals`
235
+ );
236
+ }
237
+ return bound;
238
+ });
239
+ }
240
+ function headTuple(head, bindings) {
241
+ return head.terms.map((term) => {
242
+ if (term.type === "constant") {
243
+ return term.value;
244
+ }
245
+ const bound = bindings.get(term.name);
246
+ if (bound === void 0) {
247
+ throw new Error(
248
+ `unbound variable "${term.name}" in head of "${head.relation}"`
249
+ );
250
+ }
251
+ return bound;
252
+ });
253
+ }
254
+ function evaluateRule(db, deltas, r, deltaIndex) {
255
+ const results = [];
256
+ const step = (literalIndex, positiveIndex, bindings) => {
257
+ if (literalIndex === r.body.length) {
258
+ results.push(headTuple(r.head, bindings));
259
+ return;
260
+ }
261
+ const literal = r.body[literalIndex];
262
+ if (literal.negated) {
263
+ if (!db.has(literal.relation, groundNegated(literal, bindings))) {
264
+ step(literalIndex + 1, positiveIndex, bindings);
265
+ }
266
+ return;
267
+ }
268
+ const source = positiveIndex === deltaIndex ? deltas.get(literal.relation) ?? [] : boundSource(db, literal, bindings);
269
+ for (const tuple of source) {
270
+ const next = unify(literal, tuple, bindings);
271
+ if (next !== null) {
272
+ step(literalIndex + 1, positiveIndex + 1, next);
273
+ }
274
+ }
275
+ };
276
+ step(0, 0, /* @__PURE__ */ new Map());
277
+ return results;
278
+ }
279
+ function boundSource(db, literal, bindings) {
280
+ for (let column = 0; column < literal.terms.length; column++) {
281
+ const term = literal.terms[column];
282
+ const value = term.type === "constant" ? term.value : bindings.get(term.name);
283
+ if (value !== void 0) {
284
+ return db.lookup(literal.relation, column, value);
285
+ }
286
+ }
287
+ return db.facts(literal.relation);
288
+ }
289
+ var evaluated = /* @__PURE__ */ new WeakMap();
290
+ var deriving = /* @__PURE__ */ new Map();
291
+ function isDeriving(db) {
292
+ return (deriving.get(db) ?? 0) > 0;
293
+ }
294
+ function statesFor(db) {
295
+ let states = evaluated.get(db);
296
+ if (states === void 0) {
297
+ states = /* @__PURE__ */ new Map();
298
+ evaluated.set(db, states);
299
+ }
300
+ return states;
301
+ }
302
+ function claimFact(db, relation, key) {
303
+ const states = evaluated.get(db);
304
+ if (states === void 0) {
305
+ return;
306
+ }
307
+ for (const state of states.values()) {
308
+ state.derived.get(relation)?.delete(key);
309
+ }
310
+ }
311
+ function forgetFacts(db, relation, keys) {
312
+ const states = evaluated.get(db);
313
+ if (states === void 0) {
314
+ return;
315
+ }
316
+ for (const state of states.values()) {
317
+ state.marks = null;
318
+ const ledger = state.derived.get(relation);
319
+ if (ledger !== void 0) {
320
+ for (const key of keys) {
321
+ ledger.delete(key);
322
+ }
323
+ }
324
+ }
325
+ }
326
+ var usesNegation = (rules) => rules.some((r) => r.body.some((l) => l.negated));
327
+ function canResume(rules, state) {
328
+ return !usesNegation(rules) && state.marks !== null;
329
+ }
330
+ function factsSince(db, marks) {
331
+ const added = /* @__PURE__ */ new Map();
332
+ for (const name of db.relationNames()) {
333
+ const all = db.facts(name);
334
+ const mark = marks.get(name) ?? 0;
335
+ if (all.length > mark) {
336
+ added.set(name, all.slice(mark));
337
+ }
338
+ }
339
+ return added;
340
+ }
341
+ function currentMarks(db) {
342
+ const marks = /* @__PURE__ */ new Map();
343
+ for (const name of db.relationNames()) {
344
+ marks.set(name, db.size(name));
345
+ }
346
+ return marks;
347
+ }
348
+ function evaluate(db, rules) {
349
+ deriving.set(db, (deriving.get(db) ?? 0) + 1);
350
+ try {
351
+ return runRules(db, rules);
352
+ } finally {
353
+ const depth = (deriving.get(db) ?? 1) - 1;
354
+ if (depth === 0) {
355
+ deriving.delete(db);
356
+ } else {
357
+ deriving.set(db, depth);
358
+ }
359
+ }
360
+ }
361
+ function runRules(db, rules) {
362
+ const signature = JSON.stringify(rules);
363
+ const states = statesFor(db);
364
+ const state = states.get(signature) ?? {
365
+ marks: null,
366
+ derived: /* @__PURE__ */ new Map()
367
+ };
368
+ states.set(signature, state);
369
+ if (usesNegation(rules)) {
370
+ for (const [relation, ledger] of state.derived) {
371
+ db.retract(relation, ledger.values());
372
+ }
373
+ state.derived.clear();
374
+ }
375
+ const derived = state.derived;
376
+ const marks = canResume(rules, state) ? state.marks : void 0;
377
+ for (const stratum of stratify(rules)) {
378
+ let delta = /* @__PURE__ */ new Map();
379
+ const derivedHere = new Set(stratum.map((r) => r.head.relation));
380
+ const record = (relation, tuple) => {
381
+ if (db.add(relation, tuple)) {
382
+ addTo(delta, relation, tuple);
383
+ let ledger = derived.get(relation);
384
+ if (ledger === void 0) {
385
+ ledger = /* @__PURE__ */ new Map();
386
+ derived.set(relation, ledger);
387
+ }
388
+ ledger.set(keyOf(tuple), tuple);
389
+ }
390
+ };
391
+ const applyDelta = (seed, derivedOnly) => {
392
+ for (const r of stratum) {
393
+ const positives = r.body.filter((l) => !l.negated);
394
+ for (let i = 0; i < positives.length; i++) {
395
+ const literal = positives[i];
396
+ if (derivedOnly && !derivedHere.has(literal.relation)) {
397
+ continue;
398
+ }
399
+ if ((seed.get(literal.relation) ?? []).length === 0) {
400
+ continue;
401
+ }
402
+ for (const tuple of evaluateRule(db, seed, r, i)) {
403
+ record(r.head.relation, tuple);
404
+ }
405
+ }
406
+ }
407
+ };
408
+ if (marks === void 0 || marks === null) {
409
+ for (const r of stratum) {
410
+ const all = /* @__PURE__ */ new Map();
411
+ for (const l of r.body) {
412
+ if (!l.negated) {
413
+ all.set(l.relation, db.facts(l.relation));
414
+ }
415
+ }
416
+ for (const tuple of evaluateRule(db, all, r, -1)) {
417
+ record(r.head.relation, tuple);
418
+ }
419
+ }
420
+ } else {
421
+ applyDelta(factsSince(db, marks), false);
422
+ }
423
+ while (delta.size > 0) {
424
+ const lastDelta = delta;
425
+ delta = /* @__PURE__ */ new Map();
426
+ applyDelta(lastDelta, true);
427
+ }
428
+ }
429
+ state.marks = currentMarks(db);
430
+ return db;
431
+ }
432
+ function addTo(buckets, relation, tuple) {
433
+ const bucket = buckets.get(relation);
434
+ if (bucket === void 0) {
435
+ buckets.set(relation, [tuple]);
436
+ } else {
437
+ bucket.push(tuple);
438
+ }
439
+ }
440
+ // Annotate the CommonJS export names for ESM import in node:
441
+ 0 && (module.exports = {
442
+ Database,
443
+ constant,
444
+ evaluate,
445
+ lit,
446
+ notLit,
447
+ rule,
448
+ stratify,
449
+ variable
450
+ });
@@ -0,0 +1,80 @@
1
+ /** Tuple values. Callers intern richer identities (AST nodes, summaries) to atoms. */
2
+ type Atom = string | number;
3
+ type Tuple = readonly Atom[];
4
+ /** A term in a rule literal: a variable to bind or a constant to match. */
5
+ type Term = {
6
+ type: "variable";
7
+ name: string;
8
+ } | {
9
+ type: "constant";
10
+ value: Atom;
11
+ };
12
+ /** Shorthand constructors — rules stay readable without a parser. */
13
+ declare const variable: (name: string) => Term;
14
+ declare const constant: (value: Atom) => Term;
15
+ interface Literal {
16
+ relation: string;
17
+ terms: Term[];
18
+ /**
19
+ * Negation-as-failure. A negated literal matches when no fact in the
20
+ * (fully evaluated, lower-stratum) relation unifies with it. Every
21
+ * variable in a negated literal must be bound by a positive literal
22
+ * earlier in the body.
23
+ */
24
+ negated: boolean;
25
+ }
26
+ declare const lit: (relation: string, ...terms: Term[]) => Literal;
27
+ declare const notLit: (relation: string, ...terms: Term[]) => Literal;
28
+ interface Rule {
29
+ head: {
30
+ relation: string;
31
+ terms: Term[];
32
+ };
33
+ body: Literal[];
34
+ }
35
+ declare const rule: (relation: string, terms: Term[], body: Literal[]) => Rule;
36
+ /** A set of facts per relation, with O(1) membership. */
37
+ declare class Database {
38
+ private readonly store;
39
+ private relation;
40
+ /** Add a fact; returns true when the tuple is new. */
41
+ add(relationName: string, tuple: Tuple): boolean;
42
+ has(relationName: string, tuple: Tuple): boolean;
43
+ facts(relationName: string): readonly Tuple[];
44
+ /**
45
+ * The facts holding `value` at `column`. A join reaches for this
46
+ * instead of scanning the whole relation once one of its terms is
47
+ * already bound.
48
+ *
49
+ * A column is indexed the first time somebody asks for it and stays
50
+ * up to date after that, so a relation nobody joins on this way
51
+ * carries no index at all.
52
+ */
53
+ lookup(relationName: string, column: number, value: Atom): readonly Tuple[];
54
+ /**
55
+ * Remove facts from a relation. Returns how many were actually there.
56
+ *
57
+ * Evaluation uses this to take back what it derived last time when a
58
+ * rule set uses negation, where a new fact can invalidate an old
59
+ * conclusion. Callers rarely need it.
60
+ */
61
+ retract(relationName: string, tuples: Iterable<Tuple>): number;
62
+ size(relationName: string): number;
63
+ relationNames(): string[];
64
+ }
65
+ /**
66
+ * Assign each derived relation a stratum such that positive
67
+ * dependencies never decrease the stratum and negative dependencies
68
+ * strictly increase it. Iterates to fixpoint; a stratum exceeding the
69
+ * relation count means a negation cycle — not stratifiable, hard error.
70
+ */
71
+ declare function stratify(rules: Rule[]): Rule[][];
72
+ /**
73
+ * Evaluate `rules` over `db` to fixpoint, adding derived facts in
74
+ * place. Rules are stratified first; within a stratum, semi-naïve
75
+ * iteration joins each rule against the last round's delta so work is
76
+ * proportional to new facts, not all facts.
77
+ */
78
+ declare function evaluate(db: Database, rules: Rule[]): Database;
79
+
80
+ export { type Atom, Database, type Literal, type Rule, type Term, type Tuple, constant, evaluate, lit, notLit, rule, stratify, variable };
@@ -0,0 +1,80 @@
1
+ /** Tuple values. Callers intern richer identities (AST nodes, summaries) to atoms. */
2
+ type Atom = string | number;
3
+ type Tuple = readonly Atom[];
4
+ /** A term in a rule literal: a variable to bind or a constant to match. */
5
+ type Term = {
6
+ type: "variable";
7
+ name: string;
8
+ } | {
9
+ type: "constant";
10
+ value: Atom;
11
+ };
12
+ /** Shorthand constructors — rules stay readable without a parser. */
13
+ declare const variable: (name: string) => Term;
14
+ declare const constant: (value: Atom) => Term;
15
+ interface Literal {
16
+ relation: string;
17
+ terms: Term[];
18
+ /**
19
+ * Negation-as-failure. A negated literal matches when no fact in the
20
+ * (fully evaluated, lower-stratum) relation unifies with it. Every
21
+ * variable in a negated literal must be bound by a positive literal
22
+ * earlier in the body.
23
+ */
24
+ negated: boolean;
25
+ }
26
+ declare const lit: (relation: string, ...terms: Term[]) => Literal;
27
+ declare const notLit: (relation: string, ...terms: Term[]) => Literal;
28
+ interface Rule {
29
+ head: {
30
+ relation: string;
31
+ terms: Term[];
32
+ };
33
+ body: Literal[];
34
+ }
35
+ declare const rule: (relation: string, terms: Term[], body: Literal[]) => Rule;
36
+ /** A set of facts per relation, with O(1) membership. */
37
+ declare class Database {
38
+ private readonly store;
39
+ private relation;
40
+ /** Add a fact; returns true when the tuple is new. */
41
+ add(relationName: string, tuple: Tuple): boolean;
42
+ has(relationName: string, tuple: Tuple): boolean;
43
+ facts(relationName: string): readonly Tuple[];
44
+ /**
45
+ * The facts holding `value` at `column`. A join reaches for this
46
+ * instead of scanning the whole relation once one of its terms is
47
+ * already bound.
48
+ *
49
+ * A column is indexed the first time somebody asks for it and stays
50
+ * up to date after that, so a relation nobody joins on this way
51
+ * carries no index at all.
52
+ */
53
+ lookup(relationName: string, column: number, value: Atom): readonly Tuple[];
54
+ /**
55
+ * Remove facts from a relation. Returns how many were actually there.
56
+ *
57
+ * Evaluation uses this to take back what it derived last time when a
58
+ * rule set uses negation, where a new fact can invalidate an old
59
+ * conclusion. Callers rarely need it.
60
+ */
61
+ retract(relationName: string, tuples: Iterable<Tuple>): number;
62
+ size(relationName: string): number;
63
+ relationNames(): string[];
64
+ }
65
+ /**
66
+ * Assign each derived relation a stratum such that positive
67
+ * dependencies never decrease the stratum and negative dependencies
68
+ * strictly increase it. Iterates to fixpoint; a stratum exceeding the
69
+ * relation count means a negation cycle — not stratifiable, hard error.
70
+ */
71
+ declare function stratify(rules: Rule[]): Rule[][];
72
+ /**
73
+ * Evaluate `rules` over `db` to fixpoint, adding derived facts in
74
+ * place. Rules are stratified first; within a stratum, semi-naïve
75
+ * iteration joins each rule against the last round's delta so work is
76
+ * proportional to new facts, not all facts.
77
+ */
78
+ declare function evaluate(db: Database, rules: Rule[]): Database;
79
+
80
+ export { type Atom, Database, type Literal, type Rule, type Term, type Tuple, constant, evaluate, lit, notLit, rule, stratify, variable };
package/dist/index.js ADDED
@@ -0,0 +1,418 @@
1
+ // src/index.ts
2
+ var variable = (name) => ({ type: "variable", name });
3
+ var constant = (value) => ({ type: "constant", value });
4
+ var lit = (relation, ...terms) => ({
5
+ relation,
6
+ terms,
7
+ negated: false
8
+ });
9
+ var notLit = (relation, ...terms) => ({
10
+ relation,
11
+ terms,
12
+ negated: true
13
+ });
14
+ var rule = (relation, terms, body) => ({ head: { relation, terms }, body });
15
+ var SEP = "\0";
16
+ var atomKey = (a) => `${typeof a === "number" ? "n" : "s"}${a}`;
17
+ var keyOf = (tuple) => tuple.map(atomKey).join(SEP);
18
+ function addToBucket(index, key, tuple) {
19
+ const bucket = index.get(key);
20
+ if (bucket === void 0) {
21
+ index.set(key, [tuple]);
22
+ } else {
23
+ bucket.push(tuple);
24
+ }
25
+ }
26
+ var Database = class {
27
+ store = /* @__PURE__ */ new Map();
28
+ relation(name) {
29
+ const existing = this.store.get(name);
30
+ if (existing !== void 0) {
31
+ return existing;
32
+ }
33
+ const created = {
34
+ keys: /* @__PURE__ */ new Set(),
35
+ tuples: [],
36
+ indexes: /* @__PURE__ */ new Map()
37
+ };
38
+ this.store.set(name, created);
39
+ return created;
40
+ }
41
+ /** Add a fact; returns true when the tuple is new. */
42
+ add(relationName, tuple) {
43
+ const relation = this.relation(relationName);
44
+ const key = keyOf(tuple);
45
+ if (relation.keys.has(key)) {
46
+ if (!isDeriving(this)) {
47
+ claimFact(this, relationName, key);
48
+ }
49
+ return false;
50
+ }
51
+ relation.keys.add(key);
52
+ relation.tuples.push(tuple);
53
+ for (const [column, index] of relation.indexes) {
54
+ const value = tuple[column];
55
+ if (value !== void 0) {
56
+ addToBucket(index, atomKey(value), tuple);
57
+ }
58
+ }
59
+ return true;
60
+ }
61
+ has(relationName, tuple) {
62
+ return this.store.get(relationName)?.keys.has(keyOf(tuple)) ?? false;
63
+ }
64
+ facts(relationName) {
65
+ return this.store.get(relationName)?.tuples ?? [];
66
+ }
67
+ /**
68
+ * The facts holding `value` at `column`. A join reaches for this
69
+ * instead of scanning the whole relation once one of its terms is
70
+ * already bound.
71
+ *
72
+ * A column is indexed the first time somebody asks for it and stays
73
+ * up to date after that, so a relation nobody joins on this way
74
+ * carries no index at all.
75
+ */
76
+ lookup(relationName, column, value) {
77
+ const relation = this.store.get(relationName);
78
+ if (relation === void 0) {
79
+ return [];
80
+ }
81
+ let index = relation.indexes.get(column);
82
+ if (index === void 0) {
83
+ index = /* @__PURE__ */ new Map();
84
+ for (const tuple of relation.tuples) {
85
+ const at = tuple[column];
86
+ if (at !== void 0) {
87
+ addToBucket(index, atomKey(at), tuple);
88
+ }
89
+ }
90
+ relation.indexes.set(column, index);
91
+ }
92
+ return index.get(atomKey(value)) ?? [];
93
+ }
94
+ /**
95
+ * Remove facts from a relation. Returns how many were actually there.
96
+ *
97
+ * Evaluation uses this to take back what it derived last time when a
98
+ * rule set uses negation, where a new fact can invalidate an old
99
+ * conclusion. Callers rarely need it.
100
+ */
101
+ retract(relationName, tuples) {
102
+ const relation = this.store.get(relationName);
103
+ if (relation === void 0) {
104
+ return 0;
105
+ }
106
+ const going = /* @__PURE__ */ new Set();
107
+ for (const tuple of tuples) {
108
+ const key = keyOf(tuple);
109
+ if (relation.keys.has(key)) {
110
+ going.add(key);
111
+ }
112
+ }
113
+ if (going.size === 0) {
114
+ return 0;
115
+ }
116
+ for (const key of going) {
117
+ relation.keys.delete(key);
118
+ }
119
+ relation.tuples = relation.tuples.filter(
120
+ (tuple) => !going.has(keyOf(tuple))
121
+ );
122
+ relation.indexes.clear();
123
+ forgetFacts(this, relationName, going);
124
+ return going.size;
125
+ }
126
+ size(relationName) {
127
+ return this.store.get(relationName)?.tuples.length ?? 0;
128
+ }
129
+ relationNames() {
130
+ return [...this.store.keys()];
131
+ }
132
+ };
133
+ function stratify(rules) {
134
+ const derived = new Set(rules.map((r) => r.head.relation));
135
+ const stratum = /* @__PURE__ */ new Map();
136
+ for (const name of derived) {
137
+ stratum.set(name, 0);
138
+ }
139
+ const bound = derived.size + 1;
140
+ let changed = true;
141
+ while (changed) {
142
+ changed = false;
143
+ for (const r of rules) {
144
+ const head = r.head.relation;
145
+ for (const body of r.body) {
146
+ if (!derived.has(body.relation)) {
147
+ continue;
148
+ }
149
+ const required = (stratum.get(body.relation) ?? 0) + (body.negated ? 1 : 0);
150
+ if ((stratum.get(head) ?? 0) < required) {
151
+ if (required > bound) {
152
+ throw new Error(
153
+ `rules are not stratifiable: negation cycle through "${head}"`
154
+ );
155
+ }
156
+ stratum.set(head, required);
157
+ changed = true;
158
+ }
159
+ }
160
+ }
161
+ }
162
+ const maxStratum = Math.max(0, ...stratum.values());
163
+ const strata = Array.from({ length: maxStratum + 1 }, () => []);
164
+ for (const r of rules) {
165
+ strata[stratum.get(r.head.relation) ?? 0].push(r);
166
+ }
167
+ return strata.filter((s) => s.length > 0);
168
+ }
169
+ function unify(literal, tuple, bindings) {
170
+ if (literal.terms.length !== tuple.length) {
171
+ return null;
172
+ }
173
+ let next = null;
174
+ for (let i = 0; i < literal.terms.length; i++) {
175
+ const term = literal.terms[i];
176
+ const value = tuple[i];
177
+ if (term.type === "constant") {
178
+ if (term.value !== value) {
179
+ return null;
180
+ }
181
+ continue;
182
+ }
183
+ const bound = (next ?? bindings).get(term.name);
184
+ if (bound === void 0) {
185
+ next = next ?? new Map(bindings);
186
+ next.set(term.name, value);
187
+ continue;
188
+ }
189
+ if (bound !== value) {
190
+ return null;
191
+ }
192
+ }
193
+ return next ?? bindings;
194
+ }
195
+ function groundNegated(literal, bindings) {
196
+ return literal.terms.map((term) => {
197
+ if (term.type === "constant") {
198
+ return term.value;
199
+ }
200
+ const bound = bindings.get(term.name);
201
+ if (bound === void 0) {
202
+ throw new Error(
203
+ `unbound variable "${term.name}" in negated literal "${literal.relation}" \u2014 negated literals may only use variables bound by earlier positive literals`
204
+ );
205
+ }
206
+ return bound;
207
+ });
208
+ }
209
+ function headTuple(head, bindings) {
210
+ return head.terms.map((term) => {
211
+ if (term.type === "constant") {
212
+ return term.value;
213
+ }
214
+ const bound = bindings.get(term.name);
215
+ if (bound === void 0) {
216
+ throw new Error(
217
+ `unbound variable "${term.name}" in head of "${head.relation}"`
218
+ );
219
+ }
220
+ return bound;
221
+ });
222
+ }
223
+ function evaluateRule(db, deltas, r, deltaIndex) {
224
+ const results = [];
225
+ const step = (literalIndex, positiveIndex, bindings) => {
226
+ if (literalIndex === r.body.length) {
227
+ results.push(headTuple(r.head, bindings));
228
+ return;
229
+ }
230
+ const literal = r.body[literalIndex];
231
+ if (literal.negated) {
232
+ if (!db.has(literal.relation, groundNegated(literal, bindings))) {
233
+ step(literalIndex + 1, positiveIndex, bindings);
234
+ }
235
+ return;
236
+ }
237
+ const source = positiveIndex === deltaIndex ? deltas.get(literal.relation) ?? [] : boundSource(db, literal, bindings);
238
+ for (const tuple of source) {
239
+ const next = unify(literal, tuple, bindings);
240
+ if (next !== null) {
241
+ step(literalIndex + 1, positiveIndex + 1, next);
242
+ }
243
+ }
244
+ };
245
+ step(0, 0, /* @__PURE__ */ new Map());
246
+ return results;
247
+ }
248
+ function boundSource(db, literal, bindings) {
249
+ for (let column = 0; column < literal.terms.length; column++) {
250
+ const term = literal.terms[column];
251
+ const value = term.type === "constant" ? term.value : bindings.get(term.name);
252
+ if (value !== void 0) {
253
+ return db.lookup(literal.relation, column, value);
254
+ }
255
+ }
256
+ return db.facts(literal.relation);
257
+ }
258
+ var evaluated = /* @__PURE__ */ new WeakMap();
259
+ var deriving = /* @__PURE__ */ new Map();
260
+ function isDeriving(db) {
261
+ return (deriving.get(db) ?? 0) > 0;
262
+ }
263
+ function statesFor(db) {
264
+ let states = evaluated.get(db);
265
+ if (states === void 0) {
266
+ states = /* @__PURE__ */ new Map();
267
+ evaluated.set(db, states);
268
+ }
269
+ return states;
270
+ }
271
+ function claimFact(db, relation, key) {
272
+ const states = evaluated.get(db);
273
+ if (states === void 0) {
274
+ return;
275
+ }
276
+ for (const state of states.values()) {
277
+ state.derived.get(relation)?.delete(key);
278
+ }
279
+ }
280
+ function forgetFacts(db, relation, keys) {
281
+ const states = evaluated.get(db);
282
+ if (states === void 0) {
283
+ return;
284
+ }
285
+ for (const state of states.values()) {
286
+ state.marks = null;
287
+ const ledger = state.derived.get(relation);
288
+ if (ledger !== void 0) {
289
+ for (const key of keys) {
290
+ ledger.delete(key);
291
+ }
292
+ }
293
+ }
294
+ }
295
+ var usesNegation = (rules) => rules.some((r) => r.body.some((l) => l.negated));
296
+ function canResume(rules, state) {
297
+ return !usesNegation(rules) && state.marks !== null;
298
+ }
299
+ function factsSince(db, marks) {
300
+ const added = /* @__PURE__ */ new Map();
301
+ for (const name of db.relationNames()) {
302
+ const all = db.facts(name);
303
+ const mark = marks.get(name) ?? 0;
304
+ if (all.length > mark) {
305
+ added.set(name, all.slice(mark));
306
+ }
307
+ }
308
+ return added;
309
+ }
310
+ function currentMarks(db) {
311
+ const marks = /* @__PURE__ */ new Map();
312
+ for (const name of db.relationNames()) {
313
+ marks.set(name, db.size(name));
314
+ }
315
+ return marks;
316
+ }
317
+ function evaluate(db, rules) {
318
+ deriving.set(db, (deriving.get(db) ?? 0) + 1);
319
+ try {
320
+ return runRules(db, rules);
321
+ } finally {
322
+ const depth = (deriving.get(db) ?? 1) - 1;
323
+ if (depth === 0) {
324
+ deriving.delete(db);
325
+ } else {
326
+ deriving.set(db, depth);
327
+ }
328
+ }
329
+ }
330
+ function runRules(db, rules) {
331
+ const signature = JSON.stringify(rules);
332
+ const states = statesFor(db);
333
+ const state = states.get(signature) ?? {
334
+ marks: null,
335
+ derived: /* @__PURE__ */ new Map()
336
+ };
337
+ states.set(signature, state);
338
+ if (usesNegation(rules)) {
339
+ for (const [relation, ledger] of state.derived) {
340
+ db.retract(relation, ledger.values());
341
+ }
342
+ state.derived.clear();
343
+ }
344
+ const derived = state.derived;
345
+ const marks = canResume(rules, state) ? state.marks : void 0;
346
+ for (const stratum of stratify(rules)) {
347
+ let delta = /* @__PURE__ */ new Map();
348
+ const derivedHere = new Set(stratum.map((r) => r.head.relation));
349
+ const record = (relation, tuple) => {
350
+ if (db.add(relation, tuple)) {
351
+ addTo(delta, relation, tuple);
352
+ let ledger = derived.get(relation);
353
+ if (ledger === void 0) {
354
+ ledger = /* @__PURE__ */ new Map();
355
+ derived.set(relation, ledger);
356
+ }
357
+ ledger.set(keyOf(tuple), tuple);
358
+ }
359
+ };
360
+ const applyDelta = (seed, derivedOnly) => {
361
+ for (const r of stratum) {
362
+ const positives = r.body.filter((l) => !l.negated);
363
+ for (let i = 0; i < positives.length; i++) {
364
+ const literal = positives[i];
365
+ if (derivedOnly && !derivedHere.has(literal.relation)) {
366
+ continue;
367
+ }
368
+ if ((seed.get(literal.relation) ?? []).length === 0) {
369
+ continue;
370
+ }
371
+ for (const tuple of evaluateRule(db, seed, r, i)) {
372
+ record(r.head.relation, tuple);
373
+ }
374
+ }
375
+ }
376
+ };
377
+ if (marks === void 0 || marks === null) {
378
+ for (const r of stratum) {
379
+ const all = /* @__PURE__ */ new Map();
380
+ for (const l of r.body) {
381
+ if (!l.negated) {
382
+ all.set(l.relation, db.facts(l.relation));
383
+ }
384
+ }
385
+ for (const tuple of evaluateRule(db, all, r, -1)) {
386
+ record(r.head.relation, tuple);
387
+ }
388
+ }
389
+ } else {
390
+ applyDelta(factsSince(db, marks), false);
391
+ }
392
+ while (delta.size > 0) {
393
+ const lastDelta = delta;
394
+ delta = /* @__PURE__ */ new Map();
395
+ applyDelta(lastDelta, true);
396
+ }
397
+ }
398
+ state.marks = currentMarks(db);
399
+ return db;
400
+ }
401
+ function addTo(buckets, relation, tuple) {
402
+ const bucket = buckets.get(relation);
403
+ if (bucket === void 0) {
404
+ buckets.set(relation, [tuple]);
405
+ } else {
406
+ bucket.push(tuple);
407
+ }
408
+ }
409
+ export {
410
+ Database,
411
+ constant,
412
+ evaluate,
413
+ lit,
414
+ notLit,
415
+ rule,
416
+ stratify,
417
+ variable
418
+ };
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@suss/datalog",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "A small semi-naïve Datalog evaluator with stratified negation — the rules engine behind suss's derived program facts.",
6
+ "keywords": [
7
+ "suss",
8
+ "datalog",
9
+ "fixpoint",
10
+ "static-analysis"
11
+ ],
12
+ "license": "Apache-2.0",
13
+ "author": "Nimbus Cloud AI LLC",
14
+ "homepage": "https://github.com/nimbuscloud-ai/suss/tree/main/packages/datalog#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/nimbuscloud-ai/suss.git",
18
+ "directory": "packages/datalog"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/nimbuscloud-ai/suss/issues"
22
+ },
23
+ "main": "./dist/index.cjs",
24
+ "module": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js",
30
+ "require": "./dist/index.cjs"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "scripts": {
39
+ "build": "tsup",
40
+ "test": "vitest run",
41
+ "test:coverage": "vitest run --coverage",
42
+ "lint": "biome check .",
43
+ "lint:fix": "biome check --write .",
44
+ "typecheck": "tsc --noEmit"
45
+ },
46
+ "devDependencies": {
47
+ "fast-check": "^3.23.1",
48
+ "tsup": "*",
49
+ "typescript": "*",
50
+ "vitest": "*"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ }
55
+ }