001/*
002 * 
003 */
004package de.isas.lipidomics.palinom.goslinfragments;
005
006import de.isas.lipidomics.palinom.exceptions.ParsingException;
007import de.isas.lipidomics.domain.LipidAdduct;
008import de.isas.lipidomics.palinom.GoslinFragmentsLexer;
009import de.isas.lipidomics.palinom.GoslinFragmentsParser;
010import de.isas.lipidomics.palinom.SyntaxErrorListener;
011import de.isas.lipidomics.palinom.VisitorParser;
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 GoslinFragments grammar.
022 *
023 * @author nils.hoffmann
024 */
025@Slf4j
026public class GoslinFragmentsVisitorParser implements VisitorParser<LipidAdduct> {
027
028    @Override
029    public LipidAdduct parse(String lipidString, SyntaxErrorListener listener) throws ParsingException {
030        return parseWithModernGrammar(lipidString, listener);
031    }
032
033    private LipidAdduct parseWithModernGrammar(String lipidString, SyntaxErrorListener listener) throws ParsingException, RecognitionException {
034        CharStream charStream = CharStreams.fromString(lipidString);
035        GoslinFragmentsLexer lexer = new GoslinFragmentsLexer(charStream);
036        TokenStream tokens = new CommonTokenStream(lexer);
037        log.info("Parsing lipid identifier: {}", lipidString);
038        GoslinFragmentsParser parser = new GoslinFragmentsParser(tokens);
039        prepare(parser, lexer, listener);
040        try {
041            GoslinFragmentsParser.LipidContext context = parser.lipid();
042            if (parser.getNumberOfSyntaxErrors() > 0) {
043                throw new ParsingException("Parsing of " + lipidString + " failed with " + parser.getNumberOfSyntaxErrors() + " syntax errors!\n" + listener.getErrorString());
044            }
045            GoslinFragmentsVisitorImpl lipidVisitor = new GoslinFragmentsVisitorImpl();
046            return lipidVisitor.visit(context);
047        } catch (ParseCancellationException pce) {
048            throw new ParsingException("Parsing of " + lipidString + " failed with " + parser.getNumberOfSyntaxErrors() + " syntax errors!\n" + listener.getErrorString());
049        }
050    }
051
052}