CSc 4340/6340, Introduction to Compilers
Fall 2009
Prolog Code for Parser Algorithms

Prolog Programs for
  1. (td.pl) top-down parsing algorithms

Sample Run:

[raj@tinman parserPrologPrograms]$ more 428.pl
%
terminal('+').
terminal('*').
terminal('(').
terminal(')').
terminal(id).
terminal(nil).
%
nonterminal(e).
nonterminal(eprime).
nonterminal(t).
nonterminal(tprime).
nonterminal(f).
%
start(e).
%
p(e,[t,eprime]).
p(eprime,[nil]).
p(eprime,['+',t,eprime]).
p(t,[f,tprime]).
p(tprime,[nil]).
p(tprime,['*',f,tprime]).
p(f,[id]).
p(f,['(',e,')']).
[raj@tinman parserPrologPrograms]$ pl
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.6.64)
Copyright (c) 1990-2008 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

1 ?- ['428.pl'].
% 428.pl compiled 0.00 sec, 4,408 bytes
true.

2 ?- ['td.pl'].
% td.pl compiled 0.00 sec, 12,688 bytes
true.

3 ?- first(e,L).
L = ['(', id] .

4 ?- firstString([eprime,id,'('],L).
L = [+, nil, id] .

5 ?- follow(f,L).
L = [*, $, ')', +] .

6 ?- follow(eprime,L).
L = [$, ')'] .

7 ?- halt.
[raj@tinman parserPrologPrograms]$ pl
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.6.64)
Copyright (c) 1990-2008 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

1 ?- ['td.pl'].
% td.pl compiled 0.00 sec, 23,008 bytes
true.

2 ?- ['428.pl'].
% 428.pl compiled 0.00 sec, 11,776 bytes
true.

3 ?- predictiveParse([id,+,id,$]).
----------------------------------------
Predictive Parsing Table
----------------------------------------
M[e,(] = [e, [t, eprime]]
M[e,id] = [e, [t, eprime]]
M[eprime,+] = [eprime, [+, t, eprime]]
M[f,(] = [f, [ (, e, )]]
M[f,id] = [f, [id]]
M[t,(] = [t, [f, tprime]]
M[t,id] = [t, [f, tprime]]
M[tprime,*] = [tprime, [*, f, tprime]]
M[eprime,$] = [eprime, [nil]]
M[eprime,)] = [eprime, [nil]]
M[tprime,$] = [tprime, [nil]]
M[tprime,)] = [tprime, [nil]]
M[tprime,+] = [tprime, [nil]]
----------------------------------------
Production rules in top-down LM parse
----------------------------------------
[e, [t, eprime]]
[t, [f, tprime]]
[f, [id]]
[tprime, [nil]]
[eprime, [+, t, eprime]]
[t, [f, tprime]]
[f, [id]]
[tprime, [nil]]
[eprime, [nil]]
----------------------------------------
true .

4 ?- halt.
[raj@tinman parserPrologPrograms]$