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