Universal-transpiler is a source-to-source compiler that translates a subset of several programming languages into several others. It is also able to translate several metasyntax notations, such as EBNF and ABNF.
The online version of this translator is written in JavaScript, but an experimental version is also being written in Prolog.
This is some JavaScript code:
function add(a,b){
var g = [3,4,5];
return a+b+(g[0])+(g.length);
}
function divide(a,b){
return a/b;
}
and this is the Java code that it generates:
public static Object add(Object a,Object b){
Object g=new ArrayList<>(Arrays.asList(3,4,5));
return a+b+(g.get(0))+(g.length);
}
public static Object divide(Object a,Object b){
return a/b;
}
This translator can convert many languages into many others:
The Prolog translator is still unfinished and experimental. You can install the package by typing pack_install(transpiler)
in the SWI-Prolog console.
Now, you can use the translator to convert JavaScript source code into Lua:
:- use_module(library(transpiler)).
:- set_prolog_flag(double_quotes,chars).
:- initialization(main).
main :-
translate("function add(a,b){return a + b;}",javascript,lua,X),
atom_chars(Y,X),
writeln(Y).
A limited number of translation rules are provided here, but you can easily add your own rules to transpiler.pl
.
This is a simplified version of one of its translation rules, implementing the sine function:
%The type of this expression is double.
parentheses_expr(Data,double,sin(Var1_)) -->
{
%The parameter of the sine function can be an integer or double.
Var1 = expr(Data,double,Var1_)
},
langs_to_output(Data,sin,[
['java','javascript']:
("Math",ws,".",ws,"sin",ws,"(",ws,Var1,ws,")"),
['lua','python']:
("math",python_ws,".",python_ws,"sin",python_ws,"(",python_ws,Var1,python_ws,")"),
]).
Here is an automatically-generated list of features that have not yet been implemented in this translator.
There are several other source-to-source compilers and code generators that are similar to this one.
JTransc compiles Java, Kotlin, and Scala into several other programming languages. Pandoc is a universal document converter
This universal code generator is one example.