134 4 Logic Programming Languages
may be pushed onto the top of the stack. When returning to the stack frame of the
clause, the local variables may have an arbitrary distance from the Stack Pointer, but
still can be addressed through the FP.
4.9 Queries and Programs
So far, we have translated all constituent parts of a PROL program. The only remain-
ing aspect is how to translate programs as a whole. Assume that program p consists
of predicate definitions rr
1
.....rr
h
together with the query ⇐ g
1
,...,g
l
. The code
for program p then consists of the following parts:
• code for evaluating the query
⇐ g
1
,...,g
l
,
• an instruction no for failure, and
• code for the predicates rr
i
.
Before program execution, we assume that SP
= FP = BP = TP = −1 and
PC
= HP = 0. Before evaluating the query, registers SP, FP and BP must be
initialized and the first stack frame must be pushed onto the stack. Afterwards, the
result substitution is returned (or failure is reported):
code p
= init A
pushenv d
code
G
g
1
ρ
...
code
G
g
l
ρ
halt d
A : no
code
P
rr
1
...
code
P
rr
h
Here {X
1
,...,X
d
} = free(g
1
,...,g
l
) is the set of variablesin the query g
1
,...,g
l
,
and
ρ
(X
i
)=i for i = 1,...,d holds.
The instruction halt d terminates program execution and outputs the final bind-
ings of variable d or initiates backtracking – if demanded by the user.
The instruction init A initializes SP, FP and PC and records the address A in
the stack frame as the negative continuation address (Fig. 4.34). We have placed the
instruction no at address A. This instruction is executed when the query has failed. It
prints no to the standard output and halts.
Now we can translate the first complete P
RO L program.
Example 4.9.1 Consider the following small program:
t
(X) ⇐
¯
X
= bq(X) ⇐ s(
¯
X
) s(X) ⇐
¯
X
= a
p
⇐ q(X), t(
¯
X
) s(X) ⇐ t(
¯
X
) ⇐ p