% Un traducteur de la syntaxe XML-Prolog <==> représentation MIL
%
%----------------------------------------------------------------------------------------

:- use_module('mil.pl').

%--- le prédicat-maître tradXML(XMLterm, MILterm)

tradXML( 
	[element('Prog', [], [element('Variables', [], LV), element('Main', [], LInst)])],
	progMIL(MLV, MLInst) 
) :- 
	tradDecl(LV, MLV), tradSeq(LInst, MLInst).
	
%--- tradDecl(LV, MLV)
tradDecl([], []).
tradDecl([element('Var',[name=A],[]) | SLV], [A | SMLV]) :- atom(A), tradDecl(SLV, SMLV).
	
%--- tradSeq([LInst, MILterm)
tradSeq([], []).
tradSeq([XInst | XSInst], [Inst | SInst]) :- tradInst(XInst, Inst), tradSeq(XSInst, SInst).

%--- tradInst(XInst, Inst)

tradInst(element('Space', [], []), espace).

tradInst(element('Newline', [], []), ligne).

tradInst(element('Read', [], [element('Var', [name=A], [])]), lire A) :- atom(A).

tradInst(element('Write', [], [XExpAr]), ecrire ExpAr) :- tradExpAr(XExpAr, ExpAr).

tradInst(element('Assignment', [], [element('Var', [name=A], []), XExpAr]), A := ExpAr) :-	
	atom(A), tradExpAr(XExpAr, ExpAr).
	
tradInst(
	element('Loop', [], [XTest, element('Sequence', [], XCorps)]), 
	tantque(MTest, MCorps)
) :- 
	tradExpBool(XTest, MTest), tradSeq(XCorps, MCorps).

tradInst(element('Conditional', [], [XTest, 
				element('Sequence', [], XLVrai), 
				element('Sequence', [], XLFaux) ]
				), 
		si(MTest, MLVrai, MLFaux)
) :- 
	tradExpBool(XTest, MTest), tradSeq(XLVrai, MLVrai), tradSeq(XLFaux, MLFaux).

%--- tradExpAr(XExpAr, ExpAr)

tradExpAr(element('Cst', [val=XV], []), V) :- var(V), atom_number(XV, V).
tradExpAr(element('Cst', [val=XV], []), V) :- number(V), atom_number(XV, V).

tradExpAr(element('VarExp', [], [element('Var', [name=N], [])]), N) :- atom(N).

% énumération des opérateurs en vue de la réversibilité
tradExpAr(element('Bin', [op= '+'], [XG, XD]), G+D) :- tradExpAr(XG, G), tradExpAr(XD, D).
tradExpAr(element('Bin', [op= '*'], [XG, XD]), G*D) :- tradExpAr(XG, G), tradExpAr(XD, D).
tradExpAr(element('Bin', [op= '-'], [XG, XD]), G-D) :- tradExpAr(XG, G), tradExpAr(XD, D).
tradExpAr(element('Bin', [op= '/'], [XG, XD]), G/D) :- tradExpAr(XG, G), tradExpAr(XD, D).

%--- tradExpBool(XExpBool, ExpBool) - idem
tradExpBool(element('Test', [op='='], [XG, XD]), G=D) :- tradExpAr(XG, G), tradExpAr(XD, D).
tradExpBool(element('Test', [op='<'], [XG, XD]), G<D) :- tradExpAr(XG, G), tradExpAr(XD, D).
tradExpBool(element('Test', [op='>'], [XG, XD]), G>D) :- tradExpAr(XG, G), tradExpAr(XD, D).
tradExpBool(element('Test', [op='<='], [XG, XD]), G<=D) :- tradExpAr(XG, G), tradExpAr(XD, D).
tradExpBool(element('Test', [op='>='], [XG, XD]), G>=D) :- tradExpAr(XG, G), tradExpAr(XD, D).
tradExpBool(element('Test', [op='<>'], [XG, XD]), G<>D) :- tradExpAr(XG, G), tradExpAr(XD, D).

%---------------

:- use_module(library(sgml)).

test :- load_structure('../ExCours1/qrd.xml', X, [dialect(xml),space(remove)]),
	tradXML(X, T), write(T), prog3(T).