Parsing and replacing Javascript identifiers with Rhino in Java

Posted by Parhs on Stack Overflow See other posts from Stack Overflow or by Parhs
Published on 2010-04-19T01:06:25Z Indexed on 2010/04/19 1:43 UTC
Read the original article Hit count: 300

Filed under:
|
|

Suppose I let the user to write a condition using Javascript, the user can write conditions to perform a test and return true or false. E.g.:

INS>5 || ASTO.valueBetween(10,210)

I want to find which variables are used in the script that the user wrote. I tried to find a way to get the identifier names in Java. The Rhino library didn't help a lot. However I found that via handling exceptions I could get all the identifiers. So this problem is solved.

So everything is great, but there is one little problem. How can I replace these identifiers with a numeric identifier? E.g. INS should be _234 and ASTO should be _331.

INS and ASTO etc are entities in my database. I want to replace them, because the name may change. I could do it using a replace but this isn't easy because:

  1. It should be reversible. E.g. ASTO to _234 and _234 to ASTO again.
  2. Replacing _23 with MPLAH may also replace _234. This could be fixed with regexp somehow.
  3. What if _23 is in a comment section? Rare to happen, but possible /* _23 fdsafd ktl */. It should also be replaced.
  4. What if it is a name of a function? E.g. _32() {}. Also rare, but it shouldn't be replaced.
  5. What if it is enclosed in "" or ''?

I am sure that there are a lot more cases. Any ideas?

© Stack Overflow or respective owner

Related posts about rhino

Related posts about JavaScript