001/*
002 * 
003 */
004package de.isas.lipidomics.palinom.goslin;
005
006import de.isas.lipidomics.palinom.VisitorParser;
007import de.isas.lipidomics.palinom.exceptions.ParsingException;
008import de.isas.lipidomics.domain.LipidAdduct;
009import de.isas.lipidomics.palinom.GoslinLexer;
010import de.isas.lipidomics.palinom.GoslinParser;
011import de.isas.lipidomics.palinom.SyntaxErrorListener;
012import lombok.extern.slf4j.Slf4j;
013import org.antlr.v4.runtime.CharStream;
014import org.antlr.v4.runtime.CharStreams;
015import org.antlr.v4.runtime.CommonTokenStream;
016import org.antlr.v4.runtime.RecognitionException;
017import org.antlr.v4.runtime.TokenStream;
018import org.antlr.v4.runtime.misc.ParseCancellationException;
019
020/**
021 * Parser implementation for the Goslin grammar.
022 * @author nils.hoffmann
023 */
024@Slf4j
025public class GoslinVisitorParser implements VisitorParser<LipidAdduct> {
026
027    @Override
028    public LipidAdduct parse(String lipidString, SyntaxErrorListener listener) throws ParsingException {
029        return parseWithModernGrammar(lipidString, listener);
030    }
031
032    private LipidAdduct parseWithModernGrammar(String lipidString, SyntaxErrorListener listener) throws ParsingException, RecognitionException {
033        CharStream charStream = CharStreams.fromString(lipidString);
034        GoslinLexer lexer = new GoslinLexer(charStream);
035        TokenStream tokens = new CommonTokenStream(lexer);
036        log.info("Parsing lipid identifier: {}", lipidString);
037        GoslinParser parser = new GoslinParser(tokens);
038        prepare(parser, lexer, listener);
039        try {
040            GoslinParser.LipidContext context = parser.lipid();
041            if (parser.getNumberOfSyntaxErrors() > 0) {
042                throw new ParsingException("Parsing of " + lipidString + " failed with " + parser.getNumberOfSyntaxErrors() + " syntax errors!\n" + listener.getErrorString());
043            }
044            GoslinVisitorImpl lipidVisitor = new GoslinVisitorImpl();
045            return lipidVisitor.visit(context);
046        } catch (ParseCancellationException pce) {
047            throw new ParsingException("Parsing of " + lipidString + " failed with " + parser.getNumberOfSyntaxErrors() + " syntax errors!\n" + listener.getErrorString());
048        }
049    }
050
051}