1:- include(tokenizer).    2:- set_prolog_flag(double_quotes,chars).    3:- initialization(main).    4
    5
    6%To do:
    7%Fix the precedence of '-' and '+'. Try to make the precedence equal for both of these operators.
    8
    9main :- tokenize("return a1+b1; const r = g*b+g*2; r = 2-1+a; r = 2+1-a;",Result),atoms_to_codes(Result1,Result),parse(Result1,Result2),writeln(Result2).
   10
   11atoms_to_codes([],[]).
   12atoms_to_codes([A|B],[A1|B1]) :- atom_chars(A,A1),atoms_to_codes(B,B1).
   13
   14parse(List,Result) :-
   15	is_expr(A),is_expr(B),
   16	(
   17	member(To_parse,[
   18		['[',A,']'],
   19		['(',A,')'],
   20		['{',A,'}'],
   21		[A,'.',B],
   22		
   23		%the order of operations is wrong here
   24		[A,'*',B],
   25		[A,'/',B],
   26		[A,'+',B],
   27		[A,'-',B],
   28		
   29		[A,'!==',B],
   30		[A,'===',B],
   31		[A,',',B],
   32		['else','if',['(',A,')'],['{',B,'}']],
   33		['if',['(',A,')'],['{',B,'}']],
   34		['while',['(',A,')'],['{',B,'}']],
   35		['else',['{',A,'}']],
   36		['return',A,';'],
   37		['const',A,'=',B,';'],
   38		['let',A,'=',B,';'],
   39		['var',A,'=',B,';'],
   40		[A,'=',B,';'],
   41		[A,'*=',B,';'],
   42		['function',['(',A,')'],['{',B,'}']],
   43		['function',_,['(',A,')'],['{',B,'}']]
   44	]),parse(To_parse,List,Result1)
   45	),parse(Result1,Result);
   46	(
   47		Result=List
   48	).
   49
   50is_expr(A) :- dif(A,'='),dif(A,'*'),dif(A,'['),dif(A,']'),dif(A,'('),dif(A,')').
   51
   52
   53parse(Sublist,List,Result) :-
   54	replace(Sublist,[Sublist],List,Result).
   55
   56replace(ToReplace, ToInsert, List, Result) :-
   57    once(append([Left, ToReplace, Right], List)),
   58    append([Left, ToInsert, Right], Result)