How could I split a script into its single statements?

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

How could I split a script into its single statements?

Chris
Hi

I need to split a whole script into its single statements. For example this String:
String script = "int n=2;\n" +
        "for(int i=0;i<3;i++) {" +
        "  print(\"lala\");" +
        "}\n" +
        "print(n);";
       
Should get an array of
[0]:int n=2;
[1]:for(int i=0;i<3;i++) {
         print("lala");
     }
[2]:print(n);

I have played with bsh.Parser but this dont get me anyway - so far ... do you have an idea how I could solve my problem? I want to implement something like a precomplier. So I do replacements for special strings. Therefore a variable assignment have to be visible to the next statement. So I need to prepare and eval one statement after the next one. Any ideas?

Thanks
Chris
Reply | Threaded
Open this post in threaded view
|

Re: How could I split a script into its single statements?

Peter
You could use the (generated) bsh.Parser class for this. There is a source example in the java-doc of this class.

--Peter
Reply | Threaded
Open this post in threaded view
|

Re: How could I split a script into its single statements?

Peter
In reply to this post by Chris
Sorry, that was a bit fast ;)

You must implement a "node visitor" to achieve your goal. Currently there is no 'nice way' to distinguish the different node types, but you can read the source or use the method "dump" of "bsh.SimpleNode" to look which kind of nodes are produced. E.g. the above example will evaluate to:

TypedVariableDeclaration
 Type
  PrimitiveType
 BSHVariableDeclarator n
  PrimaryExpression
   Literal

(to transform this to classnames prepend "bsh.BSH").

You could request a feature to support your use case more smoothly at http://code.google.com/p/beanshell2 (in the "issues" section).

--Peter
Reply | Threaded
Open this post in threaded view
|

Re: How could I split a script into its single statements?

Chris
Thanks Peter!

I have ended up to inject my preparsed code directly after the last index of } or ; before my code-replace-pattern (or defaulting to position 0). This is for sure not the very best solution but it is working.

I will think about opening an issue ... i mean if this is a lot of work for you and the feature is just for one user ...

Thank you very much
Chris
Reply | Threaded
Open this post in threaded view
|

Re: How could I split a script into its single statements?

Chris
I have discoverd big issues on recursive expressions and on commented code parts ... so I have decided to file a issue.

Thank you very much!
Cheers
Chris