Attach error listeners to lexers
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / leafref / LeafRefPathParserImpl.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 org.antlr.v4.runtime.CharStreams;
11 import org.antlr.v4.runtime.CommonTokenStream;
12 import org.antlr.v4.runtime.tree.ParseTreeWalker;
13 import org.opendaylight.yangtools.yang.data.impl.leafref.LeafRefPathParser.Path_argContext;
14 import org.opendaylight.yangtools.yang.model.api.Module;
15 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
16 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
17
18 final class LeafRefPathParserImpl {
19     private final SchemaContext schemaContext;
20     private final Module module;
21     private final SchemaNode node;
22
23     LeafRefPathParserImpl(final SchemaContext schemaContext, final Module currentModule, final SchemaNode currentNode) {
24         this.schemaContext = schemaContext;
25         this.module = currentModule;
26         this.node = currentNode;
27     }
28
29     LeafRefPath parseLeafRefPath(final String path) throws LeafRefYangSyntaxErrorException {
30         final Path_argContext pathCtx = parseLeafRefPathSource(path);
31
32         final ParseTreeWalker walker = new ParseTreeWalker();
33         final LeafRefPathParserListenerImpl leafRefPathParserListenerImpl = new LeafRefPathParserListenerImpl(
34             schemaContext, module, node);
35         walker.walk(leafRefPathParserListenerImpl, pathCtx);
36
37         return leafRefPathParserListenerImpl.getLeafRefPath();
38     }
39
40     private Path_argContext parseLeafRefPathSource(final String path) throws LeafRefYangSyntaxErrorException {
41         final LeafRefPathLexer lexer = new LeafRefPathLexer(CharStreams.fromString(path));
42         final LeafRefPathParser parser = new LeafRefPathParser(new CommonTokenStream(lexer));
43
44         final LeafRefPathErrorListener errorListener = new LeafRefPathErrorListener(module);
45         lexer.removeErrorListeners();
46         lexer.addErrorListener(errorListener);
47         parser.removeErrorListeners();
48         parser.addErrorListener(errorListener);
49
50         final Path_argContext result = parser.path_arg();
51         errorListener.validate();
52         return result;
53     }
54 }