/****************************************************************

 File: topdown_generator_simple.pl

 Kristina Striegnitz, 2003.

 Usage: Consult ourEngSem_simplified.pl, unify_silent.pl

        generate_topdown(+logical formula, ?parse tree)

        E.g. generate_topdown(exists(X,woman(X),dance(X)),P)

 Nodes on the right hand side of rules are expanded in an left to
 right order. 

 There are some write commands in the code that will tell you which
 nodes are expanded when if you uncomment them.

****************************************************************/

:- op(700,xfx,--->).


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% apply_rules_topdown(+node/feature structure)
%%% Applies rules in a topdown fashion by unifying the incoming
%%% feature structure with the left hand side of the rule and then
%%% trying to expand the right hand side.

%%% Test whether we can apply lexical rules.
apply_rules_topdown(FS) :-
	lex(_Word, WordFS),
	unify_silent(WordFS,FS,_).

%%% Test whether we can apply phrasal rules.
apply_rules_topdown(FS) :-
	LHS ---> RHS,
	unify_silent(FS,LHS,_),
	expand_rhs(RHS).


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% expand_rhs(+list of nodes)
%%% List processing predicate that applies apply_rules_topdown to each
%%% node in the list. It selects the first node in the list, applies
%%% apply_rules_topdown to it and then makes a recursive call with the
%%% remainder of the list.

expand_rhs([]).
expand_rhs([FS|Rest]) :-
	%%% \+ \+ (numbervars(FS,0,_),write('Expanding node '),write(FS)),nl,nl,
	apply_rules_topdown(FS),
	%%% write('Generated parse tree '),val(syn,P,Node,_),write(P),nl,nl,
	expand_rhs(Rest).


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% generate_topdown(+logical formula, ?parse tree)
%%% We build the initial feature structure 'StartFS' in which only the
%%% cat feature and the semF.sem feature are assigned a value. At the
%%% end (if apply_rules_topdown is successfull) this feature structure
%%% will be further specified and also contain a syntactic structure
%%% corresponding to the input semantics. We return this syntactic
%%% structure.

generate_topdown(SemInput, Parse) :-
	StartFS = [cat:s, semF:[sem:SemInput|_] |_],
	%%% \+ \+ (numbervars(StartFS,0,_),write('Expanding node '),write(StartFS)),nl,nl,
        apply_rules_topdown(StartFS),
	val(syn,Parse,StartFS,_).


/**********************************************************************
                    That's all, folks!
***********************************************************************/
