2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.rfc7950.antlr;
10 import static java.util.Objects.requireNonNull;
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;
23 * Utility class for converting ANTLRErrorListener errors to SourceExceptions.
25 * @author Robert Varga
30 public final class SourceExceptionParser {
31 private static final class Listener extends AbstractParserErrorListener<SourceException> {
32 private final StatementSourceReference ref;
34 private Listener(final StatementSourceReference ref) {
35 this.ref = requireNonNull(ref);
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);
46 private SourceExceptionParser() {
51 * Parse a Recognizer extracting its root item.
53 * @param recognizer Recognizer to use
54 * @param parseMethod Root item extractor method
55 * @param ref Source reference
57 * @throws NullPointerException if any argument is null
58 * @throws SourceException if a parser error occurs
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);
66 final T ret = parseMethod.get();