Use expand_term/2 with file for dcg translation

79 Views Asked by At

I'm trying to "translate" a file that contains dcg's. in particular i am trying to transform all dcg into normal definite clauses using expand_term/2, however i would like to avoid manually translating all dcgs, so i would try to translate all clauses of the file at once (e.g. passing the whole file) . is there any way to do it?

for example, suppose we have a temp.pl file which contains some dcg:

a(X,Y) --> b(X), c(Y).
d([A | Ax]) --> b(A).
....
....

instead of using expand_term/2 individually for each term, like:

?- expand_term((a(X,Y) --> b(X), c(Y)), Clause).
Clause = [(:-non_terminal(user:a/4)),  (a(X, Y, _A, _B):-b(X, _A, _C), c(Y, _C, _B))].

And then replace the dcg with definite clause in file.

I would like to pass for example the whole file (to a clause for example ) which contains the dcg, and translate all the dcg at once and print in a file or as an output, I don't know.

1

There are 1 best solutions below

2
Guy Coder On

If I understand your question correctly then you are missing the obvious which is that what you seek is already in the SWI-Prolog code. The translation is done as the module is loaded. If you use listing/1 on a DCG predicate the code will list as normal Prolog and not DCGs.

See dcg.pl
load.pl
expand.pl
apply_macros.pl


Demonstration of listing/1 with DCG

Directory: C:/Users/Groot
File: example.pl (Based on this SO answer )

:- module(example,
    [
        monlangage/2
    ]).

:- set_prolog_flag(double_quotes, chars).

monlangage --> "ab" | "a", monlangage.

Example run

Welcome to SWI-Prolog (threaded, 64 bits, version 8.5.3)
...

?- working_directory(_,'C:/Users/Groot').
true.

?- [example].
true.

?- listing(example:_).

monlangage(A, B) :-
    (   A=[a, b|B]
    ;   A=[a|C],
        monlangage(C, B)
    ).
true.

Notice that the source code is DCG with --> and the listing is not DCG with :-. Also notice that the rewritten clause has two extra arguments.