3867daddc83ea1066803e63f3a00dd6263aacf10
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / antlr / SourceExceptionParser.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.rfc7950.antlr;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import java.util.function.Supplier;
14 import javax.annotation.concurrent.NotThreadSafe;
15 import org.antlr.v4.runtime.RecognitionException;
16 import org.antlr.v4.runtime.Recognizer;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
20 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
21
22 /**
23  * Utility class for converting ANTLRErrorListener errors to SourceExceptions.
24  *
25  * @author Robert Varga
26  */
27 @Beta
28 @NonNullByDefault
29 @NotThreadSafe
30 public final class SourceExceptionParser {
31     private static final class Listener extends AbstractParserErrorListener<SourceException> {
32         private final StatementSourceReference ref;
33
34         private Listener(final StatementSourceReference ref) {
35             this.ref = requireNonNull(ref);
36         }
37
38         @Override
39         protected SourceException createException(final Recognizer<?, ?> recognizer,
40                 final @Nullable Object offendingSymbol, final int line, final int charPositionInLine,
41                 final String msg, final @Nullable RecognitionException cause) {
42             return new SourceException(ref, cause, "%s at %s:%s", msg, line, charPositionInLine);
43         }
44     }
45
46     private SourceExceptionParser() {
47
48     }
49
50     /**
51      * Parse a Recognizer extracting its root item.
52      *
53      * @param recognizer Recognizer to use
54      * @param parseMethod Root item extractor method
55      * @param ref Source reference
56      * @return Parsed item
57      * @throws NullPointerException if any argument is null
58      * @throws SourceException if a parser error occurs
59      */
60     public static <T> T parse(final Recognizer<?, ?> recognizer, final Supplier<T> parseMethod,
61             final StatementSourceReference ref) {
62         final Listener listener = new Listener(ref);
63         recognizer.removeErrorListeners();
64         recognizer.addErrorListener(listener);
65
66         final T ret = parseMethod.get();
67         listener.validate();
68         return ret;
69     }
70 }