Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax check on a java file

For a given java file, I'd like to check if it's syntactically correct. ie. If it has semi-colons in the right places, matching parenthesis etc. Importantly, I need to check the file in isolation from all of its dependencies.

This other answer is promising, however it's really doing a semantic check rather than a syntactic check. It does what a compiler would do - check all the imports statements as well as verify external classes that are referenced in the code.

Is there a way to do a true syntax check? (A check that only inspects the raw text against Java's formal grammar)

like image 404
Fidel Avatar asked Feb 06 '23 11:02

Fidel


1 Answers

Create or use a Java source code parser. For some parser generators there are public Java grammars available - you could use it to generate the parser.

E.g. Java 8 grammar for ANTLR (no idea about quality of that grammar though, you'd have to do your evaluation - but the grammar is written by the author of ANTLR, so should be OK I guess).

like image 98
Jiri Tousek Avatar answered Feb 22 '23 09:02

Jiri Tousek