aboutsummaryrefslogtreecommitdiffstats
path: root/document/src/vespa/document/base/documentcalculator.cpp
blob: f4078b772376d3a83a4baadccc3779ea7e774953 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "documentcalculator.h"
#include <vespa/document/bucket/bucketidfactory.h>
#include <vespa/document/select/compare.h>
#include <vespa/document/select/parser.h>
#include <vespa/document/select/valuenode.h>
#include <vespa/document/select/variablemap.h>
#include <vespa/vespalib/util/exceptions.h>

namespace document {

DocumentCalculator::DocumentCalculator(
        const DocumentTypeRepo& repo,
        const vespalib::string & expression)
{
    BucketIdFactory factory;
    select::Parser parser(repo, factory);
    _selectionNode = parser.parse(expression + " == 0");
}

DocumentCalculator::~DocumentCalculator() { }

double
DocumentCalculator::evaluate(const Document& doc, std::unique_ptr<select::VariableMap> variables)
{
    select::Compare& compare(static_cast<select::Compare&>(*_selectionNode));
    const select::ValueNode& left = compare.getLeft();

    select::Context context(doc);
    context.setVariableMap(std::move(variables));
    std::unique_ptr<select::Value> value = left.getValue(context);

    select::NumberValue* num = dynamic_cast<select::NumberValue*>(value.get());

    if (!num) {
        throw vespalib::IllegalArgumentException("Expression could not be evaluated - some components of the expression may be missing");
    }

    return num->getCommonValue();
}

}