-
Notifications
You must be signed in to change notification settings - Fork 54
/
interpreter.m
414 lines (363 loc) · 14.7 KB
/
interpreter.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
%---------------------------------------------------------------------------%
% vim: ts=4 sw=4 et ft=mercury
%---------------------------------------------------------------------------%
%
% File: interpreter.m.
% Main author: fjh.
%
% This is an interpreter for definite logic programs
% (i.e. pure Prolog with no negation or if-then-else.)
%
% This is just intended as a demonstration of the use of the
% meta-programming library modules term, term_io, and varset.
%
% There are many extensions/improvements that could be made;
% they are left as an exercise for the reader.
%
% For a more efficient version (using backtrackable destructive update),
% see extras/trailed_update/samples/interpreter.m.
%
% This source file is hereby placed in the public domain. -fjh (the author).
%
%---------------------------------------------------------------------------%
%
% This module is also used as a test case in tests/debugger.
%
%---------------------------------------------------------------------------%
:- module interpreter.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
%---------------------------------------------------------------------------%
:- implementation.
:- import_module list.
:- import_module mercury_term_parser.
:- import_module require.
:- import_module solutions.
:- import_module string.
:- import_module term.
:- import_module term_context.
:- import_module term_io.
:- import_module varset.
main(!IO) :-
io.write_string("Pure Prolog Interpreter.\n\n", !IO),
io.command_line_arguments(Args, !IO),
(
Args = [],
io.stderr_stream(StdErr, !IO),
io.write_string(StdErr, "No files consulted.\n", !IO),
io.set_exit_status(1, !IO)
;
Args = [_ | _],
database_init(Database0),
consult_files(Args, Database0, Database, !IO),
main_loop(Database, !IO)
).
:- pred main_loop(database::in, io::di, io::uo) is det.
main_loop(Database, !IO) :-
io.write_string("?- ", !IO),
read_term(ReadTerm, !IO),
(
ReadTerm = eof
;
ReadTerm = error(ErrorMessage, LineNumber),
io.format("Error reading term at line %d of standard input: %s\n",
[i(LineNumber), s(ErrorMessage)], !IO),
main_loop(Database, !IO)
;
ReadTerm = term(VarSet0, Goal),
% Any special commands with side-effects (such as `consult'
% and `listing') could be identified and processed here.
solutions(solve(Database, Goal, VarSet0), Solutions),
(
Solutions = [],
io.write_string("No.\n", !IO)
;
Solutions = [_ | _],
write_solutions(Solutions, Goal, !IO),
io.write_string("Yes.\n", !IO)
),
main_loop(Database, !IO)
).
:- pred write_solutions(list(varset)::in, term::in, io::di, io::uo) is det.
write_solutions([], _, !IO).
write_solutions([VarSet | VarSets], Goal, !IO) :-
term_io.write_term_nl(VarSet, Goal, !IO),
write_solutions(VarSets, Goal, !IO).
%---------------------------------------------------------------------------%
:- pred consult_files(list(string)::in, database::in, database::out,
io::di, io::uo) is det.
consult_files([], !Database, !IO).
consult_files([File | Files], !Database, !IO) :-
consult_file(File, !Database, !IO),
consult_files(Files, !Database, !IO).
:- pred consult_file(string::in, database::in, database::out,
io::di, io::uo) is det.
consult_file(File, !Database, !IO) :-
io.format("Consulting file `%s'...\n", [s(File)], !IO),
io.open_input(File, OpenResult, !IO),
(
OpenResult = ok(InStream),
consult_until_eof(InStream, !Database, !IO),
io.close_input(InStream, !IO)
;
OpenResult = error(_),
io.format("Error opening file `%s' for input.\n", [s(File)], !IO)
).
:- pred consult_until_eof(io.text_input_stream::in,
database::in, database::out, io::di, io::uo) is det.
consult_until_eof(InStream, !Database, !IO) :-
read_term(InStream, ReadTerm, !IO),
(
ReadTerm = eof
;
ReadTerm = error(ErrorMessage, LineNumber),
io.format("Error reading term at line %d of standard input: %s\n",
[i(LineNumber), s(ErrorMessage)], !IO),
consult_until_eof(InStream, !Database, !IO)
;
ReadTerm = term(VarSet, Term),
database_assert_clause(VarSet, Term, !Database),
consult_until_eof(InStream, !Database, !IO)
).
%---------------------------------------------------------------------------%
% Solve takes a database of rules and facts, a goal to be solved,
% and a varset (which includes a supply of fresh vars, a substitution,
% and names for [some subset of] the variables). It updates the varset,
% producing a new substitution and perhaps introducing some new vars,
% and returns the varset thus updated as the result.
%
% We represent goals simply as terms. We parse (i.e. we discover
% the structure of) the body of each clause every time we interpret
% that clause. Definite logic programs do not allow disjunctions
% in the bodies of clauses, but we do, so for us, each clause is
% a boolean expression built up (using the conjunction operator ","
% and/or the disjunction operator ";") from three kinds of primitives:
% `true', unifications, and calls to user-defined predicates.
%
% Parsing each clause just once, before we put it into the database,
% would be more efficient.
%
% Not looking up the database of user-defined predicates on goals
% whose top-level functor is ,/2, ;/2, true/0 or =/2 would also be
% more efficient, as well as semantically cleaner.
%
:- pred solve(database::in, term::in, varset::in, varset::out) is nondet.
solve(Database, Goal, !VarSet) :-
(
Goal = term.functor(term.atom(", "), [SubGoalA, SubGoalB], _),
solve(Database, SubGoalA, !VarSet),
solve(Database, SubGoalB, !VarSet)
;
Goal = term.functor(term.atom(";"), [SubGoalA, SubGoalB], _),
( solve(Database, SubGoalA, !VarSet)
; solve(Database, SubGoalB, !VarSet)
)
;
Goal = term.functor(term.atom("true"), [], _)
;
Goal = term.functor(term.atom("="), [TermA, TermB], _),
unify_term_pair(TermA, TermB, !VarSet)
;
database_lookup_clause(Database, Goal, ClauseVarSet, Head0, Body0),
rename_apart(ClauseVarSet, [Head0, Body0], [Head, Body], !VarSet),
unify_term_pair(Goal, Head, !VarSet),
solve(Database, Body, !VarSet)
).
%---------------------------------------------------------------------------%
:- pred rename_apart(varset::in, list(term)::in, list(term)::out,
varset::in, varset::out) is det.
rename_apart(NewVarSet, Terms0, Terms, VarSet0, VarSet) :-
varset.merge(VarSet0, NewVarSet, Terms0, VarSet, Terms).
%---------------------------------------------------------------------------%
% unify_term_pair(TermX, TermY, !VarSet):
%
% Unify TermX with TermY, updating the varset if the unification succeeds.
%
% The standard library module `term' contains routines for unifying terms
% based on separate substitutions (maps from variables to terms),
% but here we are using substitutions that are contained in the varset
% itself, so we cannot use those versions.
%
:- pred unify_term_pair(term::in, term::in, varset::in, varset::out)
is semidet.
unify_term_pair(TermX, TermY, !VarSet) :-
(
TermX = term.variable(VarX, _ContextX),
TermY = term.variable(VarY, _ContextY),
( if varset.search_var(!.VarSet, VarX, BindingOfX) then
( if varset.search_var(!.VarSet, VarY, BindingOfY) then
% Both X and Y already have bindings;
% unify the terms they are bound to.
unify_term_pair(BindingOfX, BindingOfY, !VarSet)
else
% X is bound, Y is not. Symmetrical with the opposite case.
apply_rec_substitution(!.VarSet, BindingOfX, SubstBindingOfX),
( if SubstBindingOfX = term.variable(VarY, _) then
true
else
not var_occurs_in_term(VarY, SubstBindingOfX, !.VarSet),
varset.bind_var(VarY, SubstBindingOfX, !VarSet)
)
)
else
( if varset.search_var(!.VarSet, VarY, BindingOfY) then
% Y is bound, X is not. Symmetrical with the opposite case.
apply_rec_substitution(!.VarSet, BindingOfY, SubstBindingOfY),
( if SubstBindingOfY = term.variable(VarX, _) then
true
else
not var_occurs_in_term(VarX, SubstBindingOfY, !.VarSet),
varset.bind_var(VarX, SubstBindingOfY, !VarSet)
)
else
% Both X and Y are unbound variables; bind one to the other.
% It does not matter whether we bind X to Y, or Y to X.
( if VarX = VarY then
true
else
TermY = term.variable(VarY, term_context.dummy_context),
varset.bind_var(VarX, TermY, !VarSet)
)
)
)
;
TermX = term.variable(VarX, _ContextX),
TermY = term.functor(_FunctorY, _ArgTermsY, _ContextY),
unify_var_functor(VarX, TermY, !VarSet)
;
TermX = term.functor(_FunctorX, _ArgTermsX, _ContextX),
TermY = term.variable(VarY, _ContextY),
unify_var_functor(VarY, TermX, !VarSet)
;
TermX = term.functor(FunctorX, ArgTermsX, _ContextX),
TermY = term.functor(FunctorY, ArgTermsY, _ContextY),
FunctorX = FunctorY,
unify_term_pairs(ArgTermsX, ArgTermsY, !VarSet)
).
:- inst term_functor for term/1
---> functor(ground, ground, ground).
% Unify a variable with a term that is known to be a functor
% applied to some argument terms.
%
:- pred unify_var_functor(term.var::in, term::in(term_functor),
varset::in, varset::out) is semidet.
unify_var_functor(VarX, TermY, !VarSet) :-
( if varset.search_var(!.VarSet, VarX, BindingOfX) then
unify_term_pair(BindingOfX, TermY, !VarSet)
else
TermY = term.functor(_FunctorY, ArgTermsY, _ContextY),
not var_occurs_in_terms(VarX, ArgTermsY, !.VarSet),
varset.bind_var(VarX, TermY, !VarSet)
).
:- pred unify_term_pairs(list(term)::in, list(term)::in,
varset::in, varset::out) is semidet.
unify_term_pairs([], [], !VarSet).
unify_term_pairs([TermX | TermXs], [TermY | TermYs], !VarSet) :-
unify_term_pair(TermX, TermY, !VarSet),
unify_term_pairs(TermXs, TermYs, !VarSet).
%---------------------------------------------------------------------------%
% var_occurs_in_term(VarX, TermY, VarSet):
%
% Succeed iff VarX occurs in TermY, either as is,
% or after the substitution in VarSet is applied to TermY.
%
% VarX must not be mapped by the substitution in VarSet.
%
:- pred var_occurs_in_term(var::in, term::in, varset::in) is semidet.
var_occurs_in_term(VarX, TermY, VarSet) :-
(
TermY = term.variable(VarY, _),
(
VarX = VarY
;
varset.search_var(VarSet, VarY, BindingOfY),
var_occurs_in_term(VarX, BindingOfY, VarSet)
)
;
TermY = term.functor(_FunctorY, ArgTermsY, _ContextY),
var_occurs_in_terms(VarX, ArgTermsY, VarSet)
).
% var_occurs_in_terms(VarX, TermsY, VarSet):
%
% Succeed iff VarX occurs in any of the TermsY, either as is,
% or after the substitution in VarSet is applied to TermsY.
%
% VarX must not be mapped by the substitution in VarSet.
%
:- pred var_occurs_in_terms(var::in, list(term)::in, varset::in) is semidet.
var_occurs_in_terms(VarX, [TermY | TermsY], VarSet) :-
(
var_occurs_in_term(VarX, TermY, VarSet)
;
var_occurs_in_terms(VarX, TermsY, VarSet)
).
%---------------------------------------------------------------------------%
% apply_rec_substitution(VarSet, Term0, Term):
%
% Recursively apply substitution to Term0 until no more substitutions
% can be applied, and then return the result in Term.
%
:- pred apply_rec_substitution(varset::in, term::in, term::out) is det.
apply_rec_substitution(VarSet, Term0, Term) :-
(
Term0 = term.variable(Var, _),
( if varset.search_var(VarSet, Var, Replacement) then
% Recursively apply the substitution to the replacement.
apply_rec_substitution(VarSet, Replacement, Term)
else
Term = term.variable(Var, term_context.dummy_context)
)
;
Term0 = term.functor(Name, ArgTerms0, Context),
apply_rec_substitution_to_list(VarSet, ArgTerms0, ArgTerms),
Term = term.functor(Name, ArgTerms, Context)
).
:- pred apply_rec_substitution_to_list(varset::in, list(term)::in,
list(term)::out) is det.
apply_rec_substitution_to_list(_VarSet, [], []).
apply_rec_substitution_to_list(VarSet, [Term0 | Terms0], [Term | Terms]) :-
apply_rec_substitution(VarSet, Term0, Term),
apply_rec_substitution_to_list(VarSet, Terms0, Terms).
%---------------------------------------------------------------------------%
% We store the database just as a list of clauses.
%
% This makes the code simple and readable, but it severely limits its
% performance on anything bigger than toy programs.
%
% It would be more realistic to index the database on the predicate name/arity,
% and subindex on the name/arity of the first argument.
:- type database == list(clause).
:- type clause
---> clause(
clause_vars :: varset,
clause_head :: term,
clause_body :: term
).
:- pred database_init(database::out) is det.
database_init([]).
:- pred database_assert_clause(varset::in, term::in,
database::in, database::out) is det.
database_assert_clause(VarSet, Term, Database, [Clause | Database]) :-
( if Term = term.functor(term.atom(":-"), [H, B], _) then
Head = H,
Body = B
else
Head = Term,
Body = term.functor(term.atom("true"), [], term_context.dummy_context)
),
Clause = clause(VarSet, Head, Body).
% database_lookup_clause(Database, Goal, VarSet, Head, Body):
%
% For each clause in Database whose head may unify with Goal,
% return the representation of that clause: its varset, head and body.
%
% Since our database has no indexing, we ignore the goal, and return
% *all* the clauses.
%
:- pred database_lookup_clause(database::in, term::in,
varset::out, term::out, term::out) is nondet.
database_lookup_clause(Database, _Goal, VarSet, Head, Body) :-
list.member(Clause, Database),
Clause = clause(VarSet, Head, Body).
%---------------------------------------------------------------------------%