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