YANGTOOLS-706: Split out yang-parser-rfc7950
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / leafref / LeafRefPathErrorListener.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.data.impl.leafref;
9
10 import java.util.ArrayList;
11 import java.util.List;
12 import org.antlr.v4.runtime.BaseErrorListener;
13 import org.antlr.v4.runtime.RecognitionException;
14 import org.antlr.v4.runtime.Recognizer;
15 import org.opendaylight.yangtools.yang.model.api.Module;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 class LeafRefPathErrorListener extends BaseErrorListener {
20     private static final Logger LOG = LoggerFactory.getLogger(LeafRefPathErrorListener.class);
21
22     private final List<LeafRefPathSyntaxErrorException> exceptions = new ArrayList<>(1);
23     private final Module module;
24
25     LeafRefPathErrorListener(final Module module) {
26         this.module = module;
27     }
28
29     @Override
30     @SuppressWarnings("checkstyle:parameterName")
31     public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line,
32             final int charPositionInLine, final String msg, final RecognitionException e) {
33         LOG.debug("Syntax error in module {} at {}:{}: {}", module.getName(), line, charPositionInLine, msg, e);
34
35         exceptions.add(new LeafRefPathSyntaxErrorException(module.getName(), line, charPositionInLine, msg, e));
36     }
37
38     public void validate() throws LeafRefPathSyntaxErrorException {
39         if (exceptions.isEmpty()) {
40             return;
41         }
42
43         // Single exception: just throw it
44         if (exceptions.size() == 1) {
45             throw exceptions.get(0);
46         }
47
48         final StringBuilder sb = new StringBuilder();
49         String module = null;
50         boolean first = true;
51         for (final LeafRefPathSyntaxErrorException e : exceptions) {
52             if (module == null) {
53                 module = e.getModule();
54             }
55             if (first) {
56                 first = false;
57             } else {
58                 sb.append('\n');
59             }
60
61             sb.append(e.getFormattedMessage());
62         }
63
64         throw new LeafRefPathSyntaxErrorException(module, 0, 0, sb.toString());
65     }
66
67 }