Merge binding-model-{api,ri}
[yangtools.git] / parser / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / antlr / AbstractParserErrorListener.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 com.google.common.base.Verify.verifyNotNull;
11
12 import com.google.common.annotations.Beta;
13 import java.util.ArrayList;
14 import java.util.List;
15 import org.antlr.v4.runtime.BaseErrorListener;
16 import org.antlr.v4.runtime.RecognitionException;
17 import org.antlr.v4.runtime.Recognizer;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.yangtools.concepts.Mutable;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 /**
25  * Abstract base type for converting ANTLRErrorListener errors to Exceptions. This class is NOT thread-safe, nor are
26  * its subclasses expected to be thread-safe.
27  *
28  * @param <E> Reported exception type
29  * @author Robert Varga
30  */
31 @Beta
32 @NonNullByDefault
33 public abstract class AbstractParserErrorListener<E extends Exception> extends BaseErrorListener implements Mutable {
34     private static final Logger LOG = LoggerFactory.getLogger(AbstractParserErrorListener.class);
35
36     private final List<E> exceptions = new ArrayList<>();
37
38     @Override
39     @SuppressWarnings("checkstyle:parameterName")
40     public final void syntaxError(final @Nullable Recognizer<?, ?> recognizer, final @Nullable Object offendingSymbol,
41             final int line, final int charPositionInLine, final @Nullable String msg,
42             final @Nullable RecognitionException e) {
43         LOG.debug("Syntax error at {}:{}: {}", line, charPositionInLine, msg, e);
44         exceptions.add(verifyNotNull(createException(verifyNotNull(recognizer), offendingSymbol, line,
45             charPositionInLine, verifyNotNull(msg), e)));
46     }
47
48     public final void validate() throws E {
49         if (!exceptions.isEmpty()) {
50             final var it = exceptions.iterator();
51             final var exception = it.next();
52             it.forEachRemaining(exception::addSuppressed);
53             throw exception;
54         }
55     }
56
57     protected abstract E createException(Recognizer<?, ?> recognizer, @Nullable Object offendingSymbol, int line,
58             int charPositionInLine, String msg, @Nullable RecognitionException cause);
59 }