Prev Next Up Home Keys Figs Search New

Parser in C

Appeared in Volume 8/1, February 1995

Keywords: compilers.

kdb@elis.rug.ac.be
Koen De Bosschere
5th September 1994

Aur lie Bechina wrote:
I'm new in compiler building and would like to know if there is a parser in C for the language Prolog. Anyone know where I can get this source code?

The C-source for the Prolog parser of BinProlog is available from:
ftp://ftp.elis.rug.ac.be/pub/prolog

It parses the ISO-Prolog syntax as defined in the current draft ISO standard.

ok@goanna.cs.rmit.oz.au
Richard A. O'Keefe
15th September 1994

By far the best Prolog parser in C is the one in C Prolog, from EdCAAD, University of Edinburgh.

If you are willing to accept the (very minor) restriction on operators that C Prolog imposes (it has to be possible to disambiguate each possible operator with one token of lookahead, which is almost always true), it is actually very very easy to write a Prolog parser in C. It is, indeed, much easier to do it directly in C than to use Yacc. If you make the serious mistake of thinking of Prolog syntax as "difficult" (as the ISO Prolog committee seem to have done), you may have a rough time, but if you just remember that Prolog is basically an operator precedence language, and like other operator precedence languages lends itself beautifully to left-corner parsing, you'll have no trouble.

More important is the question, Why do you want a parser in C? The easy way to parse Prolog is to use read/1 in a Prolog program. This is especially important because a really good Prolog compiler would do well to handle definite clause grammar rules and any user-defined macro processing that the user may have plugged into term_expansion/2. What you want to do is:

my_compile(File) :-
  see(File),
  repeat,
    read(Term),
    expand_term(Term, Expansion),
    (   Expansion == end_of_file
    ;   Expansion = [_|_] ->
        member(Clause, Expansion),
        give_to_compiler(Clause),
        fail

;/* Expansion is not end_of_file and not a list */ give_to_compiler(Expansion), fail ), !, seen.

give_to_compiler/1 can either use your foreign function interface to transmit the clause to C code running in the same address space, or it can write it to standard output in some suitably predigested form so that the Prolog part acts as a preprocessor.

It is important to realise that a "Prolog" compiler that only supports vanillia Prolog without definite clause grammar and term_expansion/2 support is about as useful as a "C" compiler that lacks any preprocessing facilities and half its libraries.

In fact, the real easy way to get a Prolog parser written in C is to pick up a copy of WAMCC (a Prolog to C compiler). It really does compile Prolog source code to C code, which a C compiler can compile and a UNIX system can run.

Prev Next Up Home Keys Figs Search New