:- set_flag(print_depth,100).
:- nodbgcomp.
:- dynamic(proc/2).            % Compiler directives. Be sure   
:- set_flag(all_dynamic, on).  % you load this file first! 

  /*            An RGolog interpreter in Prolog.

     This is the on-line version, using cut to enforce commitment, as
     described in Section 8.6.2.   */

:- op(800, xfy, [&]).   % Conjunction 
:- op(850, xfy, [v]).   % Disjunction 
:- op(870, xfy, [=>]).  % Implication
:- op(880,xfy, [<=>]).  % Equivalence
:- op(950, xfy, [:]).   % Action sequence 
:- op(960, xfy, [#]).   % Nondeterministic action choice 

doR(A,Rules,S,S1) :- primitive_action(A), poss(A,S), !, 
                     exoTransition(do(A,S),SE), !, doR(Rules,Rules,SE,S1).
doR(E1 : E2,Rules,S,S1) :- doR(E1,Rules,S,S2), doR(E2,Rules,S2,S1).
doR(?(P),Rules,S,S) :- holds(P,S).
doR(E1 # E2,Rules,S,S1) :- doR(E1,Rules,S,S1) ; doR(E2,Rules,S,S1).
doR(if(P,E1,E2),Rules,S,S1) :- doR((?(P) : E1) # (?(-P) : E2),Rules,S,S1).
doR(star(E),Rules,S,S1) :- S1 = S ; doR(E : star(E),Rules,S,S1).
doR(while(P,E),Rules,S,S1):- doR(star(?(P) : E) : ?(-P),Rules,S,S1).
doR(pi(V,E),Rules,S,S1) :- sub(V,_,E,E1), doR(E1,Rules,S,S1).
doR(E,Rules,S,S1) :- proc(E,E1), doR(E1,Rules,S,S1).

% sub(Name,New,Term1,Term2): Term2 is Term1 with Name replaced by New. 

sub(X1,X2,T1,T2) :- var(T1), T2 = T1.
sub(X1,X2,T1,T2) :- not var(T1), T1 = X1, T2 = X2.
sub(X1,X2,T1,T2) :- not T1 = X1, T1 =..[F|L1], sub_list(X1,X2,L1,L2),
                    T2 =..[F|L2].
sub_list(X1,X2,[],[]).
sub_list(X1,X2,[T1|L1],[T2|L2]) :- sub(X1,X2,T1,T2), sub_list(X1,X2,L1,L2).

/* The holds predicate implements the revised Lloyd-Topor
   transformations on test conditions.  */

holds(P & Q,S) :- holds(P,S), holds(Q,S).
holds(P v Q,S) :- holds(P,S); holds(Q,S).
holds(P => Q,S) :- holds(-P v Q,S).
holds(P <=> Q,S) :- holds((P => Q) & (Q => P),S).
holds(-(-P),S) :- holds(P,S).
holds(-(P & Q),S) :- holds(-P v -Q,S).
holds(-(P v Q),S) :- holds(-P & -Q,S).
holds(-(P => Q),S) :- holds(-(-P v Q),S).
holds(-(P <=> Q),S) :- holds(-((P => Q) & (Q => P)),S).
holds(-all(V,P),S) :- holds(some(V,-P),S).
holds(-some(V,P),S) :- not holds(some(V,P),S).  /* Negation */
holds(-P,S) :- isAtom(P), not holds(P,S).     /* by failure */
holds(all(V,P),S) :- holds(-some(V,-P),S).
holds(some(V,P),S) :- sub(V,_,P,P1), holds(P1,S).

/* The following clause treats the holds predicate for non fluents, including
   Prolog system predicates. For this to work properly, the GOLOG programmer
   must provide, for all fluents, a clause giving the result of restoring
   situation arguments to situation-suppressed terms, for example:
         restoreSitArg(ontable(X),S,ontable(X,S)).             */

holds(A,S) :- restoreSitArg(A,S,F), F ;
              not restoreSitArg(A,S,F), isAtom(A), A.

isAtom(A) :- not (A = -W ; A = (W1 & W2) ; A = (W1 => W2) ;
    A = (W1 <=> W2) ; A = (W1 v W2) ; A = some(X,W) ; A = all(X,W)).

restoreSitArg(poss(A),S,poss(A,S)).
