Syntax Checking in Java [closed]
Asked Answered
P

5

15

I am currently working on a program that has an embedded text editor. The users are supposed to type java code in the editor. The code typed into the editor is then made into a string. I just want something that would check for missing parenthesis or a try without a catch, etc. It doesn't need to be compiled. I've looked around quite a bit, but I'm still new to programming and can't implement some of the harder stuff.

So to make it shorter: I'm looking for some java package that will analyze code for syntax errors.

Papistry answered 2/7, 2012 at 18:6 Comment(3)
Eclipse is your best place to start: eclipse.orgThorr
NetBeans is your best place to start: platform.netbeans.org/tutorials/nbm-javacc-lexer.htmlOrpiment
@Steven Morad: please choose an answer or comment what you still are looking for.Blackwell
B
19

As of Java 6 you can use JavaCompiler to compile the text and get back Diagnostic objects that tell you what problems the file has (if any). So for your example you'd need to take the content of the editor and pass it to the JavaCompiler, run it, and report back any problems. Example that follows assumes editor text written out to a file.

Example code:

File to Check

public class HelloBuggyWorld {
    String test // missing a semicolon

    public static void main (String [] args) {
        System.out.println('Hello World!');  // should be double quoted
    }
}

Checker

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class JavaSyntaxChecker {
    public static void main(String[] args) {
        System.out.println(check("/path/to/HelloBuggyWorld.java"));
    }

    public static List<String> check(String file) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits =
                fileManager.getJavaFileObjectsFromStrings(Arrays.asList(file));

        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();

        List<String> messages = new ArrayList<String>();
        Formatter formatter = new Formatter();
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            messages.add(diagnostic.getKind() + ":\t Line [" + diagnostic.getLineNumber() + "] \t Position [" + diagnostic.getPosition() + "]\t" + diagnostic.getMessage(Locale.ROOT) + "\n");
        }

        return messages;
    }
}

Output

From running the main method.

[ERROR:  Line [5]    Position [124] HelloBuggyWorld.java:5: unclosed character literal
, ERROR:     Line [5]    Position [126] HelloBuggyWorld.java:5: ';' expected
, ERROR:     Line [5]    Position [131] HelloBuggyWorld.java:5: not a statement
, ERROR:     Line [5]    Position [136] HelloBuggyWorld.java:5: ';' expected
, ERROR:     Line [5]    Position [137] HelloBuggyWorld.java:5: unclosed character literal
]
Blackwell answered 2/7, 2012 at 19:1 Comment(0)
S
2

You can use JDT to parse and analyze source.

That's scala example. It's easy to do the same with java:

val str = "..." // Checking source code
val parser : ASTParser = ASTParser.newParser(org.eclipse.jdt.core.dom.AST.JLS3)    
val options = JavaCore.getOptions.asInstanceOf[java.util.Map[Object, Object]]
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7)
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7)
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7)
parser.setCompilerOptions(options)
parser.setSource(str.toCharArray)
val cu: CompilationUnit = parser.createAST(null).asInstanceOf[CompilationUnit]

CompilationUnit has method getProblems(). It returns list of detailed problem reports.

Staircase answered 27/7, 2012 at 13:0 Comment(0)
I
1

You can look at Beanshell interpreter. It can interpret Java code (both full source file and code fragments) and report errors on syntax.

Idolism answered 2/7, 2012 at 18:38 Comment(0)
P
1

Assuming that you want to validate that user has input java code with correct syntax then you could invoke javac compiler directly from within your program.

public int com.sun.tools.javac.Main.compile(String[] args);

You need tools.jar in your class path.

Polymorphism answered 2/7, 2012 at 18:59 Comment(0)
W
0

This is pretty standard in Eclipse and Netbeans.

If you want a nice, simple editor with parentheses-checks I'd vote for Sublime text.

Wellspring answered 2/7, 2012 at 18:14 Comment(1)
Does Sublime Text provide API that respond to Steven question ? If so, be more specific.Modulate

© 2022 - 2024 — McMap. All rights reserved.