2 * Copyright (c) 2019 Pantheon Technologies, s.r.o. 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.xpath.impl;
10 import static com.google.common.base.Verify.verify;
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;
18 * Utility methods for dealing with {@link ParseTree}s.
20 final class ParseTreeUtils {
21 private ParseTreeUtils() {
25 static <T extends ParseTree> T getChild(final ParseTree parent, final Class<T> type, final int offset) {
26 return verifyTree(type, parent.getChild(offset));
29 static void verifyChildCount(final ParseTree tree, final int expected) {
30 if (tree.getChildCount() != expected) {
31 throw illegalShape(tree);
35 static int verifyAtLeastChildren(final ParseTree tree, final int expected) {
36 final int count = tree.getChildCount();
37 if (count < expected) {
38 throw illegalShape(tree);
43 static TerminalNode verifyTerminal(final ParseTree tree) {
44 if (tree instanceof TerminalNode terminal) {
47 throw new VerifyException("'%s' is not a terminal node".formatted(tree.getText()));
50 static Token verifyToken(final ParseTree parent, final int offset, final int expected) {
51 final var node = verifyTerminal(parent.getChild(offset));
52 final var token = node.getSymbol();
53 final int type = token.getType();
54 verify(type == expected, "Item %s has type %s, expected %s", node, type, expected);
58 static <T extends ParseTree> T verifyTree(final Class<T> type, final ParseTree tree) {
59 if (type.isInstance(tree)) {
60 return type.cast(tree);
62 throw new VerifyException("'%s' does not have expected type %s".formatted(tree.getText(), type));
65 static VerifyException illegalShape(final ParseTree tree) {
66 return new VerifyException("Invalid parser shape of '%s'".formatted(tree.getText()));