Search code examples
prologvisual-prolog

handle error in prolog


/**************************
Assignment Statment Module
**************************/
assgnStmnt(Clist) :-
        Clist = [H|T], id(H), conc(Exp, [';'|AnotherStmnt], T), Exp = [Op|Rem], Op = '=', expr(Rem), assgnStmnt(AnotherStmnt),!
        ;
        Clist = [], !.

This code is to parse assignment statement in complier. But i need to output to user where's the syntax error in his code.

like : if he entered : x = x + 1, I want to output that expected ';' not found.

How can i do that ???


Solution

  • Technically depends from your grammar, but if we assume you already know where error productions will go, you could code this way:

    assgnStmnt(Clist) :-
        Clist = [H|T],
        id(H),
        conc(Exp, [StmntSep|AnotherStmnt], T),
        Exp = [Op|Rem],
        Op = '=',
        expr(Rem),
        expected(StmntSep, ';'), % the right position depends on grammar
        assgnStmnt(AnotherStmnt),
        !
        ; Clist = [].
    
    expected(Token, Token) :- !.
    expected(Wrong, Token) :-
        format('expected ~w, found ~w~n', [Token, Wrong]),
        fail. % fail here depends on error recovery strategy
    

    test:

    ?- assgnStmnt([x,=,x+1,';',x,=,x+1,';']).
    true.
    
    ?- assgnStmnt([x,=,x+1,';',x,=,x+1]).
    expected ;, found x
    expected ;, found =
    expected ;, found x+1
    false.