aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/prelude/query/ToolBox.java
blob: e278ad3848731f6da4b2599ce97ba23595b22768 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;

import com.yahoo.api.annotations.Beta;

/**
 * Query tree helper methods and factories.
 *
 * @author Steinar Knutsen
 */
@Beta
public final class ToolBox {

    public static abstract class QueryVisitor {

        /**
         * Called for each item in the query tree given to
         * {@link ToolBox#visit(QueryVisitor, Item)}. Return true to visit the
         * sub-items of the given item, return false to ignore the sub-items.
         *
         * @param item each item in the query tree
         * @return whether or not to visit the sub-items of the argument item
         *         (and then invoke the {@link #onExit()} method)
         */
        public abstract boolean visit(Item item);

        /**
         * Invoked when all sub-items have been visited, or immediately after
         * visit() if there are no sub-items or visit() returned false.
         * This default implementation does nothing.
         */
        public void onExit() {}

    }

    public static void visit(QueryVisitor visitor, Item item) {
        if (item instanceof CompositeItem) {
            if (visitor.visit(item)) {
                CompositeItem composite = (CompositeItem) item;
                for (int i = 0; i < composite.getItemCount(); ++i) {
                    visit(visitor, composite.getItem(i));
                }
            }
        } else {
            visitor.visit(item);
        }
        visitor.onExit();
    }

}