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.

2
  • This seems a bit different because its trying to check a single statement, not compile a complete class? Commented Mar 27, 2015 at 10:02
  • exactly. I'm trying to verify the syntax in a small orphan piece of pseudo code of my own making. Commented Mar 27, 2015 at 10:04

4 Answers 4

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.

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

Comments

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);
}

2 Comments

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?
BeanShell is a long established script engine. I did not look at it for many years. It is listed here 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.
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);

Comments

-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.