简体   繁体   中英

Groovy Syntax Checking in Java

I'm implementing a Web-based Groovy code editor and need to check the code for syntax errors. The Java implementation below works OK but the resulting message contains some undesired elements (in bold). I'm looking for a way to list warnings and errors individually. I'm using this maven dependency: groovy-all 2.1.1

try {
    new GroovyShell().parse(groovyCode);            
} catch(CompilationFailedException cfe) {
    System.out.println(cfe.getMessage());
}

Output:

startup failed:

Script1.groovy: 1: unexpected token: n @ line 1, column 19.

def factorial(n)  n == 1 ? 1 : n * factorial(n - 1) }
                         ^

1 error

Would not make much sense to parse the error message. Try to look into

CompilationFailedException.getUnit()
ProcessingUnit.getErrorCollector()
ErrorCollector.getWarnings() & getErrors() 

EDIT

Ok, looks like unit is null on the CompilationFailedException . Try catching MultipleCompilationErrorsException instead:

try {
    new GroovyShell().parse(groovyCode);
} catch(MultipleCompilationErrorsException cfe) {
    ErrorCollector errorCollector = cfe.getErrorCollector();
    System.out.println("Errors: "+errorCollector.getErrorCount());
}

Btw, take a look at the ErrorCollector sources, you might find write method useful to output the info about compilation errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM