与 Sam Harwell
描述它的方式类似,以下代码演示如何在调用解析器规则(如解析器)后获取语法错误列表:functionDefinition
C
语法检查器:
import c.grammar.CLexer;
import c.grammar.CParser;
import org.antlr.v4.runtime.CodePointCharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import java.util.List;
import static org.antlr.v4.runtime.CharStreams.fromString;
public class CSyntaxChecker
{
public static List<SyntaxError> getSyntaxErrors(String sourceCode)
{
CodePointCharStream inputStream = fromString(sourceCode);
CLexer lexer = new CLexer(inputStream);
CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
CParser parser = new CParser(commonTokenStream);
SyntaxErrorListener listener = new SyntaxErrorListener();
parser.addErrorListener(listener);
parser.functionDefinition();
return listener.getSyntaxErrors();
}
}
语法错误侦听器:
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.misc.Utils;
import java.util.ArrayList;
import java.util.List;
public class SyntaxErrorListener extends BaseErrorListener
{
private final List<SyntaxError> syntaxErrors = new ArrayList<>();
SyntaxErrorListener()
{
}
List<SyntaxError> getSyntaxErrors()
{
return syntaxErrors;
}
@Override
public void syntaxError(Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line, int charPositionInLine,
String msg, RecognitionException e)
{
syntaxErrors.add(new SyntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e));
}
@Override
public String toString()
{
return Utils.join(syntaxErrors.iterator(), "\n");
}
}
语法错误:
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
public class SyntaxError
{
private final Recognizer<?, ?> recognizer;
private final Object offendingSymbol;
private final int line;
private final int charPositionInLine;
private final String message;
private final RecognitionException e;
SyntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e)
{
this.recognizer = recognizer;
this.offendingSymbol = offendingSymbol;
this.line = line;
this.charPositionInLine = charPositionInLine;
this.message = msg;
this.e = e;
}
public Recognizer<?, ?> getRecognizer()
{
return recognizer;
}
public Object getOffendingSymbol()
{
return offendingSymbol;
}
public int getLine()
{
return line;
}
public int getCharPositionInLine()
{
return charPositionInLine;
}
public String getMessage()
{
return message;
}
public RecognitionException getException()
{
return e;
}
}