Prolog

eyemind reads .pl files written in a pure subset of Prolog with set semantics: facts and rules with structural terms and lists, exact arithmetic, stratified negation, aggregates and fresh witnesses, and requests that ask queries and check goals. It compiles them to ordinary Logic Script (LS). This is an input extension: the meaning of the compiled program is defined by the LS specification, and this document says how eyemind reads Prolog and what it compiles each part to. ISO/IEC 13211-1:1995, with Technical Corrigenda 1:2007, 2:2012 and 3:2017, is the reference for the notation and operations the subset shares with Prolog, not for how a program is evaluated: relations are sets of ground facts, and clause order, repeated derivations and the order of answers have no meaning.

The Prolog conformance suite has cases for each section of this reference. Run them with node pl-conformance/run.js or in the Prolog browser runner.

Logic Script · Logical English

A Logical English document can include a .pl file as a Prolog resource; the LE reference says how its clauses are read with this reference.

A first program

human(socrates).
mortal(Person) :- human(Person).

?- mortal(Who).
?- why.
?- check(mortal(socrates)).
% Answer 1
mortal(socrates).

% Goal check 2
check_result(2, true).

The query asks who is mortal, and the goal check whether Socrates is. ?- why. asks for the reason, which eyemind gives with --proof; see Requests.

Documents

A document is UTF-8 text of statements, each ended by a full stop that is followed by layout, a comment or the end of the text:

Statement Form
Fact Head. with a ground head
Unit clause Head. with a variable in its head
Rule Head :- Goal1, ..., GoalN.
Request ?- Goals., ?- why., ?- why(Goals)., ?- check., ?- check(Goals).
Directive :- table Name/Arity, ... .

The whole input is read before anything runs, so a request can use facts and rules that come after it. Several .pl files are read as one program, in the order given, and their table directives are joined. The table directive takes predicate names and nonnegative arities. It makes their ordinary rules demand-driven, wherever the directive stands. Facts and rules with fresh/1 remain available to forward reasoning. A declared predicate may have no clauses. Any other directive, such as :- dynamic p/1., is an error.

RDF data given with the program states one fact rdf(S, P, O, G) per quad, as for an LS program: an IRI is iri('...'), a literal literal(Lexical, datatype(IRI)) or literal(Lexical, lang(Tag)), an xsd:integer an integer, and the default graph default_graph. With --stream-messages, each RDF message supplies its own facts for a separate run. Direct inputs to a Prolog run are .pl sources and RDF data. RDF logic profile switches are unavailable.

Syntax

Layout and comments

Whitespace separates tokens. % starts a comment to the end of the line, and /* one to the first */, which does not nest; a block comment that is not closed is an error. Comment markers inside quotes are text.

Names, variables and quotes

Token Form
Name A lowercase ASCII letter, then ASCII letters, digits and _: socrates, rule_1
Quoted atom '...', with '' for a quote inside: 'red-fox', 'Élodie'
Variable An uppercase ASCII letter or _, then ASCII letters, digits and _
String "...", with "" for a double quote inside
Integer Decimal digits: 0, 42, 123456789012345678901234567890
Real Digits with a fraction, an exponent or both: 2.5, 1.0e-3, 1e21

Names and variables are ASCII; other characters need quotes. A quoted atom that could be written without quotes is the same atom: socrates and 'socrates'. The variable _ is anonymous: each occurrence is a new variable. Other variables that begin with _ are ordinary, shared within their statement, but an answer does not show them.

Inside quotes, \n, \r, \t, \b, \f, \\, \' and \" escape a line feed, carriage return, tab, backspace, form feed, backslash and quotes, and \uXXXX and \UXXXXXXXX the character with that hexadecimal code. A \u high surrogate must be followed by a \u low surrogate, and the pair is one character. Any other escape is an error.

A real needs digits on both sides of its decimal point: 1. ends a statement, and .5 is not a number. An exponent needs digits. A sign is not part of a number token; a minus written before a number makes a negative number, as in -3 and - 3. Numbers in other bases, 0'c character codes and digit groups such as 1_000 are errors.

Operators

The operators are fixed, after ISO 6.3.4.4, from the loosest binding to the tightest:

Priority Type Operators
1200 xfx :-
1200 fx :-, ?-
1150 fx table
1000 xfy ,
900 fy \+
700 xfx =, \=, is, <, =<, >, >=, =:=, =\=, @<, @=<, @>, @>=, =..
500 yfx +, -, \/, /\, xor
400 yfx *, /, //, div, rem, mod, <<, >>
200 xfx **
200 xfy ^
200 fy -, +, \

The arguments of a compound and the items of a list are terms of priority 999 at most, and parentheses group any term. A negative number is a term of priority 0, so 2 ** -2 is read, and -2^2 is -(2^2), which is -4. Both operands of **, and the left operand of ^, bind tighter than 200: 2 ** 3 ** 2 and 2 ** 3 ^ 2 are errors, and 2 ^ 3 ** 2 is 2 ^ (3 ** 2).

A name directly followed by (, without layout, starts a compound: point(2, 3), '+'(1, 2), -(3). xor, is, div, rem and mod are names that act as infix operators.

The operators of priority 700, \+, :- and ?- build goals, not data: p(X = Y) is an error, while p('='(X, Y)) is the term. The arithmetic operators build ordinary compounds: p(1 + 2) has the argument '+'(1, 2), which is evaluated only where arithmetic is.

Cut !, disjunction ;, if-then-else, curly terms {...} and operator declarations are not supported; using them is an error.

Terms

Kind Examples
Atom socrates, 'Élodie', '7'
Integer 0, -42, unbounded
Real 2.5, 1.0e-3, a finite binary64 value
String "text"
Variable X, _Total, _
Compound point(2, 3)
List [], [a, b], [H | T]

Integers, reals, atoms and strings are distinct: 1, 1.0, '1' and "1" are four terms, and none is turned into another. [] is the empty list, as in ISO, and '[]' is the same term. A non-empty list is the compound '.'(Head, Tail), and its tail must be a list or a variable: [a | b] is an error, and so is an answer that would contain such a list. -0.0 is 0.0.

Unification is syntactic and checks for cycles: X = f(X) fails. It never evaluates arithmetic or converts between numbers.

A predicate name, or the name of a compound, must not begin with $; such names are eyemind’s own (see Compilation to LS).

Clauses and goals

A fact’s head is ground; a head with a variable makes a unit clause, a rule with an empty body. A rule body is goals joined by ,, which parentheses may group; groups are flattened. A head is an atom or a compound; it must not be a variable, a number or a built-in predicate, and the names aggregate_all, fresh, why and check cannot be defined at any arity. Every other predicate is ordinary, with no clauses until the program gives it some: ?- call(true). has no answers unless the program defines call/1, and fail is an ordinary predicate too.

Goal Meaning
p(T1, ..., Tn) or p A call of an ordinary predicate
true, false Succeeds; fails
Left Op Right A built-in comparison or unification (see Built-in predicates)
A built-in call, such as string_length(S, N) A built-in predicate
\+ Goal Negation of one goal (see Negation)
aggregate_all(Template, Goal, Result) An aggregate (see Aggregates)
fresh(W) A new witness, as the last goal of a rule (see Witnesses)

A variable’s scope is its statement. A variable is not a goal, and call/N is not supported.

Binding modes

Goals run from left to right. The compiler uses these modes to select rules that can run forward and to plan demand-driven calls.

Goal Needs bound Binds
Ordinary call nothing all its variables
true, false nothing nothing
X = Y, T =.. L, atom_chars(A, L), atom_codes(A, L), number_chars(N, L), string_codes(S, L) one argument all its variables
X is E E all its variables
atom_concat(A, B, C) C, or both A and B all its variables
string_concat(A, B, C) A and B C
string_length(S, N) S N
X \= Y, comparisons, contains_text/2 every variable nothing
\+ Goal every variable of Goal other than _ nothing
aggregate_all(T, G, R) nothing the variables of R
fresh(W) nothing; W must not be bound W

A rule is range-restricted when its body, read this way from no bindings, meets every goal’s needs and binds every variable of its head.

Evaluation

A range-restricted rule normally runs forward and derives every fact it can, whether or not a request asks for it. Unit clauses with variables, ordinary rules of predicates named in a table directive and rules that need bindings from their caller are demand-driven. Rules with fresh/1 run forward. A demand-driven rule is used only for the calls that need it, with the bindings those calls supply, and every answer it gives must be ground: an answer that leaves a variable of its head unbound is an error.

Facts and answers are sets: a fact holds once however many derivations it has, and a query’s answers are distinct. A finite set of facts does not make a search finite: :- table p/1. p(X) :- p(f(X)). ?- p(a). demands p(a), p(f(a)) and ever deeper calls, until a resource bound stops the run with an error.

Built-in predicates

Predicate Meaning
true, false Succeeds; fails.
X = Y Unifies X and Y.
X \= Y X and Y do not unify with the current bindings; binds nothing. X \= a fails while X is unbound.
V is E Evaluates E and unifies the value with V: 1 is 1.0 fails.
A < B, A =< B, A > B, A >= B Compares the values of A and B, exactly across integers and reals.
A =:= B, A =\= B The values are equal, or not: 1 =:= 1.0 succeeds.
A @< B, A @=< B, A @> B, A @>= B Compares two atoms, or two strings, by the code points of their characters; anything else is an error.
T =.. L L is T’s name followed by its arguments. For an atom, number, string or empty list, it is [T]. For a nonempty list with head H and tail Tail, it is ['.', H, Tail].
atom_chars(A, L), atom_codes(A, L) L is the list of A’s characters as one-character atoms, or as code points.
atom_concat(A, B, C) C is A followed by B; with C alone bound, every split, shortest A first.
number_chars(N, L) L spells N; a bound L is read as a number after leading layout, and fails if it spells none.
string_codes(S, L) L is the list of the code points of the string S.
string_concat(A, B, C) C is the string A followed by the string B.
string_length(S, N) N is the number of characters of the string S.
contains_text(T, P) The string P, lowercased, occurs in the string T, lowercased, by Unicode default case conversion; an empty P occurs in every T.

The atom and number predicates are LS’s primitives of the same names (LS-SPEC 4.3), with their argument patterns and errors. A string predicate given anything but a string is an error.

Arithmetic

An integer is exact and unbounded; a real is a finite binary64 value. An expression is evaluated only by is/2, the numeric comparisons and the sum, min and max aggregates; elsewhere 1 + 2 is a compound. A variable in an expression may be bound to a number or to an expression, which is then evaluated too.

Operator Value
X + Y, X - Y, X * Y An integer for two integers, a real otherwise.
-X, +X X negated, or X, of the same type.
X / Y A real, for integers too: 1 / 4 is 0.25; two integers give their exact quotient rounded once.
X // Y The integer quotient rounded toward zero.
X div Y The integer quotient rounded down.
X rem Y The integer remainder with the sign of X.
X mod Y The integer remainder with the sign of Y.
X ** Y A real power; a negative X needs an integer Y.
X ^ Y An exact integer for two integers and Y >= 0, so 0 ^ 0 is 1; a real when either is a real.
X /\ Y, X \/ Y, X xor Y, \X Bitwise and, or, exclusive or and complement of integers.
X << Y, X >> Y Integer shifts; >> keeps the sign.

With -7 and 3, //, div, rem and mod give -2, -3, -1 and 2. For an integer ^ with a negative exponent, the bases 1 and -1 give integers, the base 0 is an error, and any other integer base is an error that asks for a real base, as ISO Corrigendum 3 does: 2.0 ^ -1 is 0.5.

Function Value
abs(X) The absolute value, of X’s type.
sign(X) -1, 0 or 1, of X’s type.
min(X, Y), max(X, Y) The smaller or larger operand, unchanged; the first when they are equal.
sqrt(X), exp(X), log(X) Square root, exponential and natural logarithm, as reals.
sin(X), cos(X), tan(X), asin(X), acos(X), atan(X) Trigonometric functions of radians and their inverses.
atan2(Y, X) The angle of the point (X, Y); two zero arguments are an error.
float(X) X as a real.
floor(X), ceiling(X), truncate(X) The integer below, above or toward zero from the real X.
round(X) The integer nearest to the real X, halfway toward positive infinity: round(-2.5) is -2.
float_integer_part(X), float_fractional_part(X) The real X’s integral part, truncated, and the rest.
gcd(X, Y) The nonnegative greatest common divisor of two integers.
pi, e The binary64 values of π and e.

//, div, rem, mod and the bit operations need integers, and floor, ceiling, round, truncate, float_integer_part and float_fractional_part need a real, as ISO requires: round(3) is an error; write round(float(3)). Evaluation is an error for an unbound variable, a term that is not a number, a function the tables do not list, a division by zero, a result that is not a finite real, and a nonzero power that underflows to zero. A host’s math library may give a different last bit for the transcendental functions (LS-SPEC 13).

Negation

\+ Goal succeeds when Goal has no solution, once everything that derives it is complete; it binds nothing. Goal is one ordinary call or built-in test, and every variable in it other than _ must be bound when it runs. A negated conjunction, a nested negation, and a negated aggregate or witness are errors: define a helper predicate instead. \+ X = Y is \+ (X = Y). No dependency cycle may pass through a negation, as LS’s stratification requires (LS-SPEC 6.1). Absence means only that the program has no evidence for the goal.

Aggregates

?- aggregate_all(count, mortal(Person), Count).
?- aggregate_all(sum(Value), score(Person, Value), Total).
?- aggregate_all(min(Value), score(Person, Value), Minimum).
?- aggregate_all(max(Value), score(Person, Value), Maximum).
?- aggregate_all(list(Person - Value), score(Person, Value), Results).

aggregate_all(Template, Producer, Result) collects the solutions of Producer, one goal or a parenthesized conjunction, once everything that derives them is complete. The variables bound before the aggregate are its group; the producer’s other variables are its own, and no later goal or head sees their bindings. The solutions are the distinct tuples of the producer’s own variables: repeated facts and other derivations of the same tuple add nothing, while equal template values from distinct tuples count separately.

Template Result
count The number of tuples.
sum(V) The sum of the values of V; 0 when there are none.
min(V), max(V) The least or greatest value of V; fails when there are none.
list(T) The list of the instances of T, one per tuple, in an unspecified order.

The producer must bind every variable of the template that the group does not. Result is unified with the value after collecting, so a bound Result filters nothing before.

In a range-restricted rule only the goals before the aggregate make its group, even when a call binds the rule’s head: total(X, N) :- aggregate_all(count, p(X), N), q(X). counts every p fact, whatever total(a, N) asks. A rule that is not range-restricted may group by the bindings its calls supply.

Witnesses

ticket(Person, Ticket) :- registered(Person), fresh(Ticket).

fresh(W), as the last goal of a rule, binds the named variable W to a new value. The variable occurs in the head and no preceding goal may mention it. The value is a witness, distinct from every atom, number and string. The rule’s body must bind every other variable of its head. The rule makes one witness for each binding of the other variables of its head, and none when a known fact already fits its head with some value for W. A witness is LS’s Skolem term (LS-SPEC 8.2): skolem(Rule, 'W', [Values]), from the number of its compiled rule, the variable’s name and the values of the head’s other variables, which answers show as such.

Requests

Request Effect
?- Goals. A query: its distinct answers.
?- check(Goals). A goal check: whether Goals has a solution.
?- why(Goals). A query, as ?- Goals.
?- why., ?- check. Accepted after a query; the proof and its check are made by --proof and --prove-and-check.

Queries and goal checks are numbered together, from 1, in the order of the program. A why or check without a query before it is an error. A query is read with no variables bound. At run time, unification can link two unbound variables, and X \= a fails while X is unbound. Arithmetic expressions and negation require their input bindings.

Output

The output of a run is a Prolog document, one group of records per query or goal check in order, separated by an empty line:

Heading Records
% Answer N The answers of query N, or no_answer(N).
% Goal check N check_result(N, true). or check_result(N, false).

When every goal of a query is an ordinary call and no goal has _, each distinct ground instance of each goal is printed as a fact. Otherwise an answer is answer(N, [binding("Name", Value), ...]), with the variables in order of first occurrence, leaving out those that begin with _ and the producers’ own variables of aggregates. Every value written must be ground; an answer that leaves a written variable unbound is an error. Answers come in the order eyemind finds them, which has no meaning.

A program without requests writes each fact its rules derive, one per line, without a heading.

A term is written as Prolog reads it back: an atom bare when it is a name and quoted otherwise, a string in double quotes, an integer in decimal, a real with the shortest digits that give it back and always a fraction or an exponent (2.5, 15.0, 1e21, 4.8e-5), a compound in functional notation ('+'(1, 2)) and a list in brackets. Inside quotes, a line feed, carriage return, tab, backslash and the quote are escaped, and other control characters are written \uXXXX. A record that fits in 88 columns is one line; a longer one puts each argument on its own line, indented by four spaces, keeping the argument of a one-argument compound beside it and filling lines with the items of a list of atoms, numbers and strings. The bindings of an answer are always one per line:

% Answer 4
answer(4, [
    binding("M", 7),
    binding("Who", ada)
]).

--to pl writes this document, the default for a Prolog run; --to eyemind writes the answers of the compiled program.

Compilation to LS

Each fact compiles to an LS fact, and each ordinary forward rule to implies. A demand-driven rule normally compiles to a backward rule (implied_by), which a search answers, ending with a goal that raises an error when an answer is not ground. A forward rule’s call of such a predicate is answered by that search.

A demand-driven predicate on a cycle of calls compiles instead to forward rules gated by demand facts, so that each call is answered once, as a table answers it (the magic-set transformation). A call of such a predicate, with the arguments the goals before it have bound marked b and the others f, derives the demand fact '$pl:call:NAME/ARITY:ADORNMENT'(Bound...) from those goals, and each of the predicate’s demand-driven rules, for that pattern, becomes a forward rule whose first goal is the demand. For fibonacci(N, F) called with N bound:

implies([struct('$pl:call:fibonacci/2:bf', N), gt(N, 1), ...], fibonacci(N, F))

So does a demand-driven predicate whose demand-driven rules call one. Such a rule is split into a chain of rules, one link for each later goal that facts answer: a link concludes a supplementary fact, '$pl:sup:K:I'(...), of the variables bound so far that later goals or the head need, and the next link joins it with that goal. LS’s semi-naive search starts from a goal’s new facts when only goals answered by facts come before it, so each new fact of a long chain of demands costs one indexed lookup, and the demands of the rule’s calls are derived from the same supplementary facts.

A negation or an aggregate whose call’s demand would depend on that negation or aggregate is on a cycle of LS’s dependencies, though Prolog decides it once the call is complete. Such a negation or aggregate gets its own copy of the predicates it reaches that demand facts or forward rules answer, named $pl:ctxN:NAME, with demands of its own. When even the copy is on a cycle, as when a recursive rule negates a call whose demand its own recursion derives, the copy’s gated predicates are searched instead, without tables; a search that meets a cycle of calls does not end before a resource bound stops it.

A query N compiles to a backward rule for '$pl:answer'(N, [V1, ...]), with the query’s variables outside the producers of its aggregates, and the statement query('$pl:answer'(N, [V1, ...])); a goal check compiles to '$pl:check'(N), solved once. A rule with fresh/1 compiles to a forward rule whose head-only variable gets the witness. It uses a restricted rule when another clause defines the same predicate or companion RDF supplies facts for rdf/4 (LS-SPEC 7.2), whose firings a proof cannot certify.

\+ G compiles to not(G), and an aggregate to findall_sorted over the tuples of the producer’s own variables, renamed apart, with helpers that keep the distinct tuples and compute the result. An arithmetic expression compiles to an LS expression where the values agree, X + Y to add(X, Y); an operator whose types ISO checks, a variable, which may be bound to an expression, and any other term are computed by helper rules first. A string is the compound '$string'(Text). A predicate whose name and arity are LS’s own, such as call/1 or compare/3, is renamed with a leading $, and so is a compound named implies/2, implied_by/2, forward/2 or backward/2; output writes the Prolog names. The helpers’ names begin with $pl:, and they follow the program’s clauses. --program prints the compiled program as a standalone LS script.

Proofs and check reports are .js documents of the compiled program, and check against it, as for every input that compiles to LS: --proof, --check-proof and --prove-and-check work on .pl inputs. That the program means what the Prolog says is a matter of the compiler and its tests; a checked proof establishes the answers under the compiled rules.

Not supported

These belong to Prolog but not to this subset, and are errors where the reader meets them: cut, disjunction, if-then-else, curly terms, operator declarations, directives other than table, and variables as goals. call/N, assert/1 and retract/1, findall/3, bagof/3 and setof/3, I/O, streams, exceptions and catch/3, flags, modules and DCGs have no built-in meaning; such a name is an ordinary predicate without clauses unless the program defines it. Use aggregate_all/3 to collect solutions.