%
% mapping CIF-code to ICode
%
% replace all generate/5 of result type integer/float/string/boolean with restrict/4
%

:- module(cif2i,[cif2i/2]).

:- [prolog_detect].			%load the Prolog detecting module

:- prolog_detect:prolog(Prolog),
	(	(	Prolog=sicstus,
			!,
			use_module(library(lists))
		);
		(	Prolog=pfdm,
			!,
			use_module(library(lists))
		);
		Prolog=eclipse;
		Prolog=swi;
		(	write('*** Unsupported Prolog system ***'),
			nl,
			!,
			fail
		)
	).


cif2i([],[]) :-
	!.

cif2i([Cif|Cifs],[I|Is]) :-
	!,
	cif2i(Cif,I),
	cif2i(Cifs,Is).

cif2i(Cif,I) :-
	Cif=generate(Fname,Arg_types,Args,Result_type,Result),		%replace with generate/5
	member(Result_type,[integer,float,boolean,string]),		%one of the scalar types
	!,
	I=restrict(Fname,Arg_types,Args,Result).

cif2i(Cif,Cif) :-
	Cif=generate(_,_,_,_,_),
	!.

cif2i(Cif,I) :-
	Cif=restrict_subquery(Generator,Set,Predicate),			%a restrict_subquery/3
	!,
	cif2i(Set,Set_in_i),						%recursively work on G
	cif2i(Predicate,Predicate_in_i),				%and P
	I=restrict_subquery(Generator,Set_in_i,Predicate_in_i).

cif2i(Cif,I) :-
	Cif=generate_subquery(Gen_type,Gen_var,Sub,Aux1,Aux2),		%a generate_subquery/5
	!,
	cif2i(Sub,Sub_in_i),						%recursively work on it
	cif2i(Aux1,Aux1_in_i),
	cif2i(Aux2,Aux2_in_i),
	I=generate_subquery(Gen_type,Gen_var,Sub_in_i,Aux1_in_i,Aux2_in_i).

cif2i(Cif,I) :-
	Cif=expression(Gen,Req,Agg,Set),		%a expression/4
	!,
	cif2i(Set,Set_in_i),				%work on the set icode
	I=expression(Gen,Req,Agg,Set_in_i).

cif2i(Cif,I) :-
	Cif=logical_or(Lhs,Rhs),		%logical_or/2
	!,
	cif2i(Lhs,Lhs_in_i),
	cif2i(Rhs,Rhs_in_i),
	I=logical_or(Lhs_in_i,Rhs_in_i).

cif2i(Cif,I) :-
	Cif=logical_and(Lhs,Rhs),		%logical_and/2
	!,
	cif2i(Lhs,Lhs_in_i),
	cif2i(Rhs,Rhs_in_i),
	I=logical_and(Lhs_in_i,Rhs_in_i).

cif2i(Cif,I) :-
	Cif=logical_not(X),			%logical_not/1
	!,
	cif2i(X,X_in_i),
	I=logical_not(X_in_i).

cif2i(Cif,Cif).					%all the rest

