Language tutorial
This tutorial covers facts, queries, joins, recursion, negation, arithmetic and aggregates.
Each example below is a complete program. Save one as example.dl
and run relic -s example.dl.
1. State facts and ask questions
A fact ends in a period. Lowercase names are symbols; uppercase names are variables. A predicate is identified by its name and number of arguments.
depends(web, api).
depends(api, database).
depends(worker, api).
depends(App, api)?
The answer is web and worker. A query returns the
named variables in order of first occurrence. Use _ for a value you
do not need; each _ is independent. depends(web, _)?
is a yes-or-no question with no output columns.
2. Join relations with rules
:- reads “if”, and commas mean “and”. Repeating a variable
joins matching values. A head is derived whenever its body holds.
depends(web, api).
depends(api, database).
depends(worker, api).
two_steps(App, Target) :-
depends(App, Middle), depends(Middle, Target).
two_steps(App, database)?
Several rules with the same head contribute to the same relation. Relations are sets: stating or deriving the same fact twice adds no duplicate.
3. Follow an arbitrary number of steps
A base rule includes direct dependencies. A recursive rule extends an existing chain by one edge. Evaluation stops when no new facts can be derived.
depends(web, api).
depends(api, database).
depends(worker, api).
affected(App, Changed) :- depends(App, Changed).
affected(App, Changed) :-
depends(App, Middle), affected(Middle, Changed).
affected(App, database)?
Cycles do not keep this program running forever: there are only finitely
many pairs of these symbols. Recursion that generates new integers can still
grow without bound; use limits for workloads you do not control, for example
-l tuples=100000 -l memory=67108864. The memory limit bounds
accounted engine storage, not total process memory.
4. Ask what is absent
not tests for absence. First establish the possible values with
a positive relation; then exclude the values you do not want.
depends(web, api).
depends(api, database).
depends(worker, api).
service(S) :- depends(S, _).
service(S) :- depends(_, S).
leaf(S) :- service(S), not depends(S, _).
leaf(S)?
database has no outgoing dependency. A variable in a negated
literal must already be bound by the rule's positive facts or assignments.
Negation is stratified: a relation cannot depend on itself through negation.
relic rejects such a program.
5. Compute with values
Values are symbols, double-quoted byte strings, or signed 64-bit integers.
The symbol api and the string "api" are different values.
Arithmetic belongs in body comparisons; = can bind a computed value.
size(api, 12).
size(web, 7).
larger(Service, Bytes) :- size(Service, N), Bytes = N * 1024,
Bytes > 10000.
larger(Service, Bytes)?
Operators include +, -, *, /
and mod. Overflow and division by zero fail evaluation.
String functions include length, cat,
substr, index, match and str.
6. Count a group
An aggregate folds the distinct rows inside its braces. A variable shared with the outer rule selects the group; bind it both outside and inside the braces.
depends(web, api).
depends(api, database).
depends(worker, api).
service(S) :- depends(S, _).
service(S) :- depends(_, S).
dependency_count(S, N) :- service(S),
N = count { depends(S, Target) }.
dependency_count(S, N)?
The result includes database 0: an empty group has a count of
zero. sum(Value), min(Value) and max(Value)
select the value to fold. Aggregates read complete relations and cannot recurse
through themselves.
Keep the variables you want to count: count { depends(S, _) }
counts distinct rows with no local columns, so it returns at most one.
Using Target preserves each different dependency.
7. Plan a subway transfer
On this fictional network, start at museum on the red line.
Find destinations that require one line change, along with the transfer
station and the line to board.
% A fictional subway network; segments work in both directions.
segment(red, museum, central).
segment(red, central, harbor).
segment(blue, west_end, central).
segment(blue, central, garden).
segment(blue, garden, airport).
segment(green, harbor, hill).
adjacent(Line, A, B) :- segment(Line, A, B).
adjacent(Line, A, B) :- segment(Line, B, A).
ride(Line, A, B) :- adjacent(Line, A, B).
ride(Line, A, C) :- ride(Line, A, B), adjacent(Line, B, C).
direct(Destination) :- ride(red, museum, Destination).
one_transfer(Destination, Transfer, Line) :-
ride(red, museum, Transfer), ride(Line, Transfer, Destination),
Line != red, not direct(Destination).
% Starting at museum on red: destination, transfer station, new line.
one_transfer(Destination, Transfer, Line)?
adjacent makes each segment bidirectional. ride
finds stations connected along a single line. one_transfer joins
a red-line ride to a ride on another line; not direct excludes
destinations already reachable on red. The columns below are destination,
transfer station and new line.
airport central blue
garden central blue
hill harbor green
west_end central blue
Recursion follows any number of stops on a line, including its cycles, without enumerating every possible path. This query finds destinations with one transfer; it does not optimize travel time or count the stops.
Try this example in the browser.
8. Find unused functions
A source-code analyzer can represent function definitions and calls as facts. Starting from the entry point, recursion finds reachable functions; negation then finds definitions outside that set.
% Analyze an explicit call graph, starting at main.
function(main). function(parse). function(scan). function(print).
function(legacy_parser). function(debug_dump).
entry(main).
calls(main, parse). calls(parse, scan). calls(main, print).
calls(legacy_parser, debug_dump). calls(debug_dump, legacy_parser).
reachable(Function) :- entry(Function).
reachable(Callee) :- reachable(Caller), calls(Caller, Callee).
unused(Function) :- function(Function), not reachable(Function).
% Reachable functions, then functions unreachable from any entry point.
reachable(Function)?
unused(Function)?
The first query lists reachable functions. The second identifies
debug_dump and legacy_parser as unreachable from
main. They call each other, but a cycle does not make either
reachable without a call from an entry point.
main
parse
print
scan
debug_dump
legacy_parser
The result depends on the supplied call graph and entry points. Additional
entry points can be represented by more entry facts.
Try this example in the browser.
9. Infer types through an expression graph
Facts can also describe expressions and assignments. In this small model,
assignments propagate type information and addition requires two integers.
The symbols integer and text are labels for the
analyzed language, represented as ordinary Datalog data.
% Toy expression graph: assignments copy types; addition needs integers.
int_literal(one). text_literal(label).
assign(x, one). assign(y, x). assign(title, label).
add(total, x, y). add(broken, x, title).
type(Expression, integer) :- int_literal(Expression).
type(Expression, text) :- text_literal(Expression).
type(To, Type) :- assign(To, From), type(From, Type).
type(Sum, integer) :- add(Sum, Left, Right),
type(Left, integer), type(Right, integer).
type_error(Expression) :- add(Expression, Left, _),
type(Left, Type), Type != integer.
type_error(Expression) :- add(Expression, _, Right),
type(Right, Type), Type != integer.
% Inferred types, then additions with a non-integer operand.
type(Expression, Type)?
type_error(Expression)?
The first query shows the inferred types. The type of one
propagates through x and y, allowing total
to be inferred as an integer. The second query reports broken,
whose right operand has type text.
label text
one integer
title text
total integer
x integer
y integer
broken
The two type_error rules check the left and right operands
separately. Either rule can report an invalid addition; set semantics merge
duplicate reports. These diagnostics are query results from the model, not
errors raised by relic itself.
Try this example in the browser.
The full language
See the language reference for safety, ordering, string functions, aggregate semantics and limits. The example collection works through larger programs.