2.17.3 Indexing for body code
The current SWI-Prolog versions only consider the head for generating clause indexing. This would make it impossible to examine a head argument and pass the argument in the body without copying the argument. Consider the two clauses below. Both have equal semantics under Prolog. The first version would loose clause indexing while the second creates a copy of the f/1 argument. Neither is desirable.
p(X) :- X = f(I), integer(I), q(X). p(f(I)) :- integer(I), q(f(X)).
As of SWI-Prolog 8.3.21, unifications against head arguments that happen before anything else in the body are compiled special. Effectively, the term unified too is moved into the head (providing indexing) and places where this term is used simply use the corresponding argument. The explicit unification is removed. Decompilation (clause/2) reverses this process, but may not produce exactly the same term. The re-inserted unfications are ordered according to the argument position and the variable is always on the left hand of the =/2. Thus,
p(X,Y) :- f(_) = Y, X = g(_), q(X,Y).
Is decompiled into the following equivalent clause.
p(X,Y) :- X = g(_), Y = f(_), q(X,Y).
Additional notes:
- This transformation is only performed on static code.
- The unifications must immediately follow the head in a conjunction.
- As sole exception, calls to true/0
are skipped. This allows
goal_expansion/2
to convert goals to
true
while preserving this optimization. - If the head argument is not used the body unification is still moved
into the head. The decompiler does not inverse the process in that case.
Thus,
p(X) :- X = a.
is fully equivalent top(a).
- Currently this optimziation is enabled regardless of the Prolog flag optimise. As this optimization harms source-level debugging, this may not be desirable. On the other hand we do not want determinism to depend on optimization while this optimization affects determinism.