001/*
002 * 
003 */
004package de.isas.lipidomics.palinom.lipidmaps;
005
006import de.isas.lipidomics.palinom.exceptions.ParsingException;
007import de.isas.lipidomics.domain.LipidAdduct;
008import de.isas.lipidomics.palinom.LipidMapsLexer;
009import de.isas.lipidomics.palinom.LipidMapsParser;
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 LipidMaps grammar.
022 *
023 * @author nils.hoffmann
024 */
025@Slf4j
026public class LipidMapsVisitorParser implements VisitorParser<LipidAdduct> {
027
028    @Override
029    public LipidAdduct parse(String lipidString, SyntaxErrorListener listener) throws ParsingException {
030        return parseWithLipidMapsGrammar(lipidString, listener);
031    }
032
033    private LipidAdduct parseWithLipidMapsGrammar(String lipidString, SyntaxErrorListener listener) throws ParsingException, RecognitionException {
034        CharStream charStream = CharStreams.fromString(lipidString);
035        LipidMapsLexer lexer = new LipidMapsLexer(charStream);
036        TokenStream tokens = new CommonTokenStream(lexer);
037        log.info("Parsing lipid maps identifier: {}", lipidString);
038        LipidMapsParser parser = new LipidMapsParser(tokens);
039        prepare(parser, lexer, listener);
040        try {
041            LipidMapsParser.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            LipidMapsVisitorImpl lipidVisitor = new LipidMapsVisitorImpl();
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}