SyntaxCheckerErrorListener.java

package org.thewonderlemming.c4plantuml.syntaxchecker;

import java.nio.file.Path;

import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.thewonderlemming.c4plantuml.commons.Reporter;

/**
 * An ANTLR4 {@link BaseErrorListener} implementation to check files for syntax errors and to report them to a given
 * {@link Reporter}.
 *
 * @author thewonderlemming
 *
 */
public class SyntaxCheckerErrorListener extends BaseErrorListener {

    private static final String SYNTAX_ERROR_FORMAT = "Syntax error in file \"%s\", "
        + "line %d, "
        + "position %d, "
        + "offending symbol: %s.\n\tError message: %s";

    private final Path filepath;

    private final Reporter reporter;


    /**
     * Default constructor.
     *
     * @param reporter the {@link Reporter} to report errors to.
     * @param filepath the source file to parse.
     */
    public SyntaxCheckerErrorListener(final Reporter reporter, final Path filepath) {

        this.reporter = reporter;
        this.filepath = filepath;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line,
        final int charPositionInLine, final String msg, final RecognitionException exception) {

        String errorDescription = String
            .format(SYNTAX_ERROR_FORMAT,
                this.filepath.toFile().getName(),
                line,
                charPositionInLine,
                offendingSymbol,
                SyntaxErrorMessageMapper.getMappingForParserMessageOrGetDefault(msg));

        if (null != exception) {
            errorDescription += "\n\t" + exception;
        }

        this.reporter.report(errorDescription);
    }
}