Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Logicals

A logical is a relation. Facts are relation values, rules are log declarations, and a query is a call. The model is Datalog with stratified negation:

  • every rule set the checker accepts terminates on every finite fact base, so a query can never hang;
  • answers are sets: clause order and goal order change the cost of a query, never its answers, and there is no cut and no first-solution commitment;
  • unsafe variables, negation cycles, and value invention are reported by fol code check, not discovered at run time.

Facts and rules have one spelling. A caller cannot tell whether the relation it queries is a stored fact base or a rule.

The code blocks on this page read in order as one program, and the book audit type-checks them that way.

Relations

rel[T1, ..., Tn] is a finite set of tuples. Its columns are positional and typed, and every column type must satisfy ord, because joins and indexes need a total order. A column is an ordered scalar: an int width up to 64 bits or i128, bol, chr, or str. A flt column is error Q1006.

con[exp] parent: rel[str, str] = {
    { "albert", "bob" },
    { "albert", "betty" },
    { "alice", "bob" },
    { "alice", "betty" },
    { "bob", "carl" },
    { "bob", "tom" },
};

con dances: rel[str] = { "albert", "alice", "carl" };
  • A con relation is a compile-time constant fact base. Its initializer is a literal of constants, which the checker evaluates.
  • A var[mut] relation is a runtime fact base, changed with methods on the binding:
pro[] edges_demo(): int = {
    var[mut] edges: rel[int, int] = {};
    edges.add(1, 2);
    edges.add(2, 3);
    edges.add(2, 3);
    edges.remove(1, 2);
    var known: bol = edges.has(2, 3);
    var[mut] total: int = 0;
    each (edge in edges) {
        total = total + edge.c0 + edge.c1;
    };
    return edges.len() + total;
};
  • .add and .remove take one value per column, .has answers membership, and .len() counts distinct tuples: duplicates collapse. .add and .remove change a binding in a routine; a file-scope relation is read with .has, .len(), and queries.
  • each (t in edges) { ... } visits tuples in column order. A one-column relation yields its element type; a wider one yields a positional record whose fields are c0, c1, and so on.
  • rel needs the heap, so it is available from fol_model = "memo" up. A relation copies (cpy) when every column does, which a str column does not; it always clones and is send and share, since every column is a scalar.
  • A rule never reads ambient mutable state. A var relation reaches a rule only as an argument (see Relation parameters).

Rules

A log body is a list of clauses separated by ;. A tuple belongs to the relation when any clause holds for it. An optional label => names a clause.

log[exp] grandparent(g, c: str) = {
    exi p: str, parent(g, p) and parent(p, c);
};

log[exp] ancestor(a, d: str) = {
    direct => parent(a, d);
    step => exi m: str, parent(a, m) and ancestor(m, d);
};

A log has no return type: it is always a relation, and its head parameters are its columns. It is not generic.

A clause body is a formula, not a statement. It may contain:

  • relation goals r(args), where r is a rel binding, a rel parameter, or another log;
  • and, or, not, and parentheses;
  • exi x: T, formula, which introduces a clause-local variable;
  • _ as a goal argument, an anonymous variable that is projected away;
  • comparisons == != < <= > >= and integer arithmetic + - * / % on bound values;
  • calls to pure funs that take ordered scalars and return an ordered scalar or an opt of one.

or is distributed into one clause per alternative, and not is pushed through and and or onto goals and comparisons, where not a < b becomes a >= b. The alternatives of a labelled clause that or splits are labelled <label>_1, <label>_2, and so on in source order, so a proof names each one. not cannot wrap an exi: write not r(x, _) for “no r(x, y) for any y”. all, ->, and <-> belong to ghost logicals and theorems (see Proofs); an executable log rejects them as Q1007, as it does any other expression with no rule reading.

More rules over the same facts:

log dancing_parent(a: str) = {
    parent(a, _) and dances(a);
};

log sibling(a, b: str) = {
    exi p: str, parent(p, a) and parent(p, b) and a != b;
};

con brothers: rel[str, str] = { { "bob", "bill" }, { "bill", "bob" } };

log uncle(u, c: str) = {
    exi p: str, parent(p, c) and brothers(p, u);
};

dancing_parent(a) holds when a is the parent of anyone, which _ leaves unnamed, and a dances.

A rule that derives new facts from old ones is just another clause:

con stabs: rel[str, str, str] = { { "tybalt", "mercutio", "sword" } };
con friends: rel[str, str] = { { "romeo", "mercutio" } };

log hates(a, b: str) = {
    friends(a, _) and stabs(b, "mercutio", _);
};

Variables

  • Head parameters are the relation’s columns.
  • exi x: T, introduces a variable local to one clause. Its type annotation is required.
  • _ in a goal is a fresh anonymous variable, so not likes(a, _) reads “a likes nobody”. Outside a goal or a query argument, _ is an error.
  • A name that resolves to nothing is an ordinary unresolved-name error. No variable is ever invented from a spelling.
  • An expression goal argument, as in edges(a, b + 1), reads as a fresh variable that equals the expression.

Negation and stratification

not goal is allowed when the goal’s relation does not depend, directly or transitively, on the relation being defined. The checker builds the dependency graph between relations and computes its strongly connected components; a negative edge inside one component is error Q1002, which prints the cycle.

log lonely(people: rel[str]; likes: rel[str, str]; a: str) = {
    people(a) and not likes(a, _);
};

Safety

Every head variable, every variable inside a not, and every variable used in a comparison or a fun call must be bound by a positive relation goal in the same clause. An equality x == expr binds x once everything in expr is bound. Otherwise the clause is error Q1001, which names the variable and the goal that needs it. Safety is what keeps every answer drawn from the finite fact bases.

Arithmetic and value invention

A clause may compute a value from bound variables:

log next_hop(edges: rel[int, int]; a, b: int) = {
    exi k: int, edges(a, k) and b == k + 1;
};

Inside a recursive component a computed value may not reach the head or a recursive goal’s argument, because count(n + 1) style rules never terminate. Crossing that line is error Q1003. A non-recursive clause may compute freely, since it fires a finite number of times.

Arithmetic that overflows its column type, divides by zero, or takes a remainder by zero is undefined, and the comparison that holds it does not hold: answers never depend on the order goals run in. A call to a fun that breaks is undefined the same way, so a query never breaks because a clause call did.

A call to a fun that returns opt[T] compares at T, as a side of a comparison, a goal argument, or a bol condition. The comparison holds when the call returns a value that satisfies it, and nil is undefined, as a break is: the comparison does not hold whichever way it points.

fun[] half(n: int): opt[int] = {
    if (n % 2 == 0) {
        return n / 2;
    };
    return nil;
};

con sizes: rel[int] = { 2, 3, 4 };

log halves(n, m: int) = {
    sizes(n) and m == half(n);
};

halves holds { 2, 1 } and { 4, 2 }; 3 has no half, so no tuple starts with it.

Queries

A query is a call. With every argument bound it returns bol. Each _ marks an output column: one free column returns set[T], and several return a rel[...] of the free columns in order.

fun[] reach_count(edges: rel[int, int]): int = {
    var pairs: rel[int, int] = reach(edges, _, _);
    return pairs.len();
};

pro[] main(): int = {
    var yes: bol = grandparent("albert", "carl");
    var kids: set[str] = parent("albert", _);
    var pairs: rel[str, str] = ancestor(_, _);
    var dancers: set[str] = dancing_parent(_);
    var cousins: set[str] = uncle("bill", _);
    var[mut] ring: rel[int, int] = {};
    ring.add(1, 2);
    ring.add(2, 1);
    var hops: int = reach_count(ring);
    return hops;
};

A query is a pure expression, so a fun may run one.

Relation parameters

A log may take rel parameters: its input fact bases, passed as loans. In a goal or a query the relation arguments come in the parameters’ positions.

log reach(edges: rel[int, int]; a, b: int) = {
    edges(a, b);
    exi m: int, edges(a, m) and reach(edges, m, b);
};

Inside a recursive component a relation parameter must be passed through unchanged (Q1004). It is then a fixed parameter of the whole component: the engine evaluates the component once per distinct argument, and the prover reads it as an inductive parameter, so a theorem about reach holds for every edge relation. Inside a clause, a relation argument names a relation parameter, a con relation, or a log without relation parameters.

Relations of other packages

A rule reads the log and con relations a dependency exports through the dependency’s namespace, and ordinary code queries them the same way:

// graph/lib.fol
con[exp] edge: rel[int, int] = { { 1, 2 }, { 2, 3 }, { 3, 4 } };

log[exp] reach(a, b: int) = {
    edge(a, b);
    exi m: int, edge(a, m) and reach(m, b);
};

// app/src/main.fol
use graph: loc = {"../../graph"};

log far(a: int) = {
    graph::reach(a, 4) and not graph::edge(a, 4);
};

pro[] main(): int = {
    var pairs: rel[int, int] = graph::reach(_, _);
    return pairs.len() - 6;
};

A dependency never reads its dependents, so each package’s strata are computed on their own, in dependency order. To the dependent’s rules, a dependency’s relation is an input fact base: a con relation’s tuples, or the answers of the dependency’s own compiled rules. A dependency’s log that takes relation parameters is not read by a rule of another package; ordinary code queries it with its relation arguments.

Evaluation

  • The checker lowers every exec log and every file-scope relation of a package into one checked rule IR, the same IR the prover reads.
  • The backend emits typed Rust for each component of rule sets: one nested loop per clause plan, scanning or probing an index keyed by the bound columns, filtering, assigning, and antijoining for not.
  • A recursive component runs semi-naive iteration to a fixpoint: each round joins only the tuples the previous round derived.
  • A component that takes no relation parameters is computed once per process; one that does is computed per query.

Diagnostics

CodeMeaning
Q1001unsafe variable: not bound by a positive goal
Q1002negation inside a recursive component (the cycle is printed)
Q1003a computed value reaches a recursive head or goal
Q1004a relation parameter changes inside a recursive component
Q1005goal, query, or relation-method arity mismatch
Q1006a column type is not an ordered scalar
Q1007a construct outside the Datalog subset in an executable log

Each code has a fol code explain entry with a failing and a fixed example.

Logicals in proofs

Inside a proof, a log is an inductive predicate: each clause is a constructor, each exi binder a constructor argument, and each relation parameter an inductive parameter. A con relation is decidable membership in its literal. The Proofs chapter shows both readings.