aboutsummaryrefslogtreecommitdiffstats
path: root/searchsummary/src/vespa/juniper/matchobject.cpp
blob: 60b14cd5bcaf255a3cec662c38eca32f2e3e7e28 (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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "query.h"
#include "matchobject.h"
#include "juniperdebug.h"
#include "juniper_separators.h"
#include "result.h"
#include "charutil.h"
#include "wildcard_match.h"
#include <stack>
#include <vespa/log/log.h>
LOG_SETUP(".juniper.matchobject");

using namespace juniper::separators;

class traverser : public IQueryExprVisitor
{
public:
    traverser(MatchObject& mo) : _mo(mo) {}

    void VisitQueryNode(QueryNode*) override {
        // We must not add this node to nonterminals before all children has been added!
        // Matcher::flush_candidates() depend on this order to avoid having to loop
        // until no more candidates...
    }

    void RevisitQueryNode(QueryNode* n) override
    {
        _mo.add_nonterm(n);
    }

    void VisitQueryTerm(QueryTerm* t) override
    {
        if (t->rewriter && t->rewriter->ForDocument())
            _mo.add_reduction_term(t, t->rewriter);
        else
            _mo.add_queryterm(t);
    }
private:
    MatchObject& _mo;
};


class query_expander : public IQueryExprVisitor
{
public:
    query_expander(MatchObject& mo, uint32_t langid)
        : _caller(), _mo(mo), _langid(langid) {}

    void VisitQueryTerm(QueryTerm* orig) override
    {
        const char* nt = NULL;
        size_t length;
        juniper::RewriteHandle* te = NULL;
        bool reduction = false;

        if (orig->rewriter)
        {
            // Check if expansions are necessary
            if (orig->rewriter->ForQuery())
            {
                te = orig->rewriter->Rewrite(_langid, orig->term());
                if (te)
                    nt = orig->rewriter->NextTerm(te, length);
            }

            // If this rewriter is both an expander and a reducer, only matches
            // of reduced forms will be valid, need to take steps to add expansions
            // to a separate mapping
            reduction = orig->rewriter->ForDocument();
        }
        if (nt == NULL)
        {
            QueryTerm* t = new QueryTerm(orig); // No matches found, just clone term..
            if (!reduction)
                _mo.add_queryterm(t);
            else
                _mo.add_reduction_term(t, orig->rewriter);
            update(t);
            return;
        }
        // Start expanding...
        std::vector<QueryTerm*> newterms;
        while (nt != NULL)
        {
            QueryTerm* nqt = new QueryTerm(nt, length, -1);
            // Copy options but do not apply juniper stem match for expanded terms
            nqt->_options = orig->_options | X_EXACT;
            if (!reduction)
                _mo.add_queryterm(nqt);
            else
                _mo.add_reduction_term(nqt, orig->rewriter);
            newterms.push_back(nqt);
            nt = orig->rewriter->NextTerm(te, length);
        }
        if (newterms.size() == 1)
        {
            update(newterms.front());
            return;
        }

        QueryNode* qn = new QueryNode(newterms.size(), orig->_weight, orig->_weight);
        // preserve options for nodes too, but make the node an OR..
        qn->_options = orig->_options | X_OR;
        for (std::vector<QueryTerm*>::iterator it = newterms.begin();
             it != newterms.end();      ++it)
        {
            qn->AddChild(*it);
        }
        update(qn);
        _mo.add_nonterm(qn);
    }


    // Visit on descent:
    void VisitQueryNode(QueryNode* n) override {
        QueryNode* qn = new QueryNode(n);
        update(qn);
        _caller.push(qn);
    }


    // revisit on return:
    void RevisitQueryNode(QueryNode* n) override {
        QueryNode* qn = _caller.top();
        if (n->_parent) _caller.pop();
        _mo.add_nonterm(qn);
    }

    QueryExpr* NewQuery() {
        if (_caller.empty()) return NULL;
        return _caller.top();
    }
private:
    void update(QueryExpr* e)
    {
        if (!_caller.empty())
            _caller.top()->AddChild(e);
    }

    std::stack<QueryNode*> _caller; // Recursion emulator..
    MatchObject& _mo;
    uint32_t _langid;
};  // class query_expander

MatchObject::MatchObject(QueryExpr* query, bool has_reductions) :
    _query(query),
    _qt(),
    _nonterms(),
    _match_overlap(false), _max_arity(0),
    _has_reductions(has_reductions),
    _qt_byname(),
    _reduce_matchers()
{
    LOG(debug, "MatchObject(default)");
    traverser tr(*this);
    query->Accept(tr); // Initialize structure for the query
    _max_arity = query->MaxArity();
}



MatchObject::MatchObject(QueryExpr* query,  bool has_reductions, uint32_t langid) :
    _query(NULL),
    _qt(),
    _nonterms(),
    _match_overlap(false),
    _max_arity(0),
    _has_reductions(has_reductions),
    _qt_byname(),
    _reduce_matchers()
{
    LOG(debug, "MatchObject(language %d)", langid);
    query_expander qe(*this, langid);
    query->Accept(qe); // Create a new, modified query
    _query = qe.NewQuery(); // Fetch the new query..

    if (LOG_WOULD_LOG(debug)) {
        std::string s;
        _query->Dump(s);
        LOG(debug, "juniper::MatchObject(language id %d): modified stack: %s",
            langid, s.c_str());
    }
    _max_arity = _query->MaxArity();
}



MatchObject::~MatchObject()
{
    // _query is now always owned by the match object!
    delete _query;
}


bool MatchObject::Match(MatchObject::iterator& mi, Token& token, unsigned& options)
{
    QueryTerm* q = mi.first_match(token);
    if (!q) return false;
    options = 0;
    q->total_match_cnt++;
    if (q->ucs4_len == static_cast<size_t>(token.curlen))
    {
        options |= X_EXACT;
        q->exact_match_cnt++;
    }
    return true;
}


void MatchObject::add_nonterm(QueryNode* n)
{
    _nonterms.push_back(n);
    n->_node_idx = _nonterms.size() - 1;
}



void MatchObject::add_queryterm(QueryTerm* nt)
{
    _qt.push_back(nt);
    nt->idx = _qt.size() - 1;

    _qt_byname.Insert(
            *(reinterpret_cast<const queryterm_hashtable::keytype*>(nt->ucs4_term())), nt);

    LOG(debug, "MatchObject: adding term '%s'", nt->term());
}


void MatchObject::add_reduction_term(QueryTerm* nt, juniper::Rewriter* rw)
{
    // All terms go here:
    _qt.push_back(nt);
    nt->idx = _qt.size() - 1;

    LOG(debug, "MatchObject: adding reduction term '%s'", nt->term());
    if (!nt->reduce_matcher)
        nt->reduce_matcher = _reduce_matchers.find(rw);
    nt->reduce_matcher->add_term(nt);
}


match_iterator::match_iterator(MatchObject* mo, Result* rhandle) :
    _table(mo->_qt_byname), _el(NULL), _rhandle(rhandle),
    _reductions(mo->HasReductions()), _reduce_matches(NULL), _reduce_matches_it(),
    _mo(mo), _len(0), _stem_min(rhandle->StemMin()), _stemext(rhandle->StemExt()),
    _term(NULL)
{}


QueryTerm* match_iterator::first()
{
    for (; _el != NULL; _el = _el->GetNext())
    {
        QueryTerm* q = _el->GetItem();

        // If exact match is desired by this subexpression,
        // only have effect if exact match
        if (q->Exact() && _len > q->len) continue;

        if (q->is_wildcard())
        {
            if (fast::util::wildcard_match(_term, q->ucs4_term()) == false) continue;
            return q;
        }

        if (_len < q->ucs4_len) continue;
        // allow prefix match iff prefix query term or
        // rest < _stem_extend and length > stem_min
        if (!q->is_prefix())
        {
            size_t stem_extend = (q->ucs4_len <= _stem_min ? 0 : _stemext);
            if (_len > q->ucs4_len + stem_extend) continue;
        }
        if (juniper::strncmp(_term, q->ucs4_term(), q->ucs4_len) != 0) continue;
        return q;
    }
    return NULL;
}


QueryTerm* match_iterator::next_reduce_match()
{
    if (!_reduce_matches) return NULL;
    if (_reduce_matches_it != _reduce_matches->end())
    {
        QueryTerm* t = *_reduce_matches_it;
        ++_reduce_matches_it;
        return t;
    }
    delete _reduce_matches;
    _reduce_matches = NULL;
    return NULL;
}



QueryTerm* match_iterator::first_match(Token& token)
{
    const ucs4_t* term = token.token;
    size_t len = token.curlen;

    // Check for interlinear annotation, and "lie" to the matchobject
    if (static_cast<char32_t>(*term) == interlinear_annotation_anchor) {
        const ucs4_t *terminator = term + len;
        token.token = ++term;
        // starting annotation, skip to after SEPARATOR
        while (term < terminator && static_cast<char32_t>(*term) != interlinear_annotation_separator) {
            term++;
        }
        const ucs4_t *separator = term;
        // found separator, assume terminator at end
        if (term + 2 < terminator) {
            token.token = ++term; // skip the SEPARATOR
            QueryTerm *qt;
            // process until TERMINATOR is found
            while (term < terminator && static_cast<char32_t>(*term) != interlinear_annotation_terminator) {
                // Handle multiple terms in the same annotation, for compound nouns or multiple stems
                if (*term == ' ' || static_cast<char32_t>(*term) == interlinear_annotation_separator) {
                    token.curlen = term - token.token;
                    LOG(debug, "recurse A to match token %u..%u len %d", token.token[0], token.token[token.curlen-1], token.curlen);
                    qt = this->first_match(token);
                    if (qt != NULL) {
                        return qt;
                    }
                    token.token = ++term; // skip SPACE
                } else {
                    ++term;
                }
            }
            token.curlen = term - token.token;
            LOG(debug, "recurse B to match token %u..%u len %d", token.token[0], token.token[token.curlen-1], token.curlen);
            return this->first_match(token);
        } else {
            // broken annotation
            // process first part (before SEPARATOR) instead
            token.curlen = separator - token.token;
            LOG(debug, "recurse C to match token %u..%u len %d", token.token[0], token.token[token.curlen-1], token.curlen);
            return this->first_match(token);
        }
    } else {
        // plain token, so just reference the term
        _term = token.token;
    }

    queryterm_hashtable::keytype termval = *(reinterpret_cast<const queryterm_hashtable::keytype*>(term));
    queryterm_hashtable::keytype keyval = termval;
    if (LOG_WOULD_LOG(spam)) {
       char utf8term[1024];
       Fast_UnicodeUtil::utf8ncopy(utf8term, term, 1024, (term != NULL ? len : 0));
       LOG(spam, "term %s, len %ld, keyval 0x%x termval 0x%x",
           utf8term, len, keyval, termval);
    }
    _el = _table.FindRef(keyval);
    _len = len;
    QueryTerm* rtrn = first();

    if (rtrn == 0)
    {
        _el = _table.FindRef('*');
        if ((rtrn = first()) == 0)
        {
            _el = _table.FindRef('?');
            rtrn = first();
        }
    }
    if (_reductions)
    {
        _reduce_matches = _mo->_reduce_matchers.match(_rhandle->_langid,
                &_rhandle->_docsum[token.bytepos],
                token.bytelen);
        if (_reduce_matches)
        {
            _reduce_matches_it = _reduce_matches->begin();

            // Find the first reduce match only if no other match was found
            if (!rtrn)
                rtrn = current();
        }
    }
    return rtrn;
}



/** Return the current element without advancing iterator pointers */
QueryTerm* match_iterator::current()
{
    if (_el) return _el->GetItem();
    if (!_reduce_matches) return NULL;
    if (_reduce_matches_it != _reduce_matches->end())
    {
        QueryTerm* t = *_reduce_matches_it;
        return t;
    }
    delete _reduce_matches;
    return NULL;
}


QueryTerm* match_iterator::next()
{
    if (_el)
    {
        _el = _el->GetNext();
        return first();
    }
    else if (_reduce_matches)
        return next_reduce_match();
    return NULL;
}