34 static bool validate(
const std::vector<DependencyEdge>& edges, std::string& error_msg) {
35 std::unordered_set<std::string> predicates;
36 std::unordered_map<std::string, std::vector<std::pair<std::string, bool>>> adj;
38 for (
const auto& edge : edges) {
39 predicates.insert(edge.from);
40 predicates.insert(edge.to);
41 adj[edge.from].push_back({edge.to, edge.is_negated});
44 std::unordered_set<std::string> in_stack;
45 std::vector<std::pair<std::string, bool>> path;
46 std::unordered_set<std::string> memo_safe;
48 for (
const auto& pred : predicates) {
49 if (memo_safe.find(pred) == memo_safe.end()) {
50 bool reaches_stack =
false;
51 if (!dfs_check(pred, adj, in_stack, path, memo_safe, error_msg, reaches_stack, 0)) {
59 static bool is_recursive(
const std::string& predicate,
const std::vector<DependencyEdge>& edges) {
60 std::unordered_map<std::string, std::vector<std::string>> adj;
61 for (
const auto& e : edges) {
63 adj[e.from].push_back(e.to);
66 std::unordered_set<std::string> visited;
67 std::vector<std::string> stack;
68 auto it = adj.find(predicate);
69 if (it != adj.end()) {
72 while (!stack.empty()) {
73 std::string cur = stack.back();
75 if (cur == predicate) {
78 if (visited.insert(cur).second) {
79 auto nit = adj.find(cur);
80 if (nit != adj.end()) {
81 for (
const auto& nxt : nit->second) {
91 static bool dfs_check(
92 const std::string& current,
93 const std::unordered_map<std::string, std::vector<std::pair<std::string, bool>>>& adj,
94 std::unordered_set<std::string>& in_stack,
95 std::vector<std::pair<std::string, bool>>& path,
96 std::unordered_set<std::string>& memo_safe,
97 std::string& error_msg,
98 bool& out_reaches_stack,
102 error_msg =
"Datalog stratification recursion depth exceeded limit 256";
106 in_stack.insert(current);
107 bool reaches_stack =
false;
109 auto it = adj.find(current);
110 if (it != adj.end()) {
111 for (
const auto& edge : it->second) {
112 const std::string& next = edge.first;
113 bool is_negated = edge.second;
114 path.push_back({next, is_negated});
116 if (in_stack.find(next) != in_stack.end()) {
117 reaches_stack =
true;
118 auto pos_it = std::find_if(path.begin(), path.end(), [&](
const auto& p) { return p.first == next; });
119 if (pos_it != path.end()) {
120 bool has_negation =
false;
121 for (
auto iter = pos_it; iter != path.end(); ++iter) {
122 if (iter->second) { has_negation =
true;
break; }
125 error_msg =
"Non-stratifiable negation cycle detected involving predicate: " + next;
129 }
else if (memo_safe.find(next) == memo_safe.end()) {
130 bool child_reaches_stack =
false;
131 if (!dfs_check(next, adj, in_stack, path, memo_safe, error_msg, child_reaches_stack, depth + 1)) {
134 if (child_reaches_stack) {
135 reaches_stack =
true;
142 in_stack.erase(current);
143 out_reaches_stack = reaches_stack;
144 if (!reaches_stack) {
145 memo_safe.insert(current);
215 static std::shared_ptr<impulse::compiler::ScmProgram>
parse(
const std::string& source) {
216 return compile_internal(source, {}, {}, 0, {});
220 const std::string& source,
221 const std::vector<uint64_t>& seeds)
223 return compile_internal(source, seeds, {}, 0, {});
227 const std::string& source,
228 const std::vector<uint64_t>& node_group_pairs,
231 return compile_internal(source, {}, node_group_pairs, num_groups, {});
235 const std::string& source,
236 const std::vector<uint64_t>& allow_seeds,
237 const std::vector<uint64_t>& deny_seeds)
239 size_t half = std::max(allow_seeds.size(), deny_seeds.size());
240 if (half == 0 || half > 32) {
241 throw std::invalid_argument(
"Allow/deny split requires between 1 and 32 lanes per half");
243 std::vector<uint64_t> combined;
244 combined.reserve(half * 2);
245 for (
size_t i = 0; i < half; ++i) {
246 combined.push_back(i < allow_seeds.size() ? allow_seeds[i] : 0ULL);
248 for (
size_t i = 0; i < half; ++i) {
249 combined.push_back(i < deny_seeds.size() ? deny_seeds[i] : 0ULL);
251 auto base = compile_internal(source, combined, {}, 0, {});
252 std::vector<impulse::compiler::AstPtr> steps;
253 for (
const auto& st : base->steps) {
259 return std::make_shared<impulse::compiler::ScmProgram>(std::move(steps));
263 static std::string trim_str(
const std::string& s) {
264 size_t a = s.find_first_not_of(
" \t\r\n");
265 if (a == std::string::npos)
return "";
266 size_t b = s.find_last_not_of(
" \t\r\n");
267 return s.substr(a, b - a + 1);
270 static std::string strip_inline_comment(
const std::string& line) {
271 std::string out = line;
272 size_t slash = out.find(
"//");
273 if (slash != std::string::npos) out = out.substr(0, slash);
274 size_t pct = out.find(
'%');
275 if (pct != std::string::npos) out = out.substr(0, pct);
279 static std::vector<std::string> split_top_level_atoms(
const std::string& body) {
280 std::vector<std::string> out;
283 for (
size_t i = 0; i < body.size(); ++i) {
285 if (c ==
'(') depth++;
286 else if (c ==
')') depth = std::max(0, depth - 1);
287 else if (c ==
',' && depth == 0) {
288 std::string token = trim_str(body.substr(start, i - start));
289 if (!token.empty()) out.push_back(token);
293 if (start < body.size()) {
294 std::string token = trim_str(body.substr(start));
295 if (!token.empty()) out.push_back(token);
300 static ParsedAtom parse_atom(
const std::string& raw) {
301 std::string t = trim_str(raw);
303 if (t.starts_with(
"!")) {
305 t = trim_str(t.substr(1));
306 }
else if (t.starts_with(
"not ") || t.starts_with(
"not\t") || t.starts_with(
"NOT ") || t.starts_with(
"NOT\t")) {
308 t = trim_str(t.substr(4));
312 if (t.starts_with(
"^") || t.starts_with(
"~")) {
314 t = trim_str(t.substr(1));
317 size_t lp = t.find(
'(');
318 size_t rp = t.rfind(
')');
320 std::vector<std::string> args;
321 if (lp != std::string::npos) {
322 pred = trim_str(t.substr(0, lp));
323 if (rp != std::string::npos && rp > lp + 1) {
324 std::string arg_str = t.substr(lp + 1, rp - lp - 1);
325 std::istringstream as(arg_str);
327 while (std::getline(as, tok,
',')) {
328 std::string clean = trim_str(tok);
329 if (!clean.empty()) args.push_back(clean);
335 pred.erase(std::remove_if(pred.begin(), pred.end(), ::isspace), pred.end());
336 return {pred, args, neg, rev};
339 static bool try_parse_u64(
const std::string& tok, uint64_t& out) {
340 std::string clean = trim_str(tok);
341 if (clean.empty())
return false;
342 for (
char c : clean) {
343 if (!std::isdigit(
static_cast<unsigned char>(c)))
return false;
345 out = std::stoull(clean);
349 static void parse_fact_or_directive(
350 const std::string& line,
351 std::vector<uint64_t>& seeds,
352 std::vector<uint64_t>& group_pairs,
353 std::vector<uint64_t>& deny_nodes,
354 uint16_t& allow_deny_half)
356 std::string s = line;
357 while (!s.empty() && (s.back() ==
'.' || std::isspace(
static_cast<unsigned char>(s.back())))) {
360 if (!s.empty() && s.front() ==
'.') {
361 s = trim_str(s.substr(1));
363 if (s.empty())
return;
366 std::string lower_pred = atom.predicate;
367 std::transform(lower_pred.begin(), lower_pred.end(), lower_pred.begin(),
368 [](
unsigned char c) { return static_cast<char>(std::tolower(c)); });
370 if (lower_pred ==
"seed" || lower_pred ==
"seeds") {
371 for (
const auto& a : atom.args) {
373 if (try_parse_u64(a, v)) seeds.push_back(v);
375 }
else if (lower_pred ==
"group" || lower_pred ==
"groups") {
376 if (atom.args.size() >= 2) {
377 uint64_t u = 0, g = 0;
378 if (try_parse_u64(atom.args[0], u) && try_parse_u64(atom.args[1], g)) {
379 group_pairs.push_back(u);
380 group_pairs.push_back(g);
383 }
else if (lower_pred ==
"denied" || lower_pred ==
"deny") {
384 for (
const auto& a : atom.args) {
386 if (try_parse_u64(a, v)) deny_nodes.push_back(v);
388 }
else if (lower_pred ==
"rebac_allow_deny" || lower_pred ==
"allow_deny_split") {
389 if (!atom.args.empty()) {
391 if (try_parse_u64(atom.args[0], v)) allow_deny_half =
static_cast<uint16_t
>(v);
396 static std::shared_ptr<impulse::compiler::ScmProgram> compile_internal(
397 const std::string& source,
398 const std::vector<uint64_t>& explicit_seeds,
399 const std::vector<uint64_t>& explicit_group_pairs,
400 uint16_t explicit_num_groups,
401 const std::vector<uint64_t>& explicit_deny_nodes)
403 std::vector<uint64_t> seeds = explicit_seeds;
404 std::vector<uint64_t> group_pairs = explicit_group_pairs;
405 std::vector<uint64_t> deny_nodes = explicit_deny_nodes;
406 uint16_t allow_deny_half = 0;
408 std::vector<ParsedRule> rules;
409 std::vector<DependencyEdge> edges;
411 std::istringstream stream(source);
412 std::string raw_line;
413 while (std::getline(stream, raw_line)) {
414 std::string trimmed = trim_str(strip_inline_comment(raw_line));
415 if (trimmed.empty() || trimmed.starts_with(
"//") || trimmed.starts_with(
"%") ||
416 trimmed.starts_with(
"#") || trimmed.starts_with(
".decl") || trimmed.starts_with(
"?-")) {
420 size_t arrow_pos = trimmed.find(
":-");
421 if (arrow_pos == std::string::npos) {
422 parse_fact_or_directive(trimmed, seeds, group_pairs, deny_nodes, allow_deny_half);
426 std::string head_str = trim_str(trimmed.substr(0, arrow_pos));
427 std::string body_str = trim_str(trimmed.substr(arrow_pos + 2));
428 while (!body_str.empty() && (body_str.back() ==
'.' || std::isspace(
static_cast<unsigned char>(body_str.back())))) {
433 if (head_atom.predicate.empty())
continue;
435 auto raw_terms = split_top_level_atoms(body_str);
436 std::vector<ParsedAtom> body_atoms;
437 for (
const auto& rt : raw_terms) {
439 if (!atom.predicate.empty()) {
440 body_atoms.push_back(atom);
441 edges.push_back({head_atom.predicate, atom.predicate, atom.negated});
444 rules.push_back({head_atom.predicate, head_atom.args, std::move(body_atoms)});
447 std::string strat_err;
449 throw std::runtime_error(
"Datalog Stratification Error: " + strat_err);
452 uint16_t max_group_plus_one = explicit_num_groups;
453 for (
size_t i = 1; i < group_pairs.size(); i += 2) {
454 uint16_t g1 =
static_cast<uint16_t
>(group_pairs[i] + 1);
455 if (g1 > max_group_plus_one) max_group_plus_one = g1;
457 bool multi_lane = !seeds.empty() || !group_pairs.empty() || allow_deny_half > 0;
459 std::unordered_map<std::string, std::vector<ParsedRule>> rules_by_head;
460 std::vector<std::string> head_order;
461 for (
const auto& r : rules) {
462 if (rules_by_head.find(r.head_predicate) == rules_by_head.end()) {
463 head_order.push_back(r.head_predicate);
465 rules_by_head[r.head_predicate].push_back(r);
468 std::unordered_set<std::string> recursive_preds;
469 for (
const auto& hp : head_order) {
471 recursive_preds.insert(hp);
475 std::vector<impulse::compiler::AstPtr> steps;
476 if (!group_pairs.empty()) {
478 group_pairs, std::max<uint16_t>(1, max_group_plus_one)));
479 }
else if (!seeds.empty() || allow_deny_half > 0) {
483 std::unordered_set<std::string> emitted_recursive_rels;
484 std::vector<std::string> negated_preds;
486 for (
const auto& rule : rules) {
487 bool rule_is_recursive = recursive_preds.count(rule.head_predicate) > 0;
488 for (
const auto& atom : rule.body) {
490 negated_preds.push_back(atom.predicate);
493 if (atom.predicate == rule.head_predicate) {
496 if (rules_by_head.count(atom.predicate) > 0 && recursive_preds.count(atom.predicate) == 0) {
500 auto dir = atom.reverse_direction
505 if (!rule_is_recursive || emitted_recursive_rels.insert(atom.predicate).second) {
506 steps.push_back(std::make_shared<impulse::compiler::ScmLaneWalk>(
507 atom.predicate, -1, dir, rule_is_recursive, rule_is_recursive ? 0x04 : 0x00));
510 if (rule_is_recursive) {
511 if (emitted_recursive_rels.insert(atom.predicate).second) {
515 steps.push_back(std::make_shared<impulse::compiler::ScmFixpoint>(
529 if (allow_deny_half > 0) {
531 }
else if (!deny_nodes.empty()) {
533 }
else if (!negated_preds.empty()) {
536 }
else if (!negated_preds.empty()) {
542 : std::make_shared<impulse::compiler::ScmProgram>(steps);
544 for (
const auto& neg_pred : negated_preds) {
548 steps.push_back(pos_node);
557 return std::make_shared<impulse::compiler::ScmProgram>(steps);