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