Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to write a Compiler with Javascript?

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

like image 239
Alex Yeung Avatar asked Sep 08 '11 05:09

Alex Yeung


People also ask

Which compiler is used for JavaScript?

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.

Is JavaScript a compiler or interpreter language?

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.


2 Answers

Yes, it's very much possible using Jison.

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. :)

like image 83
Robin Maben Avatar answered Oct 04 '22 01:10

Robin Maben


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.

like image 42
rsp Avatar answered Oct 03 '22 23:10

rsp