0

Let's say I have the following string:

if(something){ /* do stuff */ }else if(something_else){ /* do other stuff */ }else{ /* do stuff once more *}

What I want is to verify that the if syntax in this string is correct. For example make sure that the else{} statement is not before the else if(){} statement or that a bracket is not left open etc...I don't care about the code inside the brackets. The string could have any number of "if else" statements and it could have or not have an "else" statement.

I have already writen a function to check it but if there is a library or a script for stuff like this I 'd prefer using it.

Anonymous
  • 4,470
  • 3
  • 36
  • 67
  • This seems a bit different because its trying to check a single statement, not compile a complete class? – DNA Mar 27 '15 at 10:02
  • exactly. I'm trying to verify the syntax in a small orphan piece of pseudo code of my own making. – Anonymous Mar 27 '15 at 10:04

4 Answers4

0

You could try to build your own parser with http://www.antlr.org/.

If you however do not care of the code inside the brackets, then this might be overkill.

Gregor Raýman
  • 3,051
  • 13
  • 19
0

You can use the Java Scripting API. There are several scripting engines, for JavaScript, but also for BeanShell, a simplified Java, just suitable for such fragmentary code.

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("BeanShell");
try {
    engine.eval("int if = -1;");
} catch (ScriptException e) {
    grrrr(e);
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • I'm trying your way, I imported the ScriptEngineManager library but when your code snippet runs it throws a null exception at engine = factory.getEngineByName("BeanShell"); Could you please tell me how to import BeanShell to ScriptEngineManager? – Anonymous Mar 27 '15 at 11:01
  • [BeanShell](http://www.beanshell.org/intro.html) is a long established script engine. I did not look at it for many years. It is listed [here](https://java.net/projects/scripting/sources/svn/show/trunk/engines) along other languages. BeanShell itself has good documentation and mentions embedding. You must register the factory for BeanShell I saw - sorry. I am afraid the BeanShell scripting might be a second level project. – Joop Eggen Mar 27 '15 at 12:02
0

If you just want to check syntax, you can use some existing Java code parser like JavaParser.

Example:

    final String classText = text + "\n" + "public class Dummy{}";
    final StringReader reader = new StringReader(classText);
    final CompilationUnit compilationUnit = JavaParser.parse(reader, true);
lexicore
  • 42,748
  • 17
  • 132
  • 221
-1

While building an own parser is the most complete solution, as Gregor wrote, limited syntax checking can be performed with regular expressions.

pkalinow
  • 1,619
  • 1
  • 17
  • 43