2 * Copyright (c) 2013 Cisco Systems, Inc. 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.repo;
10 import static java.util.Objects.requireNonNull;
12 import java.util.ArrayList;
13 import java.util.List;
14 import org.antlr.v4.runtime.BaseErrorListener;
15 import org.antlr.v4.runtime.Parser;
16 import org.antlr.v4.runtime.RecognitionException;
17 import org.antlr.v4.runtime.Recognizer;
18 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
19 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
23 public final class YangErrorListener extends BaseErrorListener {
24 private static final Logger LOG = LoggerFactory.getLogger(YangErrorListener.class);
26 private final List<YangSyntaxErrorException> exceptions = new ArrayList<>();
27 private final SourceIdentifier source;
29 public YangErrorListener(final SourceIdentifier source) {
30 this.source = requireNonNull(source);
34 @SuppressWarnings("checkstyle:parameterName")
35 public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line,
36 final int charPositionInLine, final String msg, final RecognitionException e) {
37 LOG.debug("Syntax error in {} at {}:{}: {}", source, line, charPositionInLine, msg, e);
38 exceptions.add(new YangSyntaxErrorException(source, line, charPositionInLine, msg, e));
41 @SuppressWarnings("checkstyle:illegalCatch")
42 private static String getModuleName(final Recognizer<?, ?> recognizer) {
43 if (!(recognizer instanceof Parser)) {
47 final Parser parser = (Parser) recognizer;
49 String model = parser.getInputStream().getTokenSource().getInputStream().toString();
50 model = model.substring(0, model.indexOf('\n'));
51 model = model.substring(model.indexOf("module") + 6);
52 model = model.substring(0, model.indexOf('{'));
55 } catch (Exception e) {
56 LOG.debug("Failed to extract module name from parser {}", parser, e);
61 public void validate() throws YangSyntaxErrorException {
62 if (exceptions.isEmpty()) {
66 // Single exception: just throw it
67 if (exceptions.size() == 1) {
68 throw exceptions.get(0);
71 final StringBuilder sb = new StringBuilder();
72 SourceIdentifier source = null;
74 for (YangSyntaxErrorException e : exceptions) {
76 source = e.getSource().orElse(null);
84 sb.append(e.getFormattedMessage());
87 throw new YangSyntaxErrorException(source, 0, 0, sb.toString());