Populate model/ hierarchy
[yangtools.git] / yang / yang-xpath-impl / src / main / java / org / opendaylight / yangtools / yang / xpath / impl / ParseTreeUtils.java
1 /*
2  * Copyright (c) 2019 Pantheon Technologies, s.r.o.  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.xpath.impl;
9
10 import static com.google.common.base.Verify.verify;
11
12 import com.google.common.base.VerifyException;
13 import org.antlr.v4.runtime.Token;
14 import org.antlr.v4.runtime.tree.ParseTree;
15 import org.antlr.v4.runtime.tree.TerminalNode;
16
17 /**
18  * Utility methods for dealing with {@link ParseTree}s.
19  */
20 final class ParseTreeUtils {
21     private ParseTreeUtils() {
22
23     }
24
25     static <T extends ParseTree> T getChild(final ParseTree parent, final Class<T> type, final int offset) {
26         return verifyTree(type, parent.getChild(offset));
27     }
28
29     static void verifyChildCount(final ParseTree tree, final int expected) {
30         if (tree.getChildCount() != expected) {
31             throw illegalShape(tree);
32         }
33     }
34
35     static int verifyAtLeastChildren(final ParseTree tree, final int expected) {
36         final int count = tree.getChildCount();
37         if (count < expected) {
38             throw illegalShape(tree);
39         }
40         return count;
41     }
42
43     static TerminalNode verifyTerminal(final ParseTree tree) {
44         if (tree instanceof TerminalNode) {
45             return (TerminalNode) tree;
46         }
47         throw new VerifyException(String.format("'%s' is not a terminal node", tree.getText()));
48     }
49
50     static Token verifyToken(final ParseTree parent, final int offset, final int expected) {
51         final TerminalNode node = verifyTerminal(parent.getChild(offset));
52         final Token ret = node.getSymbol();
53         final int type = ret.getType();
54         verify(type == expected, "Item %s has type %s, expected %s", node, type, expected);
55         return ret;
56     }
57
58     static <T extends ParseTree> T verifyTree(final Class<T> type, final ParseTree tree) {
59         if (type.isInstance(tree)) {
60             return type.cast(tree);
61         }
62         throw new VerifyException(String.format("'%s' does not have expected type %s", tree.getText(), type));
63     }
64
65     static VerifyException illegalShape(final ParseTree tree) {
66         return new VerifyException(String.format("Invalid parser shape of '%s'", tree.getText()));
67     }
68 }