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.rfc6020.repo;
10 import java.util.ArrayList;
11 import java.util.List;
12 import org.antlr.v4.runtime.BaseErrorListener;
13 import org.antlr.v4.runtime.Parser;
14 import org.antlr.v4.runtime.RecognitionException;
15 import org.antlr.v4.runtime.Recognizer;
16 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
20 public final class YangErrorListener extends BaseErrorListener {
21 private static final Logger LOG = LoggerFactory.getLogger(YangErrorListener.class);
22 private final List<YangSyntaxErrorException> exceptions = new ArrayList<>();
25 @SuppressWarnings("checkstyle:parameterName")
26 public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line,
27 final int charPositionInLine, final String msg, final RecognitionException e) {
28 LOG.debug("Syntax error at {}:{}: {}", line, charPositionInLine, msg, e);
30 final String module = getModuleName(recognizer);
31 exceptions.add(new YangSyntaxErrorException(module, line, charPositionInLine, msg, e));
34 @SuppressWarnings("checkstyle:illegalCatch")
35 private static String getModuleName(final Recognizer<?, ?> recognizer) {
36 if (!(recognizer instanceof Parser)) {
40 final Parser parser = (Parser) recognizer;
42 String model = parser.getInputStream().getTokenSource().getInputStream().toString();
43 model = model.substring(0, model.indexOf('\n'));
44 model = model.substring(model.indexOf("module") + 6);
45 model = model.substring(0, model.indexOf('{'));
48 } catch (Exception e) {
49 LOG.debug("Failed to extract module name from parser {}", parser, e);
54 public void validate() throws YangSyntaxErrorException {
55 if (exceptions.isEmpty()) {
59 // Single exception: just throw it
60 if (exceptions.size() == 1) {
61 throw exceptions.get(0);
64 final StringBuilder sb = new StringBuilder();
67 for (YangSyntaxErrorException e : exceptions) {
69 module = e.getModule();
77 sb.append(e.getFormattedMessage());
80 throw new YangSyntaxErrorException(module, 0, 0, sb.toString());