Is it possible to use Javascript to write a compiler that can support other kind of language as scripting?
Let's say, I have a piece of HTML.
<script language="cpp" id="cppScriptBlock" EntryPoint="main">
int main() {
cout << "<h1>CPPHeader</h1>";
}
</script>
<script language="java" id="javaScriptBlock" EntryPoint="MyJavaClass">
public class MyJavaClass {
public final void main() {
java.lang.System.out.println("<h1>JavaHeader</h1>");
}
}
</script>
<script language="csharp" id="csharpScriptBlock" EntryPoint="MyCSharpClass ">
public class MyCSharpClass {
public static void Main() {
System.Console.WriteLine("<h1>CSharpHeader</h1>");
}
}
</script>
<script language="javascript">
$("#cppScriptBlock").compileAndRun();
$("#javaScriptBlock").compileAndRun();
$("#csharpScriptBlock").compileAndRun();
</script>
And finally generate the following HTML
<h1>CPPHeader</h1>
<h1>JavaHeader</h1>
<h1>CSharpHeader</h1>
Is it possible?
Alex
Heart of the engine. As we discussed earlier, JavaScript is interpreted by an interpreter named Ignition as well as compiled by a JIT optimizing compiler named TurboFan.
JavaScript (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for Web pages, but it's used in many non-browser environments as well.
It generates a JavaScript parser based on the language constructs you define.
Jison takes a context-free grammar as input and outputs a JavaScript file capable of parsing the language described by that grammar. You can then use the generated script to parse inputs and accept, reject, or perform actions based on the input.
-- from the documentation
PS: CoffeeScript! was also created using this. :)
Yes, it is possible. But instead of writing your parser by hand I would encourage you to use a good parser generator.
For example ANTLR by Terence Parr is a very powerful parser generator that has a JavaScript target. It works in environments supporting ECMAScript 5.1. (tested in Firefox, Safari, Chrome, Internet Explorer and Node.js). It is open source (BSD license) with extensive documentation and a very good book available.
Using a tool like this, instead of writing your own parser, you write a grammar and the parser is generated for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With