summaryrefslogtreecommitdiffstats
path: root/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/ArithmeticNode.java
blob: c3e39197316dd67592809cf98ca768f3bca71db8 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchlib.rankingexpression.rule;

import com.yahoo.searchlib.rankingexpression.Reference;
import com.yahoo.searchlib.rankingexpression.evaluation.Context;
import com.yahoo.searchlib.rankingexpression.evaluation.Value;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.evaluation.TypeContext;
import com.yahoo.tensor.functions.Join;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * A binary mathematical operation
 *
 * @author bratseth
 */
public final class ArithmeticNode extends CompositeNode {

    private final List<ExpressionNode> children;
    private final List<ArithmeticOperator> operators;

    public ArithmeticNode(List<ExpressionNode> children, List<ArithmeticOperator> operators) {
        this.children = List.copyOf(children);
        this.operators = List.copyOf(operators);
    }

    public ArithmeticNode(ExpressionNode leftExpression, ArithmeticOperator operator, ExpressionNode rightExpression) {
        this.children = List.of(leftExpression, rightExpression);
        this.operators = List.of(operator);
    }

    public List<ArithmeticOperator> operators() { return operators; }

    @Override
    public List<ExpressionNode> children() { return children; }

    @Override
    public StringBuilder toString(StringBuilder string, SerializationContext context, Deque<String> path, CompositeNode parent) {
        boolean nonDefaultPrecedence = nonDefaultPrecedence(parent);
        if (nonDefaultPrecedence)
            string.append("(");

        Iterator<ExpressionNode> child = children.iterator();
        child.next().toString(string, context, path, this);
        if (child.hasNext())
            string.append(" ");
        for (Iterator<ArithmeticOperator> op = operators.iterator(); op.hasNext() && child.hasNext();) {
            string.append(op.next().toString()).append(" ");
            child.next().toString(string, context, path, this);
            if (op.hasNext())
                string.append(" ");
        }
        if (nonDefaultPrecedence)
            string.append(")");

        return string;
    }

    /**
     * Returns true if this node has lower precedence than the parent
     * (even though by virtue of being a node it will be calculated before the parent).
     */
    private boolean nonDefaultPrecedence(CompositeNode parent) {
        if ( parent == null) return false;
        if ( ! (parent instanceof ArithmeticNode arithmeticParent)) return false;

        // The line below can only be correct in both only have one operator.
        // Getting this correct is impossible without more work.
        // So for now we only handle the simple case correctly, and use a safe approach by adding
        // extra parenthesis just in case....
        return arithmeticParent.operators.get(0).hasPrecedenceOver(this.operators.get(0))
                || ((arithmeticParent.operators.size() > 1) || (operators.size() > 1));
    }

    @Override
    public TensorType type(TypeContext<Reference> context) {
        // Compute type using tensor types as arithmetic operators are supported on tensors
        // and is correct also in the special case of doubles.
        // As all our functions are type-commutative, we don't need to take operator precedence into account
        TensorType type = children.get(0).type(context);
        for (int i = 1; i < children.size(); i++)
            type = Join.outputType(type, children.get(i).type(context));
        return type;
    }

    @Override
    public Value evaluate(Context context) {
        Iterator<ExpressionNode> child = children.iterator();

        // Apply in precedence order:
        Deque<ValueItem> stack = new ArrayDeque<>();
        stack.push(new ValueItem(null, child.next().evaluate(context)));
        for (Iterator<ArithmeticOperator> it = operators.iterator(); it.hasNext() && child.hasNext();) {
            ArithmeticOperator op = it.next();
            if ( ! stack.isEmpty()) {
                while (stack.size() > 1 && ! op.hasPrecedenceOver(stack.peek().op)) {
                    popStack(stack);
                }
            }
            stack.push(new ValueItem(op, child.next().evaluate(context)));
        }
        while (stack.size() > 1) {
            popStack(stack);
        }
        return stack.getFirst().value;
    }

    private void popStack(Deque<ValueItem> stack) {
        ValueItem rhs = stack.pop();
        ValueItem lhs = stack.peek();
        lhs.value = rhs.op.evaluate(lhs.value, rhs.value);
    }

    @Override
    public CompositeNode setChildren(List<ExpressionNode> newChildren) {
        if (children.size() != newChildren.size())
            throw new IllegalArgumentException("Expected " + children.size() + " children but got " + newChildren.size());
        return new ArithmeticNode(newChildren, operators);
    }

    @Override
    public int hashCode() { return Objects.hash(children, operators); }

    public static ArithmeticNode resolve(ExpressionNode left, ArithmeticOperator op, ExpressionNode right) {
        if ( ! (left instanceof ArithmeticNode leftArithmetic)) return new ArithmeticNode(left, op, right);

        List<ExpressionNode> newChildren = new ArrayList<>(leftArithmetic.children());
        newChildren.add(right);

        List<ArithmeticOperator> newOperators = new ArrayList<>(leftArithmetic.operators());
        newOperators.add(op);

        return new ArithmeticNode(newChildren, newOperators);
    }

    private static class ValueItem {

        final ArithmeticOperator op;
        Value value;

        public ValueItem(ArithmeticOperator op, Value value) {
            this.op = op;
            this.value = value;
        }

        @Override
        public String toString() {
            return value.toString();
        }

    }

}