0

This is a very basic question. I tried searching SO, but couldn't get any solid answer. Sorry if it's really basic.

I'm trying to write a plugin/library to convert Javascript into Apache Jelly.

So the idea is to write Javascript code, which will be converted to Jelly code.

example: Javascript like code:

if(x == 1){
  print("inside if");
}

Apache converted code:

  <j:if test="x=1">
     inside if
  </j:if>

The question is, how do I parse the entire Javascript code and replace it with some other code. I did have a look at Jison but that basically is a parse generator, which parses the values AND interpret them. I feel using jison is kinda overhead for my task.

Any idea what I can use to achieve what I'm trying to do?

Edit 1: Yes, there is a Javascript top down parser at JSLint, but any easy way to specify what needs to be replaced? for example, in the above code - replacing if loop with <j:if>

4
  • If you want to parse JavaScript with JavaScript, the JSLint source code might give you some ideas. Commented Sep 15, 2013 at 15:54
  • Thanks, How do I replace what I just parsed? Commented Sep 15, 2013 at 15:55
  • A program that interprets JavaScript source code to discover the program structure it describes is called a JavaScript parser. That's what you have to write. Commented Sep 15, 2013 at 15:56
  • 2
    You generate the new code while parsing the original. JSLint aim is to validate JS code, you'll have read that code, understand it, and adapt it for your own needs. I don't think you can achieve what you're looking for without understanding how the a parser works. Commented Sep 15, 2013 at 15:56

1 Answer 1

3

You probably misunderstood the Jison calculator example. You don't have to execute any code in the parser, it's just the calculator that does that to illustrate the concept. You can put any stuff you want in a parser action, for example, to generate your xml format the code might be like:

 `if` condition block:
      { $$ = '<j:if test=' + $2 + '>' + $3 + '</if>' }

Another (and better) option is to use a abstract JS parser to build an AST and generate XML by walking this tree. That has an advantage of decoupling parsing from code generation + you can simply utilize an already made grammar like https://github.com/cjihrig/jsparser.

Sign up to request clarification or add additional context in comments.

1 Comment

Just wanted to add, There is a beautiful parser from Mozilla called Esprima, better than the one given by thg435.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.