Coverage Report

Created: 2026-07-16 06:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libyang/src/xpath.c
Line
Count
Source
1
/**
2
 * @file xpath.c
3
 * @author Michal Vasko <mvasko@cesnet.cz>
4
 * @brief YANG XPath evaluation functions
5
 *
6
 * Copyright (c) 2015 - 2026 CESNET, z.s.p.o.
7
 *
8
 * This source code is licensed under BSD 3-Clause License (the "License").
9
 * You may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     https://opensource.org/licenses/BSD-3-Clause
13
 */
14
#define _GNU_SOURCE /* asprintf, strdup */
15
#define _DEFAULT_SOURCE /* fmodl */
16
17
#include "xpath.h"
18
19
#include <assert.h>
20
#include <ctype.h>
21
#include <errno.h>
22
#include <math.h>
23
#include <stdint.h>
24
#include <stdio.h>
25
#include <stdlib.h>
26
#include <string.h>
27
28
#include "compat.h"
29
#include "context.h"
30
#include "dict.h"
31
#include "hash_table.h"
32
#include "ly_common.h"
33
#include "out.h"
34
#include "parser_data.h"
35
#include "path.h"
36
#include "plugins_exts/metadata.h"
37
#include "plugins_internal.h"
38
#include "plugins_types.h"
39
#include "printer_data.h"
40
#include "schema_compile_node.h"
41
#include "tree.h"
42
#include "tree_data.h"
43
#include "tree_data_internal.h"
44
#include "tree_edit.h"
45
#include "tree_schema_internal.h"
46
#include "xml.h"
47
48
static LY_ERR reparse_or_expr(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth);
49
static LY_ERR eval_expr_select(const struct lyxp_expr *exp, uint32_t *tok_idx, enum lyxp_expr_type etype,
50
        struct lyxp_set *set, uint32_t options);
51
static LY_ERR moveto_resolve_module(const char **qname, uint32_t *qname_len, const struct lyxp_set *set,
52
        const struct lysc_node *ctx_scnode, const struct lys_module **moveto_mod);
53
static LY_ERR moveto_axis_node_next(const struct lyd_node **iter, enum lyxp_node_type *iter_type,
54
        const struct lyd_node *node, enum lyxp_node_type node_type, enum lyxp_axis axis, struct lyxp_set *set);
55
static LY_ERR moveto_node(struct lyxp_set *set, const struct lys_module *moveto_mod, const char *ncname,
56
        uint32_t ncname_len, enum lyxp_axis axis, uint32_t options);
57
static LY_ERR moveto_scnode(struct lyxp_set *set, const struct lys_module *moveto_mod, const char *ncname,
58
        uint32_t ncname_len, enum lyxp_axis axis, uint32_t options);
59
static LY_ERR moveto_op_comp(struct lyxp_set *set1, struct lyxp_set *set2, const char *op, ly_bool *result);
60
61
#define LOGVAL_DXPATH(SET, ...) \
62
0
        LOGVAL((SET)->ctx, (SET)->cur_node, __VA_ARGS__);
63
64
#define LOGVAL_SXPATH(SET, ...) \
65
0
        if ((SET)->cur_scnode) { \
66
0
            LOG_LOCSET((SET)->cur_scnode); \
67
0
        } \
68
0
        LOGVAL((SET)->ctx, NULL, __VA_ARGS__); \
69
0
        if ((SET)->cur_scnode) { \
70
0
            LOG_LOCBACK(1); \
71
0
        }
72
73
#define LOGVAL_XPATH(SET, OPTS, ...) \
74
0
        if ((OPTS) & LYXP_SCNODE_ALL) { \
75
0
            LOGVAL_SXPATH(SET, __VA_ARGS__); \
76
0
        } else { \
77
0
            LOGVAL_DXPATH(SET, __VA_ARGS__); \
78
0
        }
79
80
/* Functions are divided into the following basic classes:
81
 *
82
 * (re)parse functions:
83
 * Parse functions parse the expression into
84
 * tokens (syntactic analysis).
85
 * Reparse functions perform semantic analysis
86
 * (do not save the result, just a check) of
87
 * the expression and fill repeat indices.
88
 *
89
 * warn functions:
90
 * Warn functions check specific reasonable conditions for schema XPath
91
 * and print a warning if they are not satisfied.
92
 *
93
 * moveto functions:
94
 * They and only they actually change the context (set).
95
 *
96
 * eval functions:
97
 * They execute a parsed XPath expression on some data subtree.
98
 */
99
100
/**
101
 * @brief Print the type of an XPath \p set.
102
 *
103
 * @param[in] set Set to use.
104
 * @return Set type string.
105
 */
106
static const char *
107
print_set_type(struct lyxp_set *set)
108
0
{
109
0
    switch (set->type) {
110
0
    case LYXP_SET_NODE_SET:
111
0
        return "node set";
112
0
    case LYXP_SET_SCNODE_SET:
113
0
        return "schema node set";
114
0
    case LYXP_SET_BOOLEAN:
115
0
        return "boolean";
116
0
    case LYXP_SET_NUMBER:
117
0
        return "number";
118
0
    case LYXP_SET_STRING:
119
0
        return "string";
120
0
    }
121
122
0
    return NULL;
123
0
}
124
125
const char *
126
lyxp_token2str(enum lyxp_token tok)
127
0
{
128
0
    switch (tok) {
129
0
    case LYXP_TOKEN_PAR1:
130
0
        return "(";
131
0
    case LYXP_TOKEN_PAR2:
132
0
        return ")";
133
0
    case LYXP_TOKEN_BRACK1:
134
0
        return "[";
135
0
    case LYXP_TOKEN_BRACK2:
136
0
        return "]";
137
0
    case LYXP_TOKEN_DOT:
138
0
        return ".";
139
0
    case LYXP_TOKEN_DDOT:
140
0
        return "..";
141
0
    case LYXP_TOKEN_AT:
142
0
        return "@";
143
0
    case LYXP_TOKEN_COMMA:
144
0
        return ",";
145
0
    case LYXP_TOKEN_DCOLON:
146
0
        return "::";
147
0
    case LYXP_TOKEN_NAMETEST:
148
0
        return "NameTest";
149
0
    case LYXP_TOKEN_NODETYPE:
150
0
        return "NodeType";
151
0
    case LYXP_TOKEN_VARREF:
152
0
        return "VariableReference";
153
0
    case LYXP_TOKEN_FUNCNAME:
154
0
        return "FunctionName";
155
0
    case LYXP_TOKEN_OPER_LOG:
156
0
        return "Operator(Logic)";
157
0
    case LYXP_TOKEN_OPER_EQUAL:
158
0
        return "Operator(Equal)";
159
0
    case LYXP_TOKEN_OPER_NEQUAL:
160
0
        return "Operator(Non-equal)";
161
0
    case LYXP_TOKEN_OPER_COMP:
162
0
        return "Operator(Comparison)";
163
0
    case LYXP_TOKEN_OPER_MATH:
164
0
        return "Operator(Math)";
165
0
    case LYXP_TOKEN_OPER_UNI:
166
0
        return "Operator(Union)";
167
0
    case LYXP_TOKEN_OPER_PATH:
168
0
        return "Operator(Path)";
169
0
    case LYXP_TOKEN_OPER_RPATH:
170
0
        return "Operator(Recursive Path)";
171
0
    case LYXP_TOKEN_AXISNAME:
172
0
        return "AxisName";
173
0
    case LYXP_TOKEN_LITERAL:
174
0
        return "Literal";
175
0
    case LYXP_TOKEN_NUMBER:
176
0
        return "Number";
177
0
    default:
178
0
        LOGINT(NULL);
179
0
        return "";
180
0
    }
181
0
}
182
183
/**
184
 * @brief Transform string into an axis.
185
 *
186
 * @param[in] str String to transform.
187
 * @param[in] str_len Length of @p str.
188
 * @return Transformed axis.
189
 */
190
static enum lyxp_axis
191
str2axis(const char *str, uint32_t str_len)
192
0
{
193
0
    switch (str_len) {
194
0
    case 4:
195
0
        assert(!strncmp("self", str, str_len));
196
0
        return LYXP_AXIS_SELF;
197
0
    case 5:
198
0
        assert(!strncmp("child", str, str_len));
199
0
        return LYXP_AXIS_CHILD;
200
0
    case 6:
201
0
        assert(!strncmp("parent", str, str_len));
202
0
        return LYXP_AXIS_PARENT;
203
0
    case 8:
204
0
        assert(!strncmp("ancestor", str, str_len));
205
0
        return LYXP_AXIS_ANCESTOR;
206
0
    case 9:
207
0
        if (str[0] == 'a') {
208
0
            assert(!strncmp("attribute", str, str_len));
209
0
            return LYXP_AXIS_ATTRIBUTE;
210
0
        } else if (str[0] == 'f') {
211
0
            assert(!strncmp("following", str, str_len));
212
0
            return LYXP_AXIS_FOLLOWING;
213
0
        } else {
214
0
            assert(!strncmp("preceding", str, str_len));
215
0
            return LYXP_AXIS_PRECEDING;
216
0
        }
217
0
        break;
218
0
    case 10:
219
0
        assert(!strncmp("descendant", str, str_len));
220
0
        return LYXP_AXIS_DESCENDANT;
221
0
    case 16:
222
0
        assert(!strncmp("ancestor-or-self", str, str_len));
223
0
        return LYXP_AXIS_ANCESTOR_OR_SELF;
224
0
    case 17:
225
0
        if (str[0] == 'f') {
226
0
            assert(!strncmp("following-sibling", str, str_len));
227
0
            return LYXP_AXIS_FOLLOWING_SIBLING;
228
0
        } else {
229
0
            assert(!strncmp("preceding-sibling", str, str_len));
230
0
            return LYXP_AXIS_PRECEDING_SIBLING;
231
0
        }
232
0
        break;
233
0
    case 18:
234
0
        assert(!strncmp("descendant-or-self", str, str_len));
235
0
        return LYXP_AXIS_DESCENDANT_OR_SELF;
236
0
    }
237
238
0
    LOGINT(NULL);
239
0
    return 0;
240
0
}
241
242
/**
243
 * @brief Print the whole expression @p exp to debug output.
244
 *
245
 * @param[in] exp Expression to use.
246
 */
247
static void
248
print_expr_struct_debug(const struct lyxp_expr *exp)
249
0
{
250
0
    char *buf = NULL;
251
0
    uint32_t i, j, size = 0, used = 0;
252
253
0
    if (!exp || (ly_ll < LY_LLDBG)) {
254
0
        return;
255
0
    }
256
257
0
    LOGDBG(LY_LDGXPATH, "expression \"%s\":", exp->expr);
258
0
    for (i = 0; i < exp->used; ++i) {
259
0
        ly_append_str(&buf, &size, &used, "\ttoken %s, in expression \"%.*s\"",
260
0
                lyxp_token2str(exp->tokens[i]), exp->tok_len[i], &exp->expr[exp->tok_pos[i]]);
261
262
0
        if (exp->repeat && exp->repeat[i]) {
263
0
            ly_append_str(&buf, &size, &used, " (repeat %d", exp->repeat[i][0]);
264
0
            for (j = 1; exp->repeat[i][j]; ++j) {
265
0
                ly_append_str(&buf, &size, &used, ", %d", exp->repeat[i][j]);
266
0
            }
267
0
            ly_append_str(&buf, &size, &used, ")");
268
0
        }
269
0
        LOGDBG(LY_LDGXPATH, buf);
270
0
        used = 0;
271
0
    }
272
273
0
    free(buf);
274
0
}
275
276
#ifndef NDEBUG
277
278
/**
279
 * @brief Print XPath set content to debug output.
280
 *
281
 * @param[in] set Set to print.
282
 */
283
static void
284
print_set_debug(struct lyxp_set *set)
285
0
{
286
0
    uint32_t i;
287
0
    char *str;
288
0
    struct lyxp_set_node *item;
289
0
    struct lyxp_set_scnode *sitem;
290
291
0
    if (ly_ll < LY_LLDBG) {
292
0
        return;
293
0
    }
294
295
0
    switch (set->type) {
296
0
    case LYXP_SET_NODE_SET:
297
0
        LOGDBG(LY_LDGXPATH, "set NODE SET:");
298
0
        for (i = 0; i < set->used; ++i) {
299
0
            item = &set->val.nodes[i];
300
301
0
            switch (item->type) {
302
0
            case LYXP_NODE_NONE:
303
0
                LOGDBG(LY_LDGXPATH, "\t%d (pos %u): NONE", i + 1, item->pos);
304
0
                break;
305
0
            case LYXP_NODE_ROOT:
306
0
                LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ROOT", i + 1, item->pos);
307
0
                break;
308
0
            case LYXP_NODE_ROOT_CONFIG:
309
0
                LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ROOT CONFIG", i + 1, item->pos);
310
0
                break;
311
0
            case LYXP_NODE_ELEM:
312
0
                if (item->node->schema && (item->node->schema->nodetype == LYS_LIST) &&
313
0
                        (lyd_child(item->node)->schema->nodetype == LYS_LEAF)) {
314
0
                    LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ELEM %s (1st child val: %s)", i + 1, item->pos,
315
0
                            item->node->schema->name, lyd_get_value(lyd_child(item->node)));
316
0
                } else if (lyd_get_value(item->node)) {
317
0
                    LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ELEM %s (val: %s)", i + 1, item->pos,
318
0
                            LYD_NAME(item->node), lyd_get_value(item->node));
319
0
                } else {
320
0
                    LOGDBG(LY_LDGXPATH, "\t%d (pos %u): ELEM %s", i + 1, item->pos, LYD_NAME(item->node));
321
0
                }
322
0
                break;
323
0
            case LYXP_NODE_TEXT:
324
0
                if (item->node->schema && (item->node->schema->nodetype & LYS_ANYDATA)) {
325
0
                    LOGDBG(LY_LDGXPATH, "\t%d (pos %u): TEXT <%s>", i + 1, item->pos,
326
0
                            item->node->schema->nodetype == LYS_ANYXML ? "anyxml" : "anydata");
327
0
                } else {
328
0
                    LOGDBG(LY_LDGXPATH, "\t%d (pos %u): TEXT %s", i + 1, item->pos, lyd_get_value(item->node));
329
0
                }
330
0
                break;
331
0
            case LYXP_NODE_META:
332
0
                LOGDBG(LY_LDGXPATH, "\t%d (pos %u): META %s = %s", i + 1, item->pos, set->val.meta[i].meta->name,
333
0
                        set->val.meta[i].meta->value);
334
0
                break;
335
0
            }
336
0
        }
337
0
        break;
338
339
0
    case LYXP_SET_SCNODE_SET:
340
0
        LOGDBG(LY_LDGXPATH, "set SCNODE SET:");
341
0
        for (i = 0; i < set->used; ++i) {
342
0
            sitem = &set->val.scnodes[i];
343
344
0
            switch (sitem->type) {
345
0
            case LYXP_NODE_ROOT:
346
0
                LOGDBG(LY_LDGXPATH, "\t%d (%u): ROOT", i + 1, sitem->in_ctx);
347
0
                break;
348
0
            case LYXP_NODE_ROOT_CONFIG:
349
0
                LOGDBG(LY_LDGXPATH, "\t%d (%u): ROOT CONFIG", i + 1, sitem->in_ctx);
350
0
                break;
351
0
            case LYXP_NODE_ELEM:
352
0
                LOGDBG(LY_LDGXPATH, "\t%d (%u): ELEM %s", i + 1, sitem->in_ctx, sitem->scnode->name);
353
0
                break;
354
0
            default:
355
0
                LOGINT(NULL);
356
0
                break;
357
0
            }
358
0
        }
359
0
        break;
360
361
0
    case LYXP_SET_BOOLEAN:
362
0
        LOGDBG(LY_LDGXPATH, "set BOOLEAN");
363
0
        LOGDBG(LY_LDGXPATH, "\t%s", (set->val.bln ? "true" : "false"));
364
0
        break;
365
366
0
    case LYXP_SET_STRING:
367
0
        LOGDBG(LY_LDGXPATH, "set STRING");
368
0
        LOGDBG(LY_LDGXPATH, "\t%s", set->val.str);
369
0
        break;
370
371
0
    case LYXP_SET_NUMBER:
372
0
        LOGDBG(LY_LDGXPATH, "set NUMBER");
373
374
0
        if (isnan(set->val.num)) {
375
0
            str = strdup("NaN");
376
0
        } else if ((set->val.num == 0) || (set->val.num == -0.0f)) {
377
0
            str = strdup("0");
378
0
        } else if (isinf(set->val.num) && !signbit(set->val.num)) {
379
0
            str = strdup("Infinity");
380
0
        } else if (isinf(set->val.num) && signbit(set->val.num)) {
381
0
            str = strdup("-Infinity");
382
0
        } else if ((long long)set->val.num == set->val.num) {
383
0
            if (asprintf(&str, "%lld", (long long)set->val.num) == -1) {
384
0
                str = NULL;
385
0
            }
386
0
        } else {
387
0
            if (asprintf(&str, "%03.1Lf", set->val.num) == -1) {
388
0
                str = NULL;
389
0
            }
390
0
        }
391
0
        LY_CHECK_ERR_RET(!str, LOGMEM(NULL), );
392
393
0
        LOGDBG(LY_LDGXPATH, "\t%s", str);
394
0
        free(str);
395
0
    }
396
0
}
397
398
#endif
399
400
/**
401
 * @brief Realloc the string \p str.
402
 *
403
 * @param[in] ctx libyang context for logging.
404
 * @param[in] needed How much free space is required.
405
 * @param[in,out] str Pointer to the string to use.
406
 * @param[in,out] used Used bytes in \p str.
407
 * @param[in,out] size Allocated bytes in \p str.
408
 * @return LY_ERR
409
 */
410
static LY_ERR
411
cast_string_realloc(const struct ly_ctx *ctx, uint64_t needed, char **str, uint32_t *used, uint32_t *size)
412
0
{
413
0
    if (*size - (unsigned)*used < needed) {
414
0
        do {
415
0
            if ((UINT32_MAX - *size) < LYXP_STRING_CAST_SIZE_STEP) {
416
0
                LOGERR(ctx, LY_EINVAL, "XPath string length limit (%" PRIu32 ") reached.", UINT32_MAX);
417
0
                return LY_EINVAL;
418
0
            }
419
0
            *size += LYXP_STRING_CAST_SIZE_STEP;
420
0
        } while (*size - (unsigned)*used < needed);
421
0
        *str = ly_realloc(*str, *size * sizeof(char));
422
0
        LY_CHECK_ERR_RET(!(*str), LOGMEM(ctx), LY_EMEM);
423
0
    }
424
425
0
    return LY_SUCCESS;
426
0
}
427
428
/**
429
 * @brief Cast nodes recursively to one string @p str.
430
 *
431
 * @param[in] node Node to cast, NULL if root.
432
 * @param[in] set XPath set.
433
 * @param[in] indent Current indent.
434
 * @param[in,out] str Resulting string.
435
 * @param[in,out] used Used bytes in @p str.
436
 * @param[in,out] size Allocated bytes in @p str.
437
 * @return LY_ERR value.
438
 */
439
static LY_ERR
440
cast_string_recursive(const struct lyd_node *node, struct lyxp_set *set, uint32_t indent, char **str, uint32_t *used,
441
        uint32_t *size)
442
0
{
443
0
    char *buf = NULL, *line, *ptr = NULL;
444
0
    const char *value_str;
445
0
    uint16_t nodetype;
446
0
    const struct lyd_node *child;
447
0
    enum lyxp_node_type child_type;
448
0
    struct lyd_node_any *any;
449
0
    LY_ERR rc;
450
451
0
    if ((set->root_type == LYXP_NODE_ROOT_CONFIG) && node && node->schema && (node->schema->flags & LYS_CONFIG_R)) {
452
0
        return LY_SUCCESS;
453
0
    }
454
455
0
    if (!node) {
456
        /* fake container */
457
0
        LY_CHECK_RET(cast_string_realloc(set->ctx, 1, str, used, size));
458
0
        strcpy(*str + (*used - 1), "\n");
459
0
        ++(*used);
460
461
0
        ++indent;
462
463
        /* print all the top-level nodes */
464
0
        child = NULL;
465
0
        child_type = 0;
466
0
        while (!moveto_axis_node_next(&child, &child_type, NULL, set->root_type, LYXP_AXIS_CHILD, set)) {
467
0
            LY_CHECK_RET(cast_string_recursive(child, set, indent, str, used, size));
468
0
        }
469
470
        /* end fake container */
471
0
        LY_CHECK_RET(cast_string_realloc(set->ctx, 1, str, used, size));
472
0
        strcpy(*str + (*used - 1), "\n");
473
0
        ++(*used);
474
475
0
        --indent;
476
0
    } else {
477
0
        if (node->schema) {
478
0
            nodetype = node->schema->nodetype;
479
0
        } else if (lyd_child(node)) {
480
0
            nodetype = LYS_CONTAINER;
481
0
        } else {
482
0
            nodetype = LYS_LEAF;
483
0
        }
484
485
0
        switch (nodetype) {
486
0
        case LYS_CONTAINER:
487
0
        case LYS_LIST:
488
0
        case LYS_RPC:
489
0
        case LYS_NOTIF:
490
0
            LY_CHECK_RET(cast_string_realloc(set->ctx, 1, str, used, size));
491
0
            strcpy(*str + (*used - 1), "\n");
492
0
            ++(*used);
493
494
0
            for (child = lyd_child(node); child; child = child->next) {
495
0
                LY_CHECK_RET(cast_string_recursive(child, set, indent + 1, str, used, size));
496
0
            }
497
498
0
            break;
499
500
0
        case LYS_LEAF:
501
0
        case LYS_LEAFLIST:
502
0
            value_str = lyd_get_value(node);
503
504
            /* print indent */
505
0
            LY_CHECK_RET(cast_string_realloc(set->ctx, indent * 2 + strlen(value_str) + 1, str, used, size));
506
0
            memset(*str + (*used - 1), ' ', indent * 2);
507
0
            *used += indent * 2;
508
509
            /* print value */
510
0
            if (*used == 1) {
511
0
                sprintf(*str + (*used - 1), "%s", value_str);
512
0
                *used += strlen(value_str);
513
0
            } else {
514
0
                sprintf(*str + (*used - 1), "%s\n", value_str);
515
0
                *used += strlen(value_str) + 1;
516
0
            }
517
518
0
            break;
519
520
0
        case LYS_ANYXML:
521
0
        case LYS_ANYDATA:
522
0
            any = (struct lyd_node_any *)node;
523
0
            if (!any->child && !any->value) {
524
                /* no content */
525
0
                buf = strdup("");
526
0
                LY_CHECK_ERR_RET(!buf, LOGMEM(set->ctx), LY_EMEM);
527
0
            } else {
528
0
                struct ly_out *out;
529
530
0
                if (any->value) {
531
0
                    buf = strdup(any->value);
532
0
                    LY_CHECK_ERR_RET(!buf, LOGMEM(set->ctx), LY_EMEM);
533
0
                } else {
534
0
                    LY_CHECK_RET(ly_out_new_memory(&buf, 0, &out));
535
0
                    rc = lyd_print_all(out, any->child, LYD_XML, 0);
536
0
                    ly_out_free(out, NULL, 0);
537
0
                    LY_CHECK_RET(rc);
538
0
                }
539
0
            }
540
541
0
            line = strtok_r(buf, "\n", &ptr);
542
0
            do {
543
0
                rc = cast_string_realloc(set->ctx, indent * 2 + strlen(line) + 1, str, used, size);
544
0
                if (rc != LY_SUCCESS) {
545
0
                    free(buf);
546
0
                    return rc;
547
0
                }
548
0
                memset(*str + (*used - 1), ' ', indent * 2);
549
0
                *used += indent * 2;
550
551
0
                strcpy(*str + (*used - 1), line);
552
0
                *used += strlen(line);
553
554
0
                strcpy(*str + (*used - 1), "\n");
555
0
                *used += 1;
556
0
            } while ((line = strtok_r(NULL, "\n", &ptr)));
557
558
0
            free(buf);
559
0
            break;
560
561
0
        default:
562
0
            LOGINT_RET(set->ctx);
563
0
        }
564
0
    }
565
566
0
    return LY_SUCCESS;
567
0
}
568
569
/**
570
 * @brief Cast an element into a string.
571
 *
572
 * @param[in] node Node to cast, NULL if root.
573
 * @param[in] set XPath set.
574
 * @param[out] str Element cast to dynamically-allocated string.
575
 * @return LY_ERR
576
 */
577
static LY_ERR
578
cast_string_elem(const struct lyd_node *node, struct lyxp_set *set, char **str)
579
0
{
580
0
    uint32_t used, size;
581
0
    LY_ERR rc;
582
583
0
    *str = malloc(LYXP_STRING_CAST_SIZE_START * sizeof(char));
584
0
    LY_CHECK_ERR_RET(!*str, LOGMEM(set->ctx), LY_EMEM);
585
0
    (*str)[0] = '\0';
586
0
    used = 1;
587
0
    size = LYXP_STRING_CAST_SIZE_START;
588
589
0
    rc = cast_string_recursive(node, set, 0, str, &used, &size);
590
0
    if (rc != LY_SUCCESS) {
591
0
        free(*str);
592
0
        return rc;
593
0
    }
594
595
0
    if (size > used) {
596
0
        *str = ly_realloc(*str, used * sizeof(char));
597
0
        LY_CHECK_ERR_RET(!*str, LOGMEM(set->ctx), LY_EMEM);
598
0
    }
599
0
    return LY_SUCCESS;
600
0
}
601
602
/**
603
 * @brief Cast a LYXP_SET_NODE_SET set into a string.
604
 *        Context position aware.
605
 *
606
 * @param[in] set Set to cast.
607
 * @param[out] str Cast dynamically-allocated string.
608
 * @return LY_ERR
609
 */
610
static LY_ERR
611
cast_node_set_to_string(struct lyxp_set *set, char **str)
612
0
{
613
0
    if (!set->used) {
614
0
        *str = strdup("");
615
0
        if (!*str) {
616
0
            LOGMEM_RET(set->ctx);
617
0
        }
618
0
        return LY_SUCCESS;
619
0
    }
620
621
0
    switch (set->val.nodes[0].type) {
622
0
    case LYXP_NODE_NONE:
623
        /* invalid */
624
0
        LOGINT_RET(set->ctx);
625
0
    case LYXP_NODE_ROOT:
626
0
    case LYXP_NODE_ROOT_CONFIG:
627
0
    case LYXP_NODE_ELEM:
628
0
    case LYXP_NODE_TEXT:
629
0
        return cast_string_elem(set->val.nodes[0].node, set, str);
630
0
    case LYXP_NODE_META:
631
0
        *str = strdup(lyd_get_meta_value(set->val.meta[0].meta));
632
0
        if (!*str) {
633
0
            LOGMEM_RET(set->ctx);
634
0
        }
635
0
        return LY_SUCCESS;
636
0
    }
637
638
0
    LOGINT_RET(set->ctx);
639
0
}
640
641
/**
642
 * @brief Cast a string into an XPath number.
643
 *
644
 * @param[in] str String to use.
645
 * @return Cast number.
646
 */
647
static long double
648
cast_string_to_number(const char *str)
649
0
{
650
0
    long double num;
651
0
    char *ptr;
652
653
0
    errno = 0;
654
0
    num = strtold(str, &ptr);
655
0
    if (errno || *ptr || (ptr == str)) {
656
0
        num = NAN;
657
0
    }
658
0
    return num;
659
0
}
660
661
/**
662
 * @brief Callback for checking value equality.
663
 *
664
 * Implementation of ::lyht_value_equal_cb.
665
 *
666
 * @param[in] val1_p First value.
667
 * @param[in] val2_p Second value.
668
 * @param[in] mod Whether hash table is being modified.
669
 * @param[in] cb_data Callback data.
670
 * @return Boolean value whether values are equal or not.
671
 */
672
static ly_bool
673
set_values_equal_cb(void *val1_p, void *val2_p, ly_bool UNUSED(mod), void *UNUSED(cb_data))
674
0
{
675
0
    struct lyxp_set_hash_node *val1, *val2;
676
677
0
    val1 = (struct lyxp_set_hash_node *)val1_p;
678
0
    val2 = (struct lyxp_set_hash_node *)val2_p;
679
680
0
    if ((val1->node == val2->node) && (val1->type == val2->type)) {
681
0
        return 1;
682
0
    }
683
684
0
    return 0;
685
0
}
686
687
/**
688
 * @brief Insert node and its hash into set.
689
 *
690
 * @param[in] set et to insert to.
691
 * @param[in] node Node with hash.
692
 * @param[in] type Node type.
693
 */
694
static void
695
set_insert_node_hash(struct lyxp_set *set, struct lyd_node *node, enum lyxp_node_type type)
696
0
{
697
0
    LY_ERR r;
698
0
    uint32_t i, hash;
699
0
    struct lyxp_set_hash_node hnode;
700
701
0
    if (!set->ht && (set->used >= LYD_HT_MIN_ITEMS)) {
702
        /* create hash table and add all the nodes */
703
0
        set->ht = lyht_new(1, sizeof(struct lyxp_set_hash_node), set_values_equal_cb, NULL, 1);
704
0
        for (i = 0; i < set->used; ++i) {
705
0
            hnode.node = set->val.nodes[i].node;
706
0
            hnode.type = set->val.nodes[i].type;
707
708
0
            hash = lyht_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
709
0
            hash = lyht_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
710
0
            hash = lyht_hash_multi(hash, NULL, 0);
711
712
0
            r = lyht_insert(set->ht, &hnode, hash, NULL);
713
0
            assert(!r);
714
0
            (void)r;
715
716
0
            if ((hnode.node == node) && (hnode.type == type)) {
717
                /* it was just added, do not add it twice */
718
0
                return;
719
0
            }
720
0
        }
721
0
    }
722
723
0
    if (set->ht) {
724
        /* add the new node into hash table */
725
0
        hnode.node = node;
726
0
        hnode.type = type;
727
728
0
        hash = lyht_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
729
0
        hash = lyht_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
730
0
        hash = lyht_hash_multi(hash, NULL, 0);
731
732
0
        r = lyht_insert(set->ht, &hnode, hash, NULL);
733
0
        assert(!r);
734
0
        (void)r;
735
0
    }
736
0
}
737
738
/**
739
 * @brief Remove node and its hash from set.
740
 *
741
 * @param[in] set Set to remove from.
742
 * @param[in] node Node to remove.
743
 * @param[in] type Node type.
744
 */
745
static void
746
set_remove_node_hash(struct lyxp_set *set, struct lyd_node *node, enum lyxp_node_type type)
747
0
{
748
0
    LY_ERR r;
749
0
    struct lyxp_set_hash_node hnode;
750
0
    uint32_t hash;
751
752
0
    if (set->ht) {
753
0
        hnode.node = node;
754
0
        hnode.type = type;
755
756
0
        hash = lyht_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
757
0
        hash = lyht_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
758
0
        hash = lyht_hash_multi(hash, NULL, 0);
759
760
0
        r = lyht_remove(set->ht, &hnode, hash);
761
0
        assert(!r);
762
0
        (void)r;
763
764
0
        if (!set->ht->used) {
765
0
            lyht_free(set->ht, NULL);
766
0
            set->ht = NULL;
767
0
        }
768
0
    }
769
0
}
770
771
/**
772
 * @brief Check whether node is in set based on its hash.
773
 *
774
 * @param[in] set Set to search in.
775
 * @param[in] node Node to search for.
776
 * @param[in] type Node type.
777
 * @param[in] skip_idx Index in @p set to skip.
778
 * @return LY_ERR
779
 */
780
static LY_ERR
781
set_dup_node_hash_check(const struct lyxp_set *set, struct lyd_node *node, enum lyxp_node_type type, int skip_idx)
782
0
{
783
0
    struct lyxp_set_hash_node hnode, *match_p;
784
0
    uint32_t hash;
785
786
0
    hnode.node = node;
787
0
    hnode.type = type;
788
789
0
    hash = lyht_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
790
0
    hash = lyht_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
791
0
    hash = lyht_hash_multi(hash, NULL, 0);
792
793
0
    if (!lyht_find(set->ht, &hnode, hash, (void **)&match_p)) {
794
0
        if ((skip_idx > -1) && (set->val.nodes[skip_idx].node == match_p->node) && (set->val.nodes[skip_idx].type == match_p->type)) {
795
            /* we found it on the index that should be skipped, find another */
796
0
            hnode = *match_p;
797
0
            if (lyht_find_next(set->ht, &hnode, hash, (void **)&match_p)) {
798
                /* none other found */
799
0
                return LY_SUCCESS;
800
0
            }
801
0
        }
802
803
0
        return LY_EEXIST;
804
0
    }
805
806
    /* not found */
807
0
    return LY_SUCCESS;
808
0
}
809
810
void
811
lyxp_set_free_content(struct lyxp_set *set)
812
0
{
813
0
    if (!set) {
814
0
        return;
815
0
    }
816
817
0
    if (set->type == LYXP_SET_NODE_SET) {
818
0
        free(set->val.nodes);
819
0
        lyht_free(set->ht, NULL);
820
0
    } else if (set->type == LYXP_SET_SCNODE_SET) {
821
0
        free(set->val.scnodes);
822
0
        lyht_free(set->ht, NULL);
823
0
    } else {
824
0
        if (set->type == LYXP_SET_STRING) {
825
0
            free(set->val.str);
826
0
        }
827
0
        set->type = LYXP_SET_NODE_SET;
828
0
    }
829
830
0
    set->val.nodes = NULL;
831
0
    set->used = 0;
832
0
    set->size = 0;
833
0
    set->ht = NULL;
834
0
    set->ctx_pos = 0;
835
0
    set->ctx_size = 0;
836
0
}
837
838
/**
839
 * @brief Free dynamically-allocated set.
840
 *
841
 * @param[in] set Set to free.
842
 */
843
static void
844
lyxp_set_free(struct lyxp_set *set)
845
0
{
846
0
    if (!set) {
847
0
        return;
848
0
    }
849
850
0
    lyxp_set_free_content(set);
851
0
    free(set);
852
0
}
853
854
/**
855
 * @brief Initialize set context.
856
 *
857
 * @param[in] new Set to initialize.
858
 * @param[in] set Arbitrary initialized set.
859
 */
860
static void
861
set_init(struct lyxp_set *new, const struct lyxp_set *set)
862
0
{
863
0
    memset(new, 0, sizeof *new);
864
0
    if (!set) {
865
0
        return;
866
0
    }
867
868
0
    new->non_child_axis = set->non_child_axis;
869
0
    new->not_found = set->not_found;
870
0
    new->ctx = set->ctx;
871
0
    new->cur_node = set->cur_node;
872
0
    new->root_type = set->root_type;
873
0
    new->context_op = set->context_op;
874
0
    new->tree = set->tree;
875
0
    new->cur_mod = set->cur_mod;
876
0
    new->format = set->format;
877
0
    new->prefix_data = set->prefix_data;
878
0
    new->vars = set->vars;
879
0
}
880
881
/**
882
 * @brief Create a deep copy of a set.
883
 *
884
 * @param[in] set Set to copy.
885
 * @return Copy of @p set.
886
 */
887
static struct lyxp_set *
888
set_copy(struct lyxp_set *set)
889
0
{
890
0
    struct lyxp_set *ret;
891
0
    uint32_t i;
892
893
0
    if (!set) {
894
0
        return NULL;
895
0
    }
896
897
0
    ret = malloc(sizeof *ret);
898
0
    LY_CHECK_ERR_RET(!ret, LOGMEM(set->ctx), NULL);
899
0
    set_init(ret, set);
900
901
0
    if (set->type == LYXP_SET_SCNODE_SET) {
902
0
        ret->type = set->type;
903
904
0
        for (i = 0; i < set->used; ++i) {
905
0
            if ((set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_CTX) ||
906
0
                    (set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_START)) {
907
0
                uint32_t idx;
908
909
0
                LY_CHECK_ERR_RET(lyxp_set_scnode_insert_node(ret, set->val.scnodes[i].scnode, set->val.scnodes[i].type,
910
0
                        set->val.scnodes[i].axis, &idx), lyxp_set_free(ret), NULL);
911
                /* coverity seems to think scnodes can be NULL */
912
0
                if (!ret->val.scnodes) {
913
0
                    lyxp_set_free(ret);
914
0
                    return NULL;
915
0
                }
916
0
                ret->val.scnodes[idx].in_ctx = set->val.scnodes[i].in_ctx;
917
0
            }
918
0
        }
919
0
    } else if (set->type == LYXP_SET_NODE_SET) {
920
0
        ret->type = set->type;
921
0
        if (set->used) {
922
0
            ret->val.nodes = malloc(set->used * sizeof *ret->val.nodes);
923
0
            LY_CHECK_ERR_RET(!ret->val.nodes, LOGMEM(set->ctx); free(ret), NULL);
924
0
            memcpy(ret->val.nodes, set->val.nodes, set->used * sizeof *ret->val.nodes);
925
0
        } else {
926
0
            ret->val.nodes = NULL;
927
0
        }
928
929
0
        ret->used = ret->size = set->used;
930
0
        ret->ctx_pos = set->ctx_pos;
931
0
        ret->ctx_size = set->ctx_size;
932
0
        if (set->ht) {
933
0
            ret->ht = lyht_dup(set->ht);
934
0
        }
935
0
    } else {
936
0
        memcpy(ret, set, sizeof *ret);
937
0
        if (set->type == LYXP_SET_STRING) {
938
0
            ret->val.str = strdup(set->val.str);
939
0
            LY_CHECK_ERR_RET(!ret->val.str, LOGMEM(set->ctx); free(ret), NULL);
940
0
        }
941
0
    }
942
943
0
    return ret;
944
0
}
945
946
/**
947
 * @brief Fill XPath set with a string. Any current data are disposed of.
948
 *
949
 * @param[in] set Set to fill.
950
 * @param[in] string String to fill into \p set.
951
 * @param[in] str_len Length of \p string. 0 is a valid value!
952
 */
953
static void
954
set_fill_string(struct lyxp_set *set, const char *string, uint32_t str_len)
955
0
{
956
0
    lyxp_set_free_content(set);
957
958
0
    set->type = LYXP_SET_STRING;
959
0
    if ((str_len == 0) && (string[0] != '\0')) {
960
0
        string = "";
961
0
    }
962
0
    set->val.str = strndup(string, str_len);
963
0
}
964
965
/**
966
 * @brief Fill XPath set with a number. Any current data are disposed of.
967
 *
968
 * @param[in] set Set to fill.
969
 * @param[in] number Number to fill into \p set.
970
 */
971
static void
972
set_fill_number(struct lyxp_set *set, long double number)
973
0
{
974
0
    lyxp_set_free_content(set);
975
976
0
    set->type = LYXP_SET_NUMBER;
977
0
    set->val.num = number;
978
0
}
979
980
/**
981
 * @brief Fill XPath set with a boolean. Any current data are disposed of.
982
 *
983
 * @param[in] set Set to fill.
984
 * @param[in] boolean Boolean to fill into \p set.
985
 */
986
static void
987
set_fill_boolean(struct lyxp_set *set, ly_bool boolean)
988
0
{
989
0
    lyxp_set_free_content(set);
990
991
0
    set->type = LYXP_SET_BOOLEAN;
992
0
    set->val.bln = boolean;
993
0
}
994
995
/**
996
 * @brief Fill XPath set with the value from another set (deep assign).
997
 *        Any current data are disposed of.
998
 *
999
 * @param[in] trg Set to fill.
1000
 * @param[in] src Source set to copy into \p trg.
1001
 */
1002
static void
1003
set_fill_set(struct lyxp_set *trg, const struct lyxp_set *src)
1004
0
{
1005
0
    if (!trg || !src) {
1006
0
        return;
1007
0
    }
1008
1009
0
    lyxp_set_free_content(trg);
1010
0
    set_init(trg, src);
1011
1012
0
    if (src->type == LYXP_SET_SCNODE_SET) {
1013
0
        trg->type = LYXP_SET_SCNODE_SET;
1014
0
        trg->used = src->used;
1015
0
        trg->size = src->used;
1016
1017
0
        if (trg->size) {
1018
0
            trg->val.scnodes = ly_realloc(trg->val.scnodes, trg->size * sizeof *trg->val.scnodes);
1019
0
            LY_CHECK_ERR_RET(!trg->val.scnodes, LOGMEM(src->ctx); memset(trg, 0, sizeof *trg), );
1020
0
            memcpy(trg->val.scnodes, src->val.scnodes, src->used * sizeof *src->val.scnodes);
1021
0
        } else {
1022
0
            trg->val.scnodes = NULL;
1023
0
        }
1024
0
    } else if (src->type == LYXP_SET_BOOLEAN) {
1025
0
        set_fill_boolean(trg, src->val.bln);
1026
0
    } else if (src->type == LYXP_SET_NUMBER) {
1027
0
        set_fill_number(trg, src->val.num);
1028
0
    } else if (src->type == LYXP_SET_STRING) {
1029
0
        set_fill_string(trg, src->val.str, strlen(src->val.str));
1030
0
    } else {
1031
0
        if (trg->type == LYXP_SET_NODE_SET) {
1032
0
            free(trg->val.nodes);
1033
0
        } else if (trg->type == LYXP_SET_STRING) {
1034
0
            free(trg->val.str);
1035
0
        }
1036
1037
0
        assert(src->type == LYXP_SET_NODE_SET);
1038
1039
0
        trg->type = LYXP_SET_NODE_SET;
1040
0
        trg->used = src->used;
1041
0
        trg->size = src->used;
1042
0
        trg->ctx_pos = src->ctx_pos;
1043
0
        trg->ctx_size = src->ctx_size;
1044
1045
0
        if (trg->size) {
1046
0
            trg->val.nodes = malloc(trg->size * sizeof *trg->val.nodes);
1047
0
            LY_CHECK_ERR_RET(!trg->val.nodes, LOGMEM(src->ctx); memset(trg, 0, sizeof *trg), );
1048
0
            memcpy(trg->val.nodes, src->val.nodes, src->used * sizeof *src->val.nodes);
1049
0
        } else {
1050
0
            trg->val.nodes = NULL;
1051
0
        }
1052
0
        if (src->ht) {
1053
0
            trg->ht = lyht_dup(src->ht);
1054
0
        } else {
1055
0
            trg->ht = NULL;
1056
0
        }
1057
0
    }
1058
0
}
1059
1060
/**
1061
 * @brief Clear context of all schema nodes.
1062
 *
1063
 * @param[in] set Set to clear.
1064
 * @param[in] new_ctx New context state for all the nodes currently in the context.
1065
 */
1066
static void
1067
set_scnode_clear_ctx(struct lyxp_set *set, int32_t new_ctx)
1068
0
{
1069
0
    uint32_t i;
1070
1071
0
    for (i = 0; i < set->used; ++i) {
1072
0
        if (set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_CTX) {
1073
0
            set->val.scnodes[i].in_ctx = new_ctx;
1074
0
        } else if (set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_START) {
1075
0
            set->val.scnodes[i].in_ctx = LYXP_SET_SCNODE_START_USED;
1076
0
        }
1077
0
    }
1078
0
}
1079
1080
/**
1081
 * @brief Remove a node from a set. Removing last node changes
1082
 *        set into LYXP_SET_EMPTY. Context position aware.
1083
 *
1084
 * @param[in] set Set to use.
1085
 * @param[in] idx Index from @p set of the node to be removed.
1086
 */
1087
static void
1088
set_remove_node(struct lyxp_set *set, uint32_t idx)
1089
0
{
1090
0
    assert(set && (set->type == LYXP_SET_NODE_SET));
1091
0
    assert(idx < set->used);
1092
1093
0
    set_remove_node_hash(set, set->val.nodes[idx].node, set->val.nodes[idx].type);
1094
1095
0
    --set->used;
1096
0
    if (idx < set->used) {
1097
0
        memmove(&set->val.nodes[idx], &set->val.nodes[idx + 1], (set->used - idx) * sizeof *set->val.nodes);
1098
0
    } else if (!set->used) {
1099
0
        lyxp_set_free_content(set);
1100
0
    }
1101
0
}
1102
1103
/**
1104
 * @brief Remove a node from a set by setting its type to LYXP_NODE_NONE.
1105
 *
1106
 * @param[in] set Set to use.
1107
 * @param[in] idx Index from @p set of the node to be removed.
1108
 */
1109
static void
1110
set_remove_node_none(struct lyxp_set *set, uint32_t idx)
1111
0
{
1112
0
    assert(set && (set->type == LYXP_SET_NODE_SET));
1113
0
    assert(idx < set->used);
1114
1115
0
    if (set->val.nodes[idx].type == LYXP_NODE_ELEM) {
1116
0
        set_remove_node_hash(set, set->val.nodes[idx].node, set->val.nodes[idx].type);
1117
0
    }
1118
0
    set->val.nodes[idx].type = LYXP_NODE_NONE;
1119
0
}
1120
1121
/**
1122
 * @brief Remove all LYXP_NODE_NONE nodes from a set. Removing last node changes
1123
 *        set into LYXP_SET_EMPTY. Context position aware.
1124
 *
1125
 * @param[in] set Set to consolidate.
1126
 */
1127
static void
1128
set_remove_nodes_none(struct lyxp_set *set)
1129
0
{
1130
0
    uint32_t i, orig_used, end = 0;
1131
0
    int64_t start;
1132
1133
0
    assert(set);
1134
1135
0
    orig_used = set->used;
1136
0
    set->used = 0;
1137
0
    for (i = 0; i < orig_used; ) {
1138
0
        start = -1;
1139
0
        do {
1140
0
            if ((set->val.nodes[i].type != LYXP_NODE_NONE) && (start == -1)) {
1141
0
                start = i;
1142
0
            } else if ((start > -1) && (set->val.nodes[i].type == LYXP_NODE_NONE)) {
1143
0
                end = i;
1144
0
                ++i;
1145
0
                break;
1146
0
            }
1147
1148
0
            ++i;
1149
0
            if (i == orig_used) {
1150
0
                end = i;
1151
0
            }
1152
0
        } while (i < orig_used);
1153
1154
0
        if (start > -1) {
1155
            /* move the whole chunk of valid nodes together */
1156
0
            if (set->used != (unsigned)start) {
1157
0
                memmove(&set->val.nodes[set->used], &set->val.nodes[start], (end - start) * sizeof *set->val.nodes);
1158
0
            }
1159
0
            set->used += end - start;
1160
0
        }
1161
0
    }
1162
0
}
1163
1164
/**
1165
 * @brief Check for duplicates in a node set.
1166
 *
1167
 * @param[in] set Set to check.
1168
 * @param[in] node Node to look for in @p set.
1169
 * @param[in] node_type Type of @p node.
1170
 * @param[in] skip_idx Index from @p set to skip.
1171
 * @return LY_ERR
1172
 */
1173
static LY_ERR
1174
set_dup_node_check(const struct lyxp_set *set, const struct lyd_node *node, enum lyxp_node_type node_type, int skip_idx)
1175
0
{
1176
0
    uint32_t i;
1177
1178
0
    if (set->ht && node) {
1179
0
        return set_dup_node_hash_check(set, (struct lyd_node *)node, node_type, skip_idx);
1180
0
    }
1181
1182
0
    for (i = 0; i < set->used; ++i) {
1183
0
        if ((skip_idx > -1) && (i == (unsigned)skip_idx)) {
1184
0
            continue;
1185
0
        }
1186
1187
0
        if ((set->val.nodes[i].node == node) && (set->val.nodes[i].type == node_type)) {
1188
0
            return LY_EEXIST;
1189
0
        }
1190
0
    }
1191
1192
0
    return LY_SUCCESS;
1193
0
}
1194
1195
ly_bool
1196
lyxp_set_scnode_contains(struct lyxp_set *set, const struct lysc_node *node, enum lyxp_node_type node_type, int skip_idx,
1197
        uint32_t *index_p)
1198
0
{
1199
0
    uint32_t i;
1200
1201
0
    for (i = 0; i < set->used; ++i) {
1202
0
        if ((skip_idx > -1) && (i == (unsigned)skip_idx)) {
1203
0
            continue;
1204
0
        }
1205
1206
0
        if ((set->val.scnodes[i].scnode == node) && (set->val.scnodes[i].type == node_type)) {
1207
0
            if (index_p) {
1208
0
                *index_p = i;
1209
0
            }
1210
0
            return 1;
1211
0
        }
1212
0
    }
1213
1214
0
    return 0;
1215
0
}
1216
1217
void
1218
lyxp_set_scnode_merge(struct lyxp_set *set1, struct lyxp_set *set2)
1219
0
{
1220
0
    uint32_t orig_used, i, j;
1221
1222
0
    assert((set1->type == LYXP_SET_SCNODE_SET) && (set2->type == LYXP_SET_SCNODE_SET));
1223
1224
0
    if (!set2->used) {
1225
0
        return;
1226
0
    }
1227
1228
0
    if (!set1->used) {
1229
        /* release hidden allocated data (lyxp_set.size) */
1230
0
        lyxp_set_free_content(set1);
1231
        /* direct copying of the entire structure */
1232
0
        memcpy(set1, set2, sizeof *set1);
1233
0
        return;
1234
0
    }
1235
1236
0
    if (set1->used + set2->used > set1->size) {
1237
0
        set1->size = set1->used + set2->used;
1238
0
        set1->val.scnodes = ly_realloc(set1->val.scnodes, set1->size * sizeof *set1->val.scnodes);
1239
0
        LY_CHECK_ERR_RET(!set1->val.scnodes, LOGMEM(set1->ctx), );
1240
0
    }
1241
1242
0
    orig_used = set1->used;
1243
1244
0
    for (i = 0; i < set2->used; ++i) {
1245
0
        for (j = 0; j < orig_used; ++j) {
1246
            /* detect duplicities */
1247
0
            if (set1->val.scnodes[j].scnode == set2->val.scnodes[i].scnode) {
1248
0
                break;
1249
0
            }
1250
0
        }
1251
1252
0
        if (j < orig_used) {
1253
            /* node is there, but update its status if needed */
1254
0
            if (set1->val.scnodes[j].in_ctx == LYXP_SET_SCNODE_START_USED) {
1255
0
                set1->val.scnodes[j].in_ctx = set2->val.scnodes[i].in_ctx;
1256
0
            } else if ((set1->val.scnodes[j].in_ctx == LYXP_SET_SCNODE_ATOM_NODE) &&
1257
0
                    (set2->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_VAL)) {
1258
0
                set1->val.scnodes[j].in_ctx = set2->val.scnodes[i].in_ctx;
1259
0
            }
1260
0
        } else {
1261
0
            memcpy(&set1->val.scnodes[set1->used], &set2->val.scnodes[i], sizeof *set2->val.scnodes);
1262
0
            ++set1->used;
1263
0
        }
1264
0
    }
1265
1266
0
    lyxp_set_free_content(set2);
1267
0
    set2->type = LYXP_SET_SCNODE_SET;
1268
0
}
1269
1270
/**
1271
 * @brief Insert a node into a set. Context position aware.
1272
 *
1273
 * @param[in] set Set to use.
1274
 * @param[in] node Node to insert to @p set.
1275
 * @param[in] pos Sort position of @p node. If left 0, it is filled just before sorting.
1276
 * @param[in] node_type Node type of @p node.
1277
 * @param[in] idx Index in @p set to insert into.
1278
 */
1279
static void
1280
set_insert_node(struct lyxp_set *set, const struct lyd_node *node, uint32_t pos, enum lyxp_node_type node_type, uint32_t idx)
1281
0
{
1282
0
    assert(set && (set->type == LYXP_SET_NODE_SET));
1283
1284
0
    if (!set->size) {
1285
        /* first item */
1286
0
        if (idx) {
1287
            /* no real harm done, but it is a bug */
1288
0
            LOGINT(set->ctx);
1289
0
            idx = 0;
1290
0
        }
1291
0
        set->val.nodes = malloc(LYXP_SET_SIZE_START * sizeof *set->val.nodes);
1292
0
        LY_CHECK_ERR_RET(!set->val.nodes, LOGMEM(set->ctx), );
1293
0
        set->type = LYXP_SET_NODE_SET;
1294
0
        set->used = 0;
1295
0
        set->size = LYXP_SET_SIZE_START;
1296
0
        set->ctx_pos = 1;
1297
0
        set->ctx_size = 1;
1298
0
        set->ht = NULL;
1299
0
    } else {
1300
        /* not an empty set */
1301
0
        if (set->used == set->size) {
1302
1303
            /* set is full */
1304
0
            set->val.nodes = ly_realloc(set->val.nodes, (set->size * LYXP_SET_SIZE_MUL_STEP) * sizeof *set->val.nodes);
1305
0
            LY_CHECK_ERR_RET(!set->val.nodes, LOGMEM(set->ctx), );
1306
0
            set->size *= LYXP_SET_SIZE_MUL_STEP;
1307
0
        }
1308
1309
0
        if (idx > set->used) {
1310
0
            LOGINT(set->ctx);
1311
0
            idx = set->used;
1312
0
        }
1313
1314
        /* make space for the new node */
1315
0
        if (idx < set->used) {
1316
0
            memmove(&set->val.nodes[idx + 1], &set->val.nodes[idx], (set->used - idx) * sizeof *set->val.nodes);
1317
0
        }
1318
0
    }
1319
1320
    /* finally assign the value */
1321
0
    set->val.nodes[idx].node = (struct lyd_node *)node;
1322
0
    set->val.nodes[idx].type = node_type;
1323
0
    set->val.nodes[idx].pos = pos;
1324
0
    ++set->used;
1325
1326
    /* add into hash table */
1327
0
    set_insert_node_hash(set, (struct lyd_node *)node, node_type);
1328
0
}
1329
1330
LY_ERR
1331
lyxp_set_scnode_insert_node(struct lyxp_set *set, const struct lysc_node *node, enum lyxp_node_type node_type,
1332
        enum lyxp_axis axis, uint32_t *index_p)
1333
0
{
1334
0
    uint32_t index;
1335
1336
0
    assert(set->type == LYXP_SET_SCNODE_SET);
1337
1338
0
    if (!set->size) {
1339
        /* first item */
1340
0
        set->val.scnodes = malloc(LYXP_SET_SIZE_START * sizeof *set->val.scnodes);
1341
0
        LY_CHECK_ERR_RET(!set->val.scnodes, LOGMEM(set->ctx), LY_EMEM);
1342
0
        set->type = LYXP_SET_SCNODE_SET;
1343
0
        set->used = 0;
1344
0
        set->size = LYXP_SET_SIZE_START;
1345
0
        set->ctx_pos = 1;
1346
0
        set->ctx_size = 1;
1347
0
        set->ht = NULL;
1348
0
    }
1349
1350
0
    if (lyxp_set_scnode_contains(set, node, node_type, -1, &index)) {
1351
        /* BUG if axes differ, this new one is thrown away */
1352
0
        set->val.scnodes[index].in_ctx = LYXP_SET_SCNODE_ATOM_CTX;
1353
0
    } else {
1354
0
        if (set->used == set->size) {
1355
0
            set->val.scnodes = ly_realloc(set->val.scnodes, (set->size * LYXP_SET_SIZE_MUL_STEP) * sizeof *set->val.scnodes);
1356
0
            LY_CHECK_ERR_RET(!set->val.scnodes, LOGMEM(set->ctx), LY_EMEM);
1357
0
            set->size *= LYXP_SET_SIZE_MUL_STEP;
1358
0
        }
1359
1360
0
        index = set->used;
1361
0
        set->val.scnodes[index].scnode = (struct lysc_node *)node;
1362
0
        set->val.scnodes[index].type = node_type;
1363
0
        set->val.scnodes[index].in_ctx = LYXP_SET_SCNODE_ATOM_CTX;
1364
0
        set->val.scnodes[index].axis = axis;
1365
0
        ++set->used;
1366
0
    }
1367
1368
0
    if (index_p) {
1369
0
        *index_p = index;
1370
0
    }
1371
1372
0
    return LY_SUCCESS;
1373
0
}
1374
1375
/**
1376
 * @brief Set all nodes with ctx 1 to a new unique context value.
1377
 *
1378
 * @param[in] set Set to modify.
1379
 * @return New context value.
1380
 */
1381
static int32_t
1382
set_scnode_new_in_ctx(struct lyxp_set *set)
1383
0
{
1384
0
    uint32_t i;
1385
0
    int32_t ret_ctx;
1386
1387
0
    assert(set->type == LYXP_SET_SCNODE_SET);
1388
1389
0
    ret_ctx = LYXP_SET_SCNODE_ATOM_PRED_CTX;
1390
0
retry:
1391
0
    for (i = 0; i < set->used; ++i) {
1392
0
        if (set->val.scnodes[i].in_ctx >= ret_ctx) {
1393
0
            ret_ctx = set->val.scnodes[i].in_ctx + 1;
1394
0
            goto retry;
1395
0
        }
1396
0
    }
1397
0
    for (i = 0; i < set->used; ++i) {
1398
0
        if (set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_CTX) {
1399
0
            set->val.scnodes[i].in_ctx = ret_ctx;
1400
0
        }
1401
0
    }
1402
1403
0
    return ret_ctx;
1404
0
}
1405
1406
/**
1407
 * @brief Get unique @p node position in the data.
1408
 *
1409
 * @param[in] node Node to find.
1410
 * @param[in] node_type Node type of @p node.
1411
 * @param[in] root Root node.
1412
 * @param[in] root_type Type of the XPath @p root node.
1413
 * @param[in] prev Node that we think is before @p node in DFS from @p root. Can optionally
1414
 * be used to increase efficiency and start the DFS from this node.
1415
 * @param[in] prev_pos Node @p prev position. Optional, but must be set if @p prev is set.
1416
 * @return Node position.
1417
 */
1418
static uint32_t
1419
get_node_pos(const struct lyd_node *node, enum lyxp_node_type node_type, const struct lyd_node *root,
1420
        enum lyxp_node_type root_type, const struct lyd_node **prev, uint32_t *prev_pos)
1421
0
{
1422
0
    const struct lyd_node *elem = NULL, *top_sibling;
1423
0
    uint32_t pos = 1;
1424
0
    ly_bool found = 0;
1425
1426
0
    assert(prev && prev_pos && !root->prev->next);
1427
1428
0
    if ((node_type == LYXP_NODE_ROOT) || (node_type == LYXP_NODE_ROOT_CONFIG)) {
1429
0
        return 0;
1430
0
    }
1431
1432
0
    if (*prev) {
1433
        /* start from the previous element instead from the root */
1434
0
        pos = *prev_pos;
1435
0
        for (top_sibling = *prev; top_sibling->parent; top_sibling = top_sibling->parent) {}
1436
0
        goto dfs_search;
1437
0
    }
1438
1439
0
    LY_LIST_FOR(root, top_sibling) {
1440
0
        LYD_TREE_DFS_BEGIN(top_sibling, elem) {
1441
0
dfs_search:
1442
0
            LYD_TREE_DFS_continue = 0;
1443
1444
0
            if (*prev && !elem) {
1445
                /* resume previous DFS */
1446
0
                elem = LYD_TREE_DFS_next = (struct lyd_node *)*prev;
1447
0
                LYD_TREE_DFS_continue = 0;
1448
0
            }
1449
1450
0
            if ((root_type == LYXP_NODE_ROOT_CONFIG) && elem->schema && (elem->schema->flags & LYS_CONFIG_R)) {
1451
                /* skip */
1452
0
                LYD_TREE_DFS_continue = 1;
1453
0
            } else {
1454
0
                if (elem == node) {
1455
0
                    found = 1;
1456
0
                    break;
1457
0
                }
1458
0
                ++pos;
1459
0
            }
1460
1461
0
            LYD_TREE_ANY_DFS_END(top_sibling, elem);
1462
0
        }
1463
1464
        /* node found */
1465
0
        if (found) {
1466
0
            break;
1467
0
        }
1468
0
    }
1469
1470
0
    if (!found) {
1471
0
        if (!(*prev)) {
1472
            /* we went from root and failed to find it, cannot be */
1473
0
            LOGINT(LYD_CTX(node));
1474
0
            return 0;
1475
0
        } else {
1476
            /* start the search again from the beginning */
1477
0
            *prev = root;
1478
1479
0
            top_sibling = root;
1480
0
            pos = 1;
1481
0
            goto dfs_search;
1482
0
        }
1483
0
    }
1484
1485
    /* remember the last found node for next time */
1486
0
    *prev = node;
1487
0
    *prev_pos = pos;
1488
1489
0
    return pos;
1490
0
}
1491
1492
/**
1493
 * @brief Assign (fill) missing node positions.
1494
 *
1495
 * @param[in] set Set to fill positions in.
1496
 * @param[in] root Context root node.
1497
 * @param[in] root_type Context root type.
1498
 * @return LY_ERR
1499
 */
1500
static LY_ERR
1501
set_assign_pos(struct lyxp_set *set, const struct lyd_node *root, enum lyxp_node_type root_type)
1502
0
{
1503
0
    const struct lyd_node *prev = NULL, *tmp_node;
1504
0
    uint32_t i, tmp_pos = 0;
1505
1506
0
    for (i = 0; i < set->used; ++i) {
1507
0
        if (!set->val.nodes[i].pos) {
1508
0
            tmp_node = NULL;
1509
0
            switch (set->val.nodes[i].type) {
1510
0
            case LYXP_NODE_META:
1511
0
                tmp_node = set->val.meta[i].meta->parent;
1512
0
                if (!tmp_node) {
1513
0
                    LOGINT_RET(root->schema->module->ctx);
1514
0
                }
1515
            /* fall through */
1516
0
            case LYXP_NODE_ELEM:
1517
0
            case LYXP_NODE_TEXT:
1518
0
                if (!tmp_node) {
1519
0
                    tmp_node = set->val.nodes[i].node;
1520
0
                }
1521
0
                set->val.nodes[i].pos = get_node_pos(tmp_node, set->val.nodes[i].type, root, root_type, &prev, &tmp_pos);
1522
0
                break;
1523
0
            default:
1524
                /* all roots have position 0 */
1525
0
                break;
1526
0
            }
1527
0
        }
1528
0
    }
1529
1530
0
    return LY_SUCCESS;
1531
0
}
1532
1533
/**
1534
 * @brief Get unique @p meta position in the parent metadata.
1535
 *
1536
 * @param[in] meta Metadata to use.
1537
 * @return Metadata position.
1538
 */
1539
static uint32_t
1540
get_meta_pos(struct lyd_meta *meta)
1541
0
{
1542
0
    uint32_t pos = 0;
1543
0
    struct lyd_meta *meta2;
1544
1545
0
    for (meta2 = meta->parent->meta; meta2 && (meta2 != meta); meta2 = meta2->next) {
1546
0
        ++pos;
1547
0
    }
1548
1549
0
    assert(meta2);
1550
0
    return pos;
1551
0
}
1552
1553
/**
1554
 * @brief Compare 2 nodes in respect to XPath document order.
1555
 *
1556
 * @param[in] item1 1st node.
1557
 * @param[in] item2 2nd node.
1558
 * @return If 1st > 2nd returns 1, 1st == 2nd returns 0, and 1st < 2nd returns -1.
1559
 */
1560
static int
1561
set_sort_compare(struct lyxp_set_node *item1, struct lyxp_set_node *item2)
1562
0
{
1563
0
    uint32_t meta_pos1 = 0, meta_pos2 = 0;
1564
1565
0
    if (item1->pos < item2->pos) {
1566
0
        return -1;
1567
0
    }
1568
1569
0
    if (item1->pos > item2->pos) {
1570
0
        return 1;
1571
0
    }
1572
1573
    /* node positions are equal, the fun case */
1574
1575
    /* 1st ELEM - == - 2nd TEXT, 1st TEXT - == - 2nd ELEM */
1576
    /* special case since text nodes are actually saved as their parents */
1577
0
    if ((item1->node == item2->node) && (item1->type != item2->type)) {
1578
0
        if (item1->type == LYXP_NODE_ELEM) {
1579
0
            assert(item2->type == LYXP_NODE_TEXT);
1580
0
            return -1;
1581
0
        } else {
1582
0
            assert((item1->type == LYXP_NODE_TEXT) && (item2->type == LYXP_NODE_ELEM));
1583
0
            return 1;
1584
0
        }
1585
0
    }
1586
1587
    /* we need meta positions now */
1588
0
    if (item1->type == LYXP_NODE_META) {
1589
0
        meta_pos1 = get_meta_pos((struct lyd_meta *)item1->node);
1590
0
    }
1591
0
    if (item2->type == LYXP_NODE_META) {
1592
0
        meta_pos2 = get_meta_pos((struct lyd_meta *)item2->node);
1593
0
    }
1594
1595
    /* 1st ROOT - 2nd ROOT, 1st ELEM - 2nd ELEM, 1st TEXT - 2nd TEXT, 1st META - =pos= - 2nd META */
1596
    /* check for duplicates */
1597
0
    if (item1->node == item2->node) {
1598
0
        assert((item1->type == item2->type) && ((item1->type != LYXP_NODE_META) || (meta_pos1 == meta_pos2)));
1599
0
        return 0;
1600
0
    }
1601
1602
    /* 1st ELEM - 2nd TEXT, 1st ELEM - any pos - 2nd META */
1603
    /* elem is always first, 2nd node is after it */
1604
0
    if (item1->type == LYXP_NODE_ELEM) {
1605
0
        assert(item2->type != LYXP_NODE_ELEM);
1606
0
        return -1;
1607
0
    }
1608
1609
    /* 1st TEXT - 2nd ELEM, 1st TEXT - any pos - 2nd META, 1st META - any pos - 2nd ELEM, 1st META - >pos> - 2nd META */
1610
    /* 2nd is before 1st */
1611
0
    if (((item1->type == LYXP_NODE_TEXT) &&
1612
0
            ((item2->type == LYXP_NODE_ELEM) || (item2->type == LYXP_NODE_META))) ||
1613
0
            ((item1->type == LYXP_NODE_META) && (item2->type == LYXP_NODE_ELEM)) ||
1614
0
            (((item1->type == LYXP_NODE_META) && (item2->type == LYXP_NODE_META)) &&
1615
0
            (meta_pos1 > meta_pos2))) {
1616
0
        return 1;
1617
0
    }
1618
1619
    /* 1st META - any pos - 2nd TEXT, 1st META <pos< - 2nd META */
1620
    /* 2nd is after 1st */
1621
0
    return -1;
1622
0
}
1623
1624
/**
1625
 * @brief Set cast for comparisons.
1626
 *
1627
 * @param[in,out] trg Target set to cast source into.
1628
 * @param[in] src Source set.
1629
 * @param[in] type Target set type.
1630
 * @param[in] src_idx Source set node index.
1631
 * @return LY_SUCCESS on success.
1632
 * @return LY_ERR value on error.
1633
 */
1634
static LY_ERR
1635
set_comp_cast(struct lyxp_set *trg, const struct lyxp_set *src, enum lyxp_set_type type, uint32_t src_idx)
1636
0
{
1637
0
    assert(src->type == LYXP_SET_NODE_SET);
1638
1639
0
    set_init(trg, src);
1640
1641
    /* insert node into target set */
1642
0
    set_insert_node(trg, src->val.nodes[src_idx].node, src->val.nodes[src_idx].pos, src->val.nodes[src_idx].type, 0);
1643
1644
    /* cast target set appropriately */
1645
0
    return lyxp_set_cast(trg, type);
1646
0
}
1647
1648
/**
1649
 * @brief Set content canonization for comparisons.
1650
 *
1651
 * @param[in,out] set Set to canonize.
1652
 * @param[in] xp_node Source XPath node/meta to use for canonization.
1653
 * @return LY_SUCCESS on success.
1654
 * @return LY_ERR value on error.
1655
 */
1656
static LY_ERR
1657
set_comp_canonize(struct lyxp_set *set, const struct lyxp_set_node *xp_node)
1658
0
{
1659
0
    const struct lysc_type *type = NULL;
1660
0
    const char *canon;
1661
0
    LY_ERR r;
1662
0
    struct lyplg_type *type_plg;
1663
1664
    /* is there anything to canonize even? */
1665
0
    if (set->type == LYXP_SET_STRING) {
1666
        /* do we have a type to use for canonization? */
1667
0
        if ((xp_node->type == LYXP_NODE_ELEM) && xp_node->node->schema && (xp_node->node->schema->nodetype & LYD_NODE_TERM)) {
1668
0
            type = ((struct lyd_node_term *)xp_node->node)->value.realtype;
1669
0
        } else if (xp_node->type == LYXP_NODE_META) {
1670
0
            type = ((struct lyd_meta *)xp_node->node)->value.realtype;
1671
0
        }
1672
0
    }
1673
0
    if (!type) {
1674
        /* no canonization needed/possible */
1675
0
        return LY_SUCCESS;
1676
0
    }
1677
1678
    /* check for built-in types without required canonization */
1679
0
    type_plg = LYSC_GET_TYPE_PLG(type->plugin_ref);
1680
0
    if (!strncmp(type_plg->id, "ly2", 3) && ((type->basetype == LY_TYPE_STRING) || (type->basetype == LY_TYPE_BOOL) ||
1681
0
            (type->basetype == LY_TYPE_ENUM))) {
1682
        /* string, boolean, enumeration */
1683
0
        return LY_SUCCESS;
1684
0
    }
1685
1686
    /* print canonized string, ignore errors, the value may not satisfy schema constraints */
1687
0
    r = lyd_value_validate3(xp_node->node->schema, set->val.str, strlen(set->val.str), set->format, set->prefix_data,
1688
0
            LYD_HINT_DATA, NULL, 0, NULL, &canon);
1689
0
    if (r && (r != LY_EINCOMPLETE)) {
1690
        /* invalid value, fine */
1691
0
        return LY_SUCCESS;
1692
0
    }
1693
1694
    /* use the canonized string value */
1695
0
    free(set->val.str);
1696
0
    set->val.str = strdup(canon);
1697
0
    lydict_remove(set->ctx, canon);
1698
0
    LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), LY_EMEM);
1699
1700
0
    return LY_SUCCESS;
1701
0
}
1702
1703
/**
1704
 * @brief Bubble sort @p set into XPath document order.
1705
 *        Context position aware.
1706
 *
1707
 * @param[in] set Set to sort.
1708
 * @return How many times the whole set was traversed - 1 (if set was sorted, returns 0).
1709
 */
1710
static int
1711
set_sort(struct lyxp_set *set)
1712
0
{
1713
0
    uint32_t i, j;
1714
0
    int ret = 0, cmp;
1715
0
    ly_bool inverted, change;
1716
0
    const struct lyd_node *root;
1717
0
    struct lyxp_set_node item;
1718
0
    struct lyxp_set_hash_node hnode;
1719
0
    uint64_t hash;
1720
1721
0
    if ((set->type != LYXP_SET_NODE_SET) || (set->used < 2)) {
1722
0
        return 0;
1723
0
    }
1724
1725
    /* find first top-level node to be used as anchor for positions */
1726
0
    for (root = set->tree; root->parent; root = root->parent) {}
1727
0
    for ( ; root->prev->next; root = root->prev) {}
1728
1729
    /* fill positions */
1730
0
    if (set_assign_pos(set, root, set->root_type)) {
1731
0
        return -1;
1732
0
    }
1733
1734
0
#ifndef NDEBUG
1735
0
    LOGDBG(LY_LDGXPATH, "SORT BEGIN");
1736
0
    print_set_debug(set);
1737
0
#endif
1738
1739
0
    for (i = 0; i < set->used; ++i) {
1740
0
        inverted = 0;
1741
0
        change = 0;
1742
1743
0
        for (j = 1; j < set->used - i; ++j) {
1744
            /* compare node positions */
1745
0
            if (inverted) {
1746
0
                cmp = set_sort_compare(&set->val.nodes[j], &set->val.nodes[j - 1]);
1747
0
            } else {
1748
0
                cmp = set_sort_compare(&set->val.nodes[j - 1], &set->val.nodes[j]);
1749
0
            }
1750
1751
            /* swap if needed */
1752
0
            if ((inverted && (cmp < 0)) || (!inverted && (cmp > 0))) {
1753
0
                change = 1;
1754
1755
0
                item = set->val.nodes[j - 1];
1756
0
                set->val.nodes[j - 1] = set->val.nodes[j];
1757
0
                set->val.nodes[j] = item;
1758
0
            } else {
1759
                /* whether node_pos1 should be smaller than node_pos2 or the other way around */
1760
0
                inverted = !inverted;
1761
0
            }
1762
0
        }
1763
1764
0
        ++ret;
1765
1766
0
        if (!change) {
1767
0
            break;
1768
0
        }
1769
0
    }
1770
1771
0
#ifndef NDEBUG
1772
0
    LOGDBG(LY_LDGXPATH, "SORT END %d", ret);
1773
0
    print_set_debug(set);
1774
0
#endif
1775
1776
    /* check node hashes */
1777
0
    if (set->used >= LYD_HT_MIN_ITEMS) {
1778
0
        assert(set->ht);
1779
0
        for (i = 0; i < set->used; ++i) {
1780
0
            hnode.node = set->val.nodes[i].node;
1781
0
            hnode.type = set->val.nodes[i].type;
1782
1783
0
            hash = lyht_hash_multi(0, (const char *)&hnode.node, sizeof hnode.node);
1784
0
            hash = lyht_hash_multi(hash, (const char *)&hnode.type, sizeof hnode.type);
1785
0
            hash = lyht_hash_multi(hash, NULL, 0);
1786
1787
0
            assert(!lyht_find(set->ht, &hnode, hash, NULL));
1788
0
        }
1789
0
    }
1790
1791
0
    return ret - 1;
1792
0
}
1793
1794
/**
1795
 * @brief Merge 2 sorted sets into one.
1796
 *
1797
 * @param[in,out] trg Set to merge into. Duplicates are removed.
1798
 * @param[in] src Set to be merged into @p trg. It is cast to #LYXP_SET_EMPTY on success.
1799
 * @return LY_ERR
1800
 */
1801
static LY_ERR
1802
set_sorted_merge(struct lyxp_set *trg, struct lyxp_set *src)
1803
0
{
1804
0
    uint32_t i, j, k, count, dup_count;
1805
0
    int cmp;
1806
0
    const struct lyd_node *root;
1807
1808
0
    if ((trg->type != LYXP_SET_NODE_SET) || (src->type != LYXP_SET_NODE_SET)) {
1809
0
        return LY_EINVAL;
1810
0
    }
1811
1812
0
    if (!src->used) {
1813
0
        return LY_SUCCESS;
1814
0
    } else if (!trg->used) {
1815
0
        set_fill_set(trg, src);
1816
0
        lyxp_set_free_content(src);
1817
0
        return LY_SUCCESS;
1818
0
    }
1819
1820
    /* find first top-level node to be used as anchor for positions */
1821
0
    for (root = trg->tree; root->parent; root = root->parent) {}
1822
0
    for ( ; root->prev->next; root = root->prev) {}
1823
1824
    /* fill positions */
1825
0
    if (set_assign_pos(trg, root, trg->root_type) || set_assign_pos(src, root, src->root_type)) {
1826
0
        return LY_EINT;
1827
0
    }
1828
1829
0
#ifndef NDEBUG
1830
0
    LOGDBG(LY_LDGXPATH, "MERGE target");
1831
0
    print_set_debug(trg);
1832
0
    LOGDBG(LY_LDGXPATH, "MERGE source");
1833
0
    print_set_debug(src);
1834
0
#endif
1835
1836
    /* make memory for the merge (duplicates are not detected yet, so space
1837
     * will likely be wasted on them, too bad) */
1838
0
    if (trg->size - trg->used < src->used) {
1839
0
        trg->size = trg->used + src->used;
1840
1841
0
        trg->val.nodes = ly_realloc(trg->val.nodes, trg->size * sizeof *trg->val.nodes);
1842
0
        LY_CHECK_ERR_RET(!trg->val.nodes, LOGMEM(src->ctx), LY_EMEM);
1843
0
    }
1844
1845
0
    i = 0;
1846
0
    j = 0;
1847
0
    count = 0;
1848
0
    dup_count = 0;
1849
0
    do {
1850
0
        cmp = set_sort_compare(&src->val.nodes[i], &trg->val.nodes[j]);
1851
0
        if (!cmp) {
1852
0
            if (!count) {
1853
                /* duplicate, just skip it */
1854
0
                ++i;
1855
0
                ++j;
1856
0
            } else {
1857
                /* we are copying something already, so let's copy the duplicate too,
1858
                 * we are hoping that afterwards there are some more nodes to
1859
                 * copy and this way we can copy them all together */
1860
0
                ++count;
1861
0
                ++dup_count;
1862
0
                ++i;
1863
0
                ++j;
1864
0
            }
1865
0
        } else if (cmp < 0) {
1866
            /* inserting src node into trg, just remember it for now */
1867
0
            ++count;
1868
0
            ++i;
1869
1870
            /* insert the hash now */
1871
0
            set_insert_node_hash(trg, src->val.nodes[i - 1].node, src->val.nodes[i - 1].type);
1872
0
        } else if (count) {
1873
0
copy_nodes:
1874
            /* time to actually copy the nodes, we have found the largest block of nodes */
1875
0
            memmove(&trg->val.nodes[j + (count - dup_count)],
1876
0
                    &trg->val.nodes[j],
1877
0
                    (trg->used - j) * sizeof *trg->val.nodes);
1878
0
            memcpy(&trg->val.nodes[j - dup_count], &src->val.nodes[i - count], count * sizeof *src->val.nodes);
1879
1880
0
            trg->used += count - dup_count;
1881
            /* do not change i, except the copying above, we are basically doing exactly what is in the else branch below */
1882
0
            j += count - dup_count;
1883
1884
0
            count = 0;
1885
0
            dup_count = 0;
1886
0
        } else {
1887
0
            ++j;
1888
0
        }
1889
0
    } while ((i < src->used) && (j < trg->used));
1890
1891
0
    if ((i < src->used) || count) {
1892
        /* insert all the hashes first */
1893
0
        for (k = i; k < src->used; ++k) {
1894
0
            set_insert_node_hash(trg, src->val.nodes[k].node, src->val.nodes[k].type);
1895
0
        }
1896
1897
        /* loop ended, but we need to copy something at trg end */
1898
0
        count += src->used - i;
1899
0
        i = src->used;
1900
0
        goto copy_nodes;
1901
0
    }
1902
1903
    /* we are inserting hashes before the actual node insert, which causes
1904
     * situations when there were initially not enough items for a hash table,
1905
     * but even after some were inserted, hash table was not created (during
1906
     * insertion the number of items is not updated yet) */
1907
0
    if (!trg->ht && (trg->used >= LYD_HT_MIN_ITEMS)) {
1908
0
        set_insert_node_hash(trg, NULL, 0);
1909
0
    }
1910
1911
0
#ifndef NDEBUG
1912
0
    LOGDBG(LY_LDGXPATH, "MERGE result");
1913
0
    print_set_debug(trg);
1914
0
#endif
1915
1916
0
    lyxp_set_free_content(src);
1917
0
    return LY_SUCCESS;
1918
0
}
1919
1920
LY_ERR
1921
lyxp_check_token(const struct ly_ctx *ctx, const struct lyxp_expr *exp, uint32_t tok_idx, enum lyxp_token want_tok)
1922
0
{
1923
0
    if (exp->used == tok_idx) {
1924
0
        if (ctx) {
1925
0
            LOGVAL(ctx, NULL, LY_VCODE_XP_EOF);
1926
0
        }
1927
0
        return LY_EINCOMPLETE;
1928
0
    }
1929
1930
0
    if (want_tok && (exp->tokens[tok_idx] != want_tok)) {
1931
0
        if (ctx) {
1932
0
            LOGVAL(ctx, NULL, LY_VCODE_XP_INTOK2, lyxp_token2str(exp->tokens[tok_idx]),
1933
0
                    &exp->expr[exp->tok_pos[tok_idx]], lyxp_token2str(want_tok));
1934
0
        }
1935
0
        return LY_ENOT;
1936
0
    }
1937
1938
0
    return LY_SUCCESS;
1939
0
}
1940
1941
LY_ERR
1942
lyxp_next_token(const struct ly_ctx *ctx, const struct lyxp_expr *exp, uint32_t *tok_idx, enum lyxp_token want_tok)
1943
0
{
1944
0
    LY_CHECK_RET(lyxp_check_token(ctx, exp, *tok_idx, want_tok));
1945
1946
    /* skip the token */
1947
0
    ++(*tok_idx);
1948
1949
0
    return LY_SUCCESS;
1950
0
}
1951
1952
/* just like lyxp_check_token() but tests for 2 tokens */
1953
static LY_ERR
1954
exp_check_token2(const struct ly_ctx *ctx, const struct lyxp_expr *exp, uint32_t tok_idx, enum lyxp_token want_tok1,
1955
        enum lyxp_token want_tok2)
1956
0
{
1957
0
    if (exp->used == tok_idx) {
1958
0
        if (ctx) {
1959
0
            LOGVAL(ctx, NULL, LY_VCODE_XP_EOF);
1960
0
        }
1961
0
        return LY_EINCOMPLETE;
1962
0
    }
1963
1964
0
    if ((exp->tokens[tok_idx] != want_tok1) && (exp->tokens[tok_idx] != want_tok2)) {
1965
0
        if (ctx) {
1966
0
            LOGVAL(ctx, NULL, LY_VCODE_XP_INTOK, lyxp_token2str(exp->tokens[tok_idx]), &exp->expr[exp->tok_pos[tok_idx]]);
1967
0
        }
1968
0
        return LY_ENOT;
1969
0
    }
1970
1971
0
    return LY_SUCCESS;
1972
0
}
1973
1974
LY_ERR
1975
lyxp_next_token2(const struct ly_ctx *ctx, const struct lyxp_expr *exp, uint32_t *tok_idx, enum lyxp_token want_tok1,
1976
        enum lyxp_token want_tok2)
1977
0
{
1978
0
    LY_CHECK_RET(exp_check_token2(ctx, exp, *tok_idx, want_tok1, want_tok2));
1979
1980
    /* skip the token */
1981
0
    ++(*tok_idx);
1982
1983
0
    return LY_SUCCESS;
1984
0
}
1985
1986
/**
1987
 * @brief Stack operation push on the repeat array.
1988
 *
1989
 * @param[in] exp Expression to use.
1990
 * @param[in] tok_idx Position in the expresion @p exp.
1991
 * @param[in] repeat_expr_type Repeated expression type, this value is pushed.
1992
 */
1993
static void
1994
exp_repeat_push(struct lyxp_expr *exp, uint32_t tok_idx, enum lyxp_expr_type repeat_expr_type)
1995
0
{
1996
0
    uint32_t i;
1997
1998
0
    if (exp->repeat[tok_idx]) {
1999
0
        for (i = 0; exp->repeat[tok_idx][i]; ++i) {}
2000
0
        exp->repeat[tok_idx] = realloc(exp->repeat[tok_idx], (i + 2) * sizeof *exp->repeat[tok_idx]);
2001
0
        LY_CHECK_ERR_RET(!exp->repeat[tok_idx], LOGMEM(NULL), );
2002
0
        exp->repeat[tok_idx][i] = repeat_expr_type;
2003
0
        exp->repeat[tok_idx][i + 1] = 0;
2004
0
    } else {
2005
0
        exp->repeat[tok_idx] = calloc(2, sizeof *exp->repeat[tok_idx]);
2006
0
        LY_CHECK_ERR_RET(!exp->repeat[tok_idx], LOGMEM(NULL), );
2007
0
        exp->repeat[tok_idx][0] = repeat_expr_type;
2008
0
    }
2009
0
}
2010
2011
/**
2012
 * @brief Reparse Predicate. Logs directly on error.
2013
 *
2014
 * [7] Predicate ::= '[' Expr ']'
2015
 *
2016
 * @param[in] ctx Context for logging.
2017
 * @param[in] exp Parsed XPath expression.
2018
 * @param[in] tok_idx Position in the expression @p exp.
2019
 * @param[in] depth Current number of nested expressions.
2020
 * @return LY_ERR
2021
 */
2022
static LY_ERR
2023
reparse_predicate(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth)
2024
0
{
2025
0
    LY_ERR rc;
2026
2027
0
    rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_BRACK1);
2028
0
    LY_CHECK_RET(rc);
2029
0
    ++(*tok_idx);
2030
2031
0
    rc = reparse_or_expr(ctx, exp, tok_idx, depth);
2032
0
    LY_CHECK_RET(rc);
2033
2034
0
    rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_BRACK2);
2035
0
    LY_CHECK_RET(rc);
2036
0
    ++(*tok_idx);
2037
2038
0
    return LY_SUCCESS;
2039
0
}
2040
2041
/**
2042
 * @brief Reparse RelativeLocationPath. Logs directly on error.
2043
 *
2044
 * [4] RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step
2045
 * [5] Step ::= '@'? NodeTest Predicate* | '.' | '..'
2046
 * [6] NodeTest ::= NameTest | NodeType '(' ')'
2047
 *
2048
 * @param[in] ctx Context for logging.
2049
 * @param[in] exp Parsed XPath expression.
2050
 * @param[in] tok_idx Position in the expression \p exp.
2051
 * @param[in] depth Current number of nested expressions.
2052
 * @return LY_ERR (LY_EINCOMPLETE on forward reference)
2053
 */
2054
static LY_ERR
2055
reparse_relative_location_path(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth)
2056
0
{
2057
0
    LY_ERR rc;
2058
2059
0
    rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_NONE);
2060
0
    LY_CHECK_RET(rc);
2061
2062
0
    goto step;
2063
0
    do {
2064
        /* '/' or '//' */
2065
0
        ++(*tok_idx);
2066
2067
0
        rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_NONE);
2068
0
        LY_CHECK_RET(rc);
2069
0
step:
2070
        /* Step */
2071
0
        switch (exp->tokens[*tok_idx]) {
2072
0
        case LYXP_TOKEN_DOT:
2073
0
            ++(*tok_idx);
2074
0
            break;
2075
2076
0
        case LYXP_TOKEN_DDOT:
2077
0
            ++(*tok_idx);
2078
0
            break;
2079
2080
0
        case LYXP_TOKEN_AXISNAME:
2081
0
            ++(*tok_idx);
2082
2083
0
            rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_DCOLON);
2084
0
            LY_CHECK_RET(rc);
2085
2086
        /* fall through */
2087
0
        case LYXP_TOKEN_AT:
2088
0
            ++(*tok_idx);
2089
2090
0
            rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_NONE);
2091
0
            LY_CHECK_RET(rc);
2092
0
            if ((exp->tokens[*tok_idx] != LYXP_TOKEN_NAMETEST) && (exp->tokens[*tok_idx] != LYXP_TOKEN_NODETYPE)) {
2093
0
                LOGVAL(ctx, NULL, LY_VCODE_XP_INTOK, lyxp_token2str(exp->tokens[*tok_idx]), &exp->expr[exp->tok_pos[*tok_idx]]);
2094
0
                return LY_EVALID;
2095
0
            }
2096
0
            if (exp->tokens[*tok_idx] == LYXP_TOKEN_NODETYPE) {
2097
0
                goto reparse_nodetype;
2098
0
            }
2099
        /* fall through */
2100
0
        case LYXP_TOKEN_NAMETEST:
2101
0
            ++(*tok_idx);
2102
0
            goto reparse_predicate;
2103
2104
0
        case LYXP_TOKEN_NODETYPE:
2105
0
reparse_nodetype:
2106
0
            ++(*tok_idx);
2107
2108
            /* '(' */
2109
0
            rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_PAR1);
2110
0
            LY_CHECK_RET(rc);
2111
0
            ++(*tok_idx);
2112
2113
            /* ')' */
2114
0
            rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_PAR2);
2115
0
            LY_CHECK_RET(rc);
2116
0
            ++(*tok_idx);
2117
2118
0
reparse_predicate:
2119
            /* Predicate* */
2120
0
            while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_BRACK1)) {
2121
0
                rc = reparse_predicate(ctx, exp, tok_idx, depth);
2122
0
                LY_CHECK_RET(rc);
2123
0
            }
2124
0
            break;
2125
0
        default:
2126
0
            LOGVAL(ctx, NULL, LY_VCODE_XP_INTOK, lyxp_token2str(exp->tokens[*tok_idx]), &exp->expr[exp->tok_pos[*tok_idx]]);
2127
0
            return LY_EVALID;
2128
0
        }
2129
0
    } while (!exp_check_token2(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_PATH, LYXP_TOKEN_OPER_RPATH));
2130
2131
0
    return LY_SUCCESS;
2132
0
}
2133
2134
/**
2135
 * @brief Reparse AbsoluteLocationPath. Logs directly on error.
2136
 *
2137
 * [3] AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath
2138
 *
2139
 * @param[in] ctx Context for logging.
2140
 * @param[in] exp Parsed XPath expression.
2141
 * @param[in] tok_idx Position in the expression \p exp.
2142
 * @param[in] depth Current number of nested expressions.
2143
 * @return LY_ERR
2144
 */
2145
static LY_ERR
2146
reparse_absolute_location_path(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth)
2147
0
{
2148
0
    LY_ERR rc;
2149
2150
0
    LY_CHECK_RET(exp_check_token2(ctx, exp, *tok_idx, LYXP_TOKEN_OPER_PATH, LYXP_TOKEN_OPER_RPATH));
2151
2152
    /* '/' RelativeLocationPath? */
2153
0
    if (exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_PATH) {
2154
        /* '/' */
2155
0
        ++(*tok_idx);
2156
2157
0
        if (lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_NONE)) {
2158
0
            return LY_SUCCESS;
2159
0
        }
2160
0
        switch (exp->tokens[*tok_idx]) {
2161
0
        case LYXP_TOKEN_DOT:
2162
0
        case LYXP_TOKEN_DDOT:
2163
0
        case LYXP_TOKEN_AXISNAME:
2164
0
        case LYXP_TOKEN_AT:
2165
0
        case LYXP_TOKEN_NAMETEST:
2166
0
        case LYXP_TOKEN_NODETYPE:
2167
0
            rc = reparse_relative_location_path(ctx, exp, tok_idx, depth);
2168
0
            LY_CHECK_RET(rc);
2169
        /* fall through */
2170
0
        default:
2171
0
            break;
2172
0
        }
2173
2174
0
    } else {
2175
        /* '//' RelativeLocationPath */
2176
0
        ++(*tok_idx);
2177
2178
0
        rc = reparse_relative_location_path(ctx, exp, tok_idx, depth);
2179
0
        LY_CHECK_RET(rc);
2180
0
    }
2181
2182
0
    return LY_SUCCESS;
2183
0
}
2184
2185
/**
2186
 * @brief Reparse FunctionCall. Logs directly on error.
2187
 *
2188
 * [9] FunctionCall ::= FunctionName '(' ( Expr ( ',' Expr )* )? ')'
2189
 *
2190
 * @param[in] ctx Context for logging.
2191
 * @param[in] exp Parsed XPath expression.
2192
 * @param[in] tok_idx Position in the expression @p exp.
2193
 * @param[in] depth Current number of nested expressions.
2194
 * @return LY_ERR
2195
 */
2196
static LY_ERR
2197
reparse_function_call(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth)
2198
0
{
2199
0
    int8_t min_arg_count = -1;
2200
0
    uint32_t arg_count, max_arg_count = 0, func_tok_idx;
2201
0
    LY_ERR rc;
2202
2203
0
    rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_FUNCNAME);
2204
0
    LY_CHECK_RET(rc);
2205
0
    func_tok_idx = *tok_idx;
2206
0
    switch (exp->tok_len[*tok_idx]) {
2207
0
    case 3:
2208
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "not", 3)) {
2209
0
            min_arg_count = 1;
2210
0
            max_arg_count = 1;
2211
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "sum", 3)) {
2212
0
            min_arg_count = 1;
2213
0
            max_arg_count = 1;
2214
0
        }
2215
0
        break;
2216
0
    case 4:
2217
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "lang", 4)) {
2218
0
            min_arg_count = 1;
2219
0
            max_arg_count = 1;
2220
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "last", 4)) {
2221
0
            min_arg_count = 0;
2222
0
            max_arg_count = 0;
2223
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "name", 4)) {
2224
0
            min_arg_count = 0;
2225
0
            max_arg_count = 1;
2226
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "true", 4)) {
2227
0
            min_arg_count = 0;
2228
0
            max_arg_count = 0;
2229
0
        }
2230
0
        break;
2231
0
    case 5:
2232
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "count", 5)) {
2233
0
            min_arg_count = 1;
2234
0
            max_arg_count = 1;
2235
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "false", 5)) {
2236
0
            min_arg_count = 0;
2237
0
            max_arg_count = 0;
2238
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "floor", 5)) {
2239
0
            min_arg_count = 1;
2240
0
            max_arg_count = 1;
2241
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "round", 5)) {
2242
0
            min_arg_count = 1;
2243
0
            max_arg_count = 1;
2244
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "deref", 5)) {
2245
0
            min_arg_count = 1;
2246
0
            max_arg_count = 1;
2247
0
        }
2248
0
        break;
2249
0
    case 6:
2250
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "concat", 6)) {
2251
0
            min_arg_count = 2;
2252
0
            max_arg_count = UINT32_MAX;
2253
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "number", 6)) {
2254
0
            min_arg_count = 0;
2255
0
            max_arg_count = 1;
2256
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "string", 6)) {
2257
0
            min_arg_count = 0;
2258
0
            max_arg_count = 1;
2259
0
        }
2260
0
        break;
2261
0
    case 7:
2262
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "boolean", 7)) {
2263
0
            min_arg_count = 1;
2264
0
            max_arg_count = 1;
2265
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "ceiling", 7)) {
2266
0
            min_arg_count = 1;
2267
0
            max_arg_count = 1;
2268
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "current", 7)) {
2269
0
            min_arg_count = 0;
2270
0
            max_arg_count = 0;
2271
0
        }
2272
0
        break;
2273
0
    case 8:
2274
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "contains", 8)) {
2275
0
            min_arg_count = 2;
2276
0
            max_arg_count = 2;
2277
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "position", 8)) {
2278
0
            min_arg_count = 0;
2279
0
            max_arg_count = 0;
2280
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "re-match", 8)) {
2281
0
            min_arg_count = 2;
2282
0
            max_arg_count = 2;
2283
0
        }
2284
0
        break;
2285
0
    case 9:
2286
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "substring", 9)) {
2287
0
            min_arg_count = 2;
2288
0
            max_arg_count = 3;
2289
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "translate", 9)) {
2290
0
            min_arg_count = 3;
2291
0
            max_arg_count = 3;
2292
0
        }
2293
0
        break;
2294
0
    case 10:
2295
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "local-name", 10)) {
2296
0
            min_arg_count = 0;
2297
0
            max_arg_count = 1;
2298
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "enum-value", 10)) {
2299
0
            min_arg_count = 1;
2300
0
            max_arg_count = 1;
2301
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "bit-is-set", 10)) {
2302
0
            min_arg_count = 2;
2303
0
            max_arg_count = 2;
2304
0
        }
2305
0
        break;
2306
0
    case 11:
2307
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "starts-with", 11)) {
2308
0
            min_arg_count = 2;
2309
0
            max_arg_count = 2;
2310
0
        }
2311
0
        break;
2312
0
    case 12:
2313
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "derived-from", 12)) {
2314
0
            min_arg_count = 2;
2315
0
            max_arg_count = 2;
2316
0
        }
2317
0
        break;
2318
0
    case 13:
2319
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "namespace-uri", 13)) {
2320
0
            min_arg_count = 0;
2321
0
            max_arg_count = 1;
2322
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "string-length", 13)) {
2323
0
            min_arg_count = 0;
2324
0
            max_arg_count = 1;
2325
0
        }
2326
0
        break;
2327
0
    case 15:
2328
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "normalize-space", 15)) {
2329
0
            min_arg_count = 0;
2330
0
            max_arg_count = 1;
2331
0
        } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "substring-after", 15)) {
2332
0
            min_arg_count = 2;
2333
0
            max_arg_count = 2;
2334
0
        }
2335
0
        break;
2336
0
    case 16:
2337
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "substring-before", 16)) {
2338
0
            min_arg_count = 2;
2339
0
            max_arg_count = 2;
2340
0
        }
2341
0
        break;
2342
0
    case 20:
2343
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "derived-from-or-self", 20)) {
2344
0
            min_arg_count = 2;
2345
0
            max_arg_count = 2;
2346
0
        }
2347
0
        break;
2348
0
    }
2349
0
    if (min_arg_count == -1) {
2350
0
        LOGVAL(ctx, NULL, LY_VCODE_XP_INFUNC, (int)exp->tok_len[*tok_idx], &exp->expr[exp->tok_pos[*tok_idx]]);
2351
0
        return LY_EINVAL;
2352
0
    }
2353
0
    ++(*tok_idx);
2354
2355
    /* '(' */
2356
0
    rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_PAR1);
2357
0
    LY_CHECK_RET(rc);
2358
0
    ++(*tok_idx);
2359
2360
    /* ( Expr ( ',' Expr )* )? */
2361
0
    arg_count = 0;
2362
0
    rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_NONE);
2363
0
    LY_CHECK_RET(rc);
2364
0
    if (exp->tokens[*tok_idx] != LYXP_TOKEN_PAR2) {
2365
0
        ++arg_count;
2366
0
        rc = reparse_or_expr(ctx, exp, tok_idx, depth);
2367
0
        LY_CHECK_RET(rc);
2368
0
    }
2369
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_COMMA)) {
2370
0
        ++(*tok_idx);
2371
2372
0
        ++arg_count;
2373
0
        rc = reparse_or_expr(ctx, exp, tok_idx, depth);
2374
0
        LY_CHECK_RET(rc);
2375
0
    }
2376
2377
    /* ')' */
2378
0
    rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_PAR2);
2379
0
    LY_CHECK_RET(rc);
2380
0
    ++(*tok_idx);
2381
2382
0
    if ((arg_count < (uint32_t)min_arg_count) || (arg_count > max_arg_count)) {
2383
0
        LOGVAL(ctx, NULL, LY_VCODE_XP_INARGCOUNT, arg_count, (int)exp->tok_len[func_tok_idx],
2384
0
                &exp->expr[exp->tok_pos[func_tok_idx]]);
2385
0
        return LY_EVALID;
2386
0
    }
2387
2388
0
    return LY_SUCCESS;
2389
0
}
2390
2391
/**
2392
 * @brief Reparse PathExpr. Logs directly on error.
2393
 *
2394
 * [10] PathExpr ::= LocationPath | PrimaryExpr Predicate*
2395
 *                 | PrimaryExpr Predicate* '/' RelativeLocationPath
2396
 *                 | PrimaryExpr Predicate* '//' RelativeLocationPath
2397
 * [2] LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
2398
 * [8] PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall
2399
 *
2400
 * @param[in] ctx Context for logging.
2401
 * @param[in] exp Parsed XPath expression.
2402
 * @param[in] tok_idx Position in the expression @p exp.
2403
 * @param[in] depth Current number of nested expressions.
2404
 * @return LY_ERR
2405
 */
2406
static LY_ERR
2407
reparse_path_expr(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth)
2408
0
{
2409
0
    LY_ERR rc;
2410
2411
0
    if (lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_NONE)) {
2412
0
        return LY_EVALID;
2413
0
    }
2414
2415
0
    switch (exp->tokens[*tok_idx]) {
2416
0
    case LYXP_TOKEN_PAR1:
2417
        /* '(' Expr ')' Predicate* */
2418
0
        ++(*tok_idx);
2419
2420
0
        rc = reparse_or_expr(ctx, exp, tok_idx, depth);
2421
0
        LY_CHECK_RET(rc);
2422
2423
0
        rc = lyxp_check_token(ctx, exp, *tok_idx, LYXP_TOKEN_PAR2);
2424
0
        LY_CHECK_RET(rc);
2425
0
        ++(*tok_idx);
2426
0
        goto predicate;
2427
0
    case LYXP_TOKEN_DOT:
2428
0
    case LYXP_TOKEN_DDOT:
2429
0
    case LYXP_TOKEN_AXISNAME:
2430
0
    case LYXP_TOKEN_AT:
2431
0
    case LYXP_TOKEN_NAMETEST:
2432
0
    case LYXP_TOKEN_NODETYPE:
2433
        /* RelativeLocationPath */
2434
0
        rc = reparse_relative_location_path(ctx, exp, tok_idx, depth);
2435
0
        LY_CHECK_RET(rc);
2436
0
        break;
2437
0
    case LYXP_TOKEN_VARREF:
2438
        /* VariableReference */
2439
0
        ++(*tok_idx);
2440
0
        goto predicate;
2441
0
    case LYXP_TOKEN_FUNCNAME:
2442
        /* FunctionCall */
2443
0
        rc = reparse_function_call(ctx, exp, tok_idx, depth);
2444
0
        LY_CHECK_RET(rc);
2445
0
        goto predicate;
2446
0
    case LYXP_TOKEN_OPER_PATH:
2447
0
    case LYXP_TOKEN_OPER_RPATH:
2448
        /* AbsoluteLocationPath */
2449
0
        rc = reparse_absolute_location_path(ctx, exp, tok_idx, depth);
2450
0
        LY_CHECK_RET(rc);
2451
0
        break;
2452
0
    case LYXP_TOKEN_LITERAL:
2453
        /* Literal */
2454
0
        ++(*tok_idx);
2455
0
        goto predicate;
2456
0
    case LYXP_TOKEN_NUMBER:
2457
        /* Number */
2458
0
        ++(*tok_idx);
2459
0
        goto predicate;
2460
0
    default:
2461
0
        LOGVAL(ctx, NULL, LY_VCODE_XP_INTOK, lyxp_token2str(exp->tokens[*tok_idx]), &exp->expr[exp->tok_pos[*tok_idx]]);
2462
0
        return LY_EVALID;
2463
0
    }
2464
2465
0
    return LY_SUCCESS;
2466
2467
0
predicate:
2468
    /* Predicate* */
2469
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_BRACK1)) {
2470
0
        rc = reparse_predicate(ctx, exp, tok_idx, depth);
2471
0
        LY_CHECK_RET(rc);
2472
0
    }
2473
2474
    /* ('/' or '//') RelativeLocationPath */
2475
0
    if (!exp_check_token2(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_PATH, LYXP_TOKEN_OPER_RPATH)) {
2476
2477
        /* '/' or '//' */
2478
0
        ++(*tok_idx);
2479
2480
0
        rc = reparse_relative_location_path(ctx, exp, tok_idx, depth);
2481
0
        LY_CHECK_RET(rc);
2482
0
    }
2483
2484
0
    return LY_SUCCESS;
2485
0
}
2486
2487
/**
2488
 * @brief Reparse UnaryExpr. Logs directly on error.
2489
 *
2490
 * [17] UnaryExpr ::= UnionExpr | '-' UnaryExpr
2491
 * [18] UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
2492
 *
2493
 * @param[in] ctx Context for logging.
2494
 * @param[in] exp Parsed XPath expression.
2495
 * @param[in] tok_idx Position in the expression @p exp.
2496
 * @param[in] depth Current number of nested expressions.
2497
 * @return LY_ERR
2498
 */
2499
static LY_ERR
2500
reparse_unary_expr(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth)
2501
0
{
2502
0
    uint32_t prev_exp;
2503
0
    LY_ERR rc;
2504
2505
    /* ('-')* */
2506
0
    prev_exp = *tok_idx;
2507
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_MATH) &&
2508
0
            (exp->expr[exp->tok_pos[*tok_idx]] == '-')) {
2509
0
        exp_repeat_push(exp, prev_exp, LYXP_EXPR_UNARY);
2510
0
        ++(*tok_idx);
2511
0
    }
2512
2513
    /* PathExpr */
2514
0
    prev_exp = *tok_idx;
2515
0
    rc = reparse_path_expr(ctx, exp, tok_idx, depth);
2516
0
    LY_CHECK_RET(rc);
2517
2518
    /* ('|' PathExpr)* */
2519
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_UNI)) {
2520
0
        exp_repeat_push(exp, prev_exp, LYXP_EXPR_UNION);
2521
0
        ++(*tok_idx);
2522
2523
0
        rc = reparse_path_expr(ctx, exp, tok_idx, depth);
2524
0
        LY_CHECK_RET(rc);
2525
0
    }
2526
2527
0
    return LY_SUCCESS;
2528
0
}
2529
2530
/**
2531
 * @brief Reparse AdditiveExpr. Logs directly on error.
2532
 *
2533
 * [15] AdditiveExpr ::= MultiplicativeExpr
2534
 *                     | AdditiveExpr '+' MultiplicativeExpr
2535
 *                     | AdditiveExpr '-' MultiplicativeExpr
2536
 * [16] MultiplicativeExpr ::= UnaryExpr
2537
 *                     | MultiplicativeExpr '*' UnaryExpr
2538
 *                     | MultiplicativeExpr 'div' UnaryExpr
2539
 *                     | MultiplicativeExpr 'mod' UnaryExpr
2540
 *
2541
 * @param[in] ctx Context for logging.
2542
 * @param[in] exp Parsed XPath expression.
2543
 * @param[in] tok_idx Position in the expression @p exp.
2544
 * @param[in] depth Current number of nested expressions.
2545
 * @return LY_ERR
2546
 */
2547
static LY_ERR
2548
reparse_additive_expr(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth)
2549
0
{
2550
0
    uint32_t prev_add_exp, prev_mul_exp;
2551
0
    LY_ERR rc;
2552
2553
0
    prev_add_exp = *tok_idx;
2554
0
    goto reparse_multiplicative_expr;
2555
2556
    /* ('+' / '-' MultiplicativeExpr)* */
2557
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_MATH) &&
2558
0
            ((exp->expr[exp->tok_pos[*tok_idx]] == '+') || (exp->expr[exp->tok_pos[*tok_idx]] == '-'))) {
2559
0
        exp_repeat_push(exp, prev_add_exp, LYXP_EXPR_ADDITIVE);
2560
0
        ++(*tok_idx);
2561
2562
0
reparse_multiplicative_expr:
2563
        /* UnaryExpr */
2564
0
        prev_mul_exp = *tok_idx;
2565
0
        rc = reparse_unary_expr(ctx, exp, tok_idx, depth);
2566
0
        LY_CHECK_RET(rc);
2567
2568
        /* ('*' / 'div' / 'mod' UnaryExpr)* */
2569
0
        while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_MATH) &&
2570
0
                ((exp->expr[exp->tok_pos[*tok_idx]] == '*') || (exp->tok_len[*tok_idx] == 3))) {
2571
0
            exp_repeat_push(exp, prev_mul_exp, LYXP_EXPR_MULTIPLICATIVE);
2572
0
            ++(*tok_idx);
2573
2574
0
            rc = reparse_unary_expr(ctx, exp, tok_idx, depth);
2575
0
            LY_CHECK_RET(rc);
2576
0
        }
2577
0
    }
2578
2579
0
    return LY_SUCCESS;
2580
0
}
2581
2582
/**
2583
 * @brief Reparse EqualityExpr. Logs directly on error.
2584
 *
2585
 * [13] EqualityExpr ::= RelationalExpr | EqualityExpr '=' RelationalExpr
2586
 *                     | EqualityExpr '!=' RelationalExpr
2587
 * [14] RelationalExpr ::= AdditiveExpr
2588
 *                       | RelationalExpr '<' AdditiveExpr
2589
 *                       | RelationalExpr '>' AdditiveExpr
2590
 *                       | RelationalExpr '<=' AdditiveExpr
2591
 *                       | RelationalExpr '>=' AdditiveExpr
2592
 *
2593
 * @param[in] ctx Context for logging.
2594
 * @param[in] exp Parsed XPath expression.
2595
 * @param[in] tok_idx Position in the expression @p exp.
2596
 * @param[in] depth Current number of nested expressions.
2597
 * @return LY_ERR
2598
 */
2599
static LY_ERR
2600
reparse_equality_expr(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth)
2601
0
{
2602
0
    uint32_t prev_eq_exp, prev_rel_exp;
2603
0
    LY_ERR rc;
2604
2605
0
    prev_eq_exp = *tok_idx;
2606
0
    goto reparse_additive_expr;
2607
2608
    /* ('=' / '!=' RelationalExpr)* */
2609
0
    while (!exp_check_token2(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_EQUAL, LYXP_TOKEN_OPER_NEQUAL)) {
2610
0
        exp_repeat_push(exp, prev_eq_exp, LYXP_EXPR_EQUALITY);
2611
0
        ++(*tok_idx);
2612
2613
0
reparse_additive_expr:
2614
        /* AdditiveExpr */
2615
0
        prev_rel_exp = *tok_idx;
2616
0
        rc = reparse_additive_expr(ctx, exp, tok_idx, depth);
2617
0
        LY_CHECK_RET(rc);
2618
2619
        /* ('<' / '>' / '<=' / '>=' AdditiveExpr)* */
2620
0
        while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_COMP)) {
2621
0
            exp_repeat_push(exp, prev_rel_exp, LYXP_EXPR_RELATIONAL);
2622
0
            ++(*tok_idx);
2623
2624
0
            rc = reparse_additive_expr(ctx, exp, tok_idx, depth);
2625
0
            LY_CHECK_RET(rc);
2626
0
        }
2627
0
    }
2628
2629
0
    return LY_SUCCESS;
2630
0
}
2631
2632
/**
2633
 * @brief Reparse OrExpr. Logs directly on error.
2634
 *
2635
 * [11] OrExpr ::= AndExpr | OrExpr 'or' AndExpr
2636
 * [12] AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
2637
 *
2638
 * @param[in] ctx Context for logging.
2639
 * @param[in] exp Parsed XPath expression.
2640
 * @param[in] tok_idx Position in the expression @p exp.
2641
 * @param[in] depth Current number of nested expressions.
2642
 * @return LY_ERR
2643
 */
2644
static LY_ERR
2645
reparse_or_expr(const struct ly_ctx *ctx, struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t depth)
2646
0
{
2647
0
    uint32_t prev_or_exp, prev_and_exp;
2648
0
    LY_ERR rc;
2649
2650
0
    ++depth;
2651
0
    LY_CHECK_ERR_RET(depth > LYXP_MAX_BLOCK_DEPTH, LOGVAL(ctx, NULL, LY_VCODE_XP_DEPTH), LY_EINVAL);
2652
2653
0
    prev_or_exp = *tok_idx;
2654
0
    goto reparse_equality_expr;
2655
2656
    /* ('or' AndExpr)* */
2657
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_LOG) && (exp->tok_len[*tok_idx] == 2)) {
2658
0
        exp_repeat_push(exp, prev_or_exp, LYXP_EXPR_OR);
2659
0
        ++(*tok_idx);
2660
2661
0
reparse_equality_expr:
2662
        /* EqualityExpr */
2663
0
        prev_and_exp = *tok_idx;
2664
0
        rc = reparse_equality_expr(ctx, exp, tok_idx, depth);
2665
0
        LY_CHECK_RET(rc);
2666
2667
        /* ('and' EqualityExpr)* */
2668
0
        while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_LOG) && (exp->tok_len[*tok_idx] == 3)) {
2669
0
            exp_repeat_push(exp, prev_and_exp, LYXP_EXPR_AND);
2670
0
            ++(*tok_idx);
2671
2672
0
            rc = reparse_equality_expr(ctx, exp, tok_idx, depth);
2673
0
            LY_CHECK_RET(rc);
2674
0
        }
2675
0
    }
2676
2677
0
    return LY_SUCCESS;
2678
0
}
2679
2680
/**
2681
 * @brief Parse NCName.
2682
 *
2683
 * @param[in] ncname Name to parse.
2684
 * @return Length of @p ncname valid bytes.
2685
 */
2686
static ssize_t
2687
parse_ncname(const char *ncname)
2688
0
{
2689
0
    uint32_t uc, size;
2690
0
    ssize_t len = 0;
2691
2692
0
    LY_CHECK_RET(ly_getutf8(&ncname, &uc, &size), 0);
2693
0
    if (!is_xmlqnamestartchar(uc) || (uc == ':')) {
2694
0
        return len;
2695
0
    }
2696
2697
0
    do {
2698
0
        len += size;
2699
0
        if (!*ncname) {
2700
0
            break;
2701
0
        }
2702
0
        LY_CHECK_RET(ly_getutf8(&ncname, &uc, &size), -len);
2703
0
    } while (is_xmlqnamechar(uc) && (uc != ':'));
2704
2705
0
    return len;
2706
0
}
2707
2708
/**
2709
 * @brief Add @p token into the expression @p exp.
2710
 *
2711
 * @param[in] ctx Context for logging.
2712
 * @param[in] exp Expression to use.
2713
 * @param[in] token Token to add.
2714
 * @param[in] tok_pos Token position in the XPath expression.
2715
 * @param[in] tok_len Token length in the XPath expression.
2716
 * @return LY_ERR
2717
 */
2718
static LY_ERR
2719
exp_add_token(const struct ly_ctx *ctx, struct lyxp_expr *exp, enum lyxp_token token, uint32_t tok_pos, uint32_t tok_len)
2720
0
{
2721
0
    uint32_t prev;
2722
2723
0
    if (exp->used == exp->size) {
2724
0
        prev = exp->size;
2725
0
        exp->size += LYXP_EXPR_SIZE_STEP;
2726
0
        if (prev > exp->size) {
2727
0
            LOGINT(ctx);
2728
0
            return LY_EINT;
2729
0
        }
2730
2731
0
        exp->tokens = ly_realloc(exp->tokens, exp->size * sizeof *exp->tokens);
2732
0
        LY_CHECK_ERR_RET(!exp->tokens, LOGMEM(ctx), LY_EMEM);
2733
0
        exp->tok_pos = ly_realloc(exp->tok_pos, exp->size * sizeof *exp->tok_pos);
2734
0
        LY_CHECK_ERR_RET(!exp->tok_pos, LOGMEM(ctx), LY_EMEM);
2735
0
        exp->tok_len = ly_realloc(exp->tok_len, exp->size * sizeof *exp->tok_len);
2736
0
        LY_CHECK_ERR_RET(!exp->tok_len, LOGMEM(ctx), LY_EMEM);
2737
0
    }
2738
2739
0
    exp->tokens[exp->used] = token;
2740
0
    exp->tok_pos[exp->used] = tok_pos;
2741
0
    exp->tok_len[exp->used] = tok_len;
2742
0
    ++exp->used;
2743
0
    return LY_SUCCESS;
2744
0
}
2745
2746
void
2747
lyxp_expr_free(struct lyxp_expr *expr)
2748
0
{
2749
0
    uint32_t i;
2750
2751
0
    if (!expr) {
2752
0
        return;
2753
0
    }
2754
2755
0
    free(expr->expr);
2756
0
    free(expr->tokens);
2757
0
    free(expr->tok_pos);
2758
0
    free(expr->tok_len);
2759
0
    if (expr->repeat) {
2760
0
        for (i = 0; i < expr->used; ++i) {
2761
0
            free(expr->repeat[i]);
2762
0
        }
2763
0
    }
2764
0
    free(expr->repeat);
2765
0
    free(expr);
2766
0
}
2767
2768
/**
2769
 * @brief Parse Axis name.
2770
 *
2771
 * @param[in] str String to parse.
2772
 * @param[in] str_len Length of @p str.
2773
 * @return LY_SUCCESS if an axis.
2774
 * @return LY_ENOT otherwise.
2775
 */
2776
static LY_ERR
2777
expr_parse_axis(const char *str, size_t str_len)
2778
0
{
2779
0
    switch (str_len) {
2780
0
    case 4:
2781
0
        if (!strncmp("self", str, str_len)) {
2782
0
            return LY_SUCCESS;
2783
0
        }
2784
0
        break;
2785
0
    case 5:
2786
0
        if (!strncmp("child", str, str_len)) {
2787
0
            return LY_SUCCESS;
2788
0
        }
2789
0
        break;
2790
0
    case 6:
2791
0
        if (!strncmp("parent", str, str_len)) {
2792
0
            return LY_SUCCESS;
2793
0
        }
2794
0
        break;
2795
0
    case 8:
2796
0
        if (!strncmp("ancestor", str, str_len)) {
2797
0
            return LY_SUCCESS;
2798
0
        }
2799
0
        break;
2800
0
    case 9:
2801
0
        if (!strncmp("attribute", str, str_len)) {
2802
0
            return LY_SUCCESS;
2803
0
        } else if (!strncmp("following", str, str_len)) {
2804
0
            return LY_SUCCESS;
2805
0
        } else if (!strncmp("namespace", str, str_len)) {
2806
0
            LOGERR(NULL, LY_EINVAL, "Axis \"namespace\" not supported.");
2807
0
            return LY_ENOT;
2808
0
        } else if (!strncmp("preceding", str, str_len)) {
2809
0
            return LY_SUCCESS;
2810
0
        }
2811
0
        break;
2812
0
    case 10:
2813
0
        if (!strncmp("descendant", str, str_len)) {
2814
0
            return LY_SUCCESS;
2815
0
        }
2816
0
        break;
2817
0
    case 16:
2818
0
        if (!strncmp("ancestor-or-self", str, str_len)) {
2819
0
            return LY_SUCCESS;
2820
0
        }
2821
0
        break;
2822
0
    case 17:
2823
0
        if (!strncmp("following-sibling", str, str_len)) {
2824
0
            return LY_SUCCESS;
2825
0
        } else if (!strncmp("preceding-sibling", str, str_len)) {
2826
0
            return LY_SUCCESS;
2827
0
        }
2828
0
        break;
2829
0
    case 18:
2830
0
        if (!strncmp("descendant-or-self", str, str_len)) {
2831
0
            return LY_SUCCESS;
2832
0
        }
2833
0
        break;
2834
0
    }
2835
2836
0
    return LY_ENOT;
2837
0
}
2838
2839
LY_ERR
2840
lyxp_expr_parse(const struct ly_ctx *ctx, const struct lyd_node *lnode, const char *expr_str, size_t expr_len,
2841
        ly_bool reparse, struct lyxp_expr **expr_p)
2842
0
{
2843
0
    LY_ERR ret = LY_SUCCESS;
2844
0
    struct lyxp_expr *expr;
2845
0
    size_t parsed = 0, tok_len;
2846
0
    enum lyxp_token tok_type;
2847
0
    ly_bool prev_func_check = 0, prev_ntype_check = 0, has_axis;
2848
0
    uint32_t tok_idx = 0;
2849
0
    ssize_t ncname_len;
2850
2851
0
    assert(expr_p);
2852
2853
0
    if (!expr_str[0]) {
2854
0
        LOGVAL(ctx, lnode, LY_VCODE_XP_EOF);
2855
0
        return LY_EVALID;
2856
0
    }
2857
2858
0
    if (!expr_len) {
2859
0
        expr_len = strlen(expr_str);
2860
0
    }
2861
0
    if (expr_len > UINT32_MAX) {
2862
0
        LOGVAL(ctx, lnode, LYVE_XPATH, "XPath expression cannot be longer than %" PRIu32 " characters.", UINT32_MAX);
2863
0
        return LY_EVALID;
2864
0
    }
2865
2866
    /* init lyxp_expr structure */
2867
0
    expr = calloc(1, sizeof *expr);
2868
0
    LY_CHECK_ERR_GOTO(!expr, LOGMEM(ctx); ret = LY_EMEM, error);
2869
0
    expr->expr = strndup(expr_str, expr_len);
2870
0
    LY_CHECK_ERR_GOTO(!expr->expr, LOGMEM(ctx); ret = LY_EMEM, error);
2871
0
    expr->used = 0;
2872
0
    expr->size = LYXP_EXPR_SIZE_START;
2873
0
    expr->tokens = malloc(expr->size * sizeof *expr->tokens);
2874
0
    LY_CHECK_ERR_GOTO(!expr->tokens, LOGMEM(ctx); ret = LY_EMEM, error);
2875
2876
0
    expr->tok_pos = malloc(expr->size * sizeof *expr->tok_pos);
2877
0
    LY_CHECK_ERR_GOTO(!expr->tok_pos, LOGMEM(ctx); ret = LY_EMEM, error);
2878
2879
0
    expr->tok_len = malloc(expr->size * sizeof *expr->tok_len);
2880
0
    LY_CHECK_ERR_GOTO(!expr->tok_len, LOGMEM(ctx); ret = LY_EMEM, error);
2881
2882
    /* make expr 0-terminated */
2883
0
    expr_str = expr->expr;
2884
2885
0
    while (is_xmlws(expr_str[parsed])) {
2886
0
        ++parsed;
2887
0
    }
2888
2889
0
    do {
2890
0
        if (expr_str[parsed] == '(') {
2891
2892
            /* '(' */
2893
0
            tok_len = 1;
2894
0
            tok_type = LYXP_TOKEN_PAR1;
2895
2896
0
            if (prev_ntype_check && expr->used && (expr->tokens[expr->used - 1] == LYXP_TOKEN_NAMETEST) &&
2897
0
                    (((expr->tok_len[expr->used - 1] == 4) &&
2898
0
                    (!strncmp(&expr_str[expr->tok_pos[expr->used - 1]], "node", 4) ||
2899
0
                    !strncmp(&expr_str[expr->tok_pos[expr->used - 1]], "text", 4))) ||
2900
0
                    ((expr->tok_len[expr->used - 1] == 7) &&
2901
0
                    !strncmp(&expr_str[expr->tok_pos[expr->used - 1]], "comment", 7)))) {
2902
                /* it is NodeType after all */
2903
0
                expr->tokens[expr->used - 1] = LYXP_TOKEN_NODETYPE;
2904
2905
0
                prev_ntype_check = 0;
2906
0
                prev_func_check = 0;
2907
0
            } else if (prev_func_check && expr->used && (expr->tokens[expr->used - 1] == LYXP_TOKEN_NAMETEST)) {
2908
                /* it is FunctionName after all */
2909
0
                expr->tokens[expr->used - 1] = LYXP_TOKEN_FUNCNAME;
2910
2911
0
                prev_ntype_check = 0;
2912
0
                prev_func_check = 0;
2913
0
            }
2914
2915
0
        } else if (expr_str[parsed] == ')') {
2916
2917
            /* ')' */
2918
0
            tok_len = 1;
2919
0
            tok_type = LYXP_TOKEN_PAR2;
2920
2921
0
        } else if (expr_str[parsed] == '[') {
2922
2923
            /* '[' */
2924
0
            tok_len = 1;
2925
0
            tok_type = LYXP_TOKEN_BRACK1;
2926
2927
0
        } else if (expr_str[parsed] == ']') {
2928
2929
            /* ']' */
2930
0
            tok_len = 1;
2931
0
            tok_type = LYXP_TOKEN_BRACK2;
2932
2933
0
        } else if (!strncmp(&expr_str[parsed], "..", 2)) {
2934
2935
            /* '..' */
2936
0
            tok_len = 2;
2937
0
            tok_type = LYXP_TOKEN_DDOT;
2938
2939
0
        } else if ((expr_str[parsed] == '.') && (!isdigit(expr_str[parsed + 1]))) {
2940
2941
            /* '.' */
2942
0
            tok_len = 1;
2943
0
            tok_type = LYXP_TOKEN_DOT;
2944
2945
0
        } else if (expr_str[parsed] == '@') {
2946
2947
            /* '@' */
2948
0
            tok_len = 1;
2949
0
            tok_type = LYXP_TOKEN_AT;
2950
2951
0
        } else if (expr_str[parsed] == ',') {
2952
2953
            /* ',' */
2954
0
            tok_len = 1;
2955
0
            tok_type = LYXP_TOKEN_COMMA;
2956
2957
0
        } else if (expr_str[parsed] == '\'') {
2958
2959
            /* Literal with ' */
2960
0
            for (tok_len = 1; (expr_str[parsed + tok_len] != '\0') && (expr_str[parsed + tok_len] != '\''); ++tok_len) {}
2961
0
            if (expr_str[parsed + tok_len] == '\0') {
2962
0
                LOGVAL(ctx, lnode, LY_VCODE_XP_EOE, expr_str[parsed], &expr_str[parsed]);
2963
0
                ret = LY_EVALID;
2964
0
                goto error;
2965
0
            }
2966
0
            ++tok_len;
2967
0
            tok_type = LYXP_TOKEN_LITERAL;
2968
2969
0
        } else if (expr_str[parsed] == '\"') {
2970
2971
            /* Literal with " */
2972
0
            for (tok_len = 1; (expr_str[parsed + tok_len] != '\0') && (expr_str[parsed + tok_len] != '\"'); ++tok_len) {}
2973
0
            if (expr_str[parsed + tok_len] == '\0') {
2974
0
                LOGVAL(ctx, lnode, LY_VCODE_XP_EOE, expr_str[parsed], &expr_str[parsed]);
2975
0
                ret = LY_EVALID;
2976
0
                goto error;
2977
0
            }
2978
0
            ++tok_len;
2979
0
            tok_type = LYXP_TOKEN_LITERAL;
2980
2981
0
        } else if ((expr_str[parsed] == '.') || (isdigit(expr_str[parsed]))) {
2982
2983
            /* Number */
2984
0
            for (tok_len = 0; isdigit(expr_str[parsed + tok_len]); ++tok_len) {}
2985
0
            if (expr_str[parsed + tok_len] == '.') {
2986
0
                ++tok_len;
2987
0
                for ( ; isdigit(expr_str[parsed + tok_len]); ++tok_len) {}
2988
0
            }
2989
0
            tok_type = LYXP_TOKEN_NUMBER;
2990
2991
0
        } else if (expr_str[parsed] == '$') {
2992
2993
            /* VariableReference */
2994
0
            parsed++;
2995
0
            ncname_len = parse_ncname(&expr_str[parsed]);
2996
0
            if (ncname_len < 1) {
2997
0
                LOGVAL(ctx, lnode, LY_VCODE_XP_INEXPR, expr_str[parsed - ncname_len],
2998
0
                        (uint32_t)(parsed - ncname_len + 1), expr_str);
2999
0
                ret = LY_EVALID;
3000
0
                goto error;
3001
0
            }
3002
0
            tok_len = ncname_len;
3003
0
            if (expr_str[parsed + tok_len] == ':') {
3004
0
                LOGVAL(ctx, lnode, LYVE_XPATH, "Variable with prefix is not supported.");
3005
0
                ret = LY_EVALID;
3006
0
                goto error;
3007
0
            }
3008
0
            tok_type = LYXP_TOKEN_VARREF;
3009
3010
0
        } else if (expr_str[parsed] == '/') {
3011
3012
            /* Operator '/', '//' */
3013
0
            if (!strncmp(&expr_str[parsed], "//", 2)) {
3014
0
                tok_len = 2;
3015
0
                tok_type = LYXP_TOKEN_OPER_RPATH;
3016
0
            } else {
3017
0
                tok_len = 1;
3018
0
                tok_type = LYXP_TOKEN_OPER_PATH;
3019
0
            }
3020
3021
0
        } else if (!strncmp(&expr_str[parsed], "!=", 2)) {
3022
3023
            /* Operator '!=' */
3024
0
            tok_len = 2;
3025
0
            tok_type = LYXP_TOKEN_OPER_NEQUAL;
3026
3027
0
        } else if (!strncmp(&expr_str[parsed], "<=", 2) || !strncmp(&expr_str[parsed], ">=", 2)) {
3028
3029
            /* Operator '<=', '>=' */
3030
0
            tok_len = 2;
3031
0
            tok_type = LYXP_TOKEN_OPER_COMP;
3032
3033
0
        } else if (expr_str[parsed] == '|') {
3034
3035
            /* Operator '|' */
3036
0
            tok_len = 1;
3037
0
            tok_type = LYXP_TOKEN_OPER_UNI;
3038
3039
0
        } else if ((expr_str[parsed] == '+') || (expr_str[parsed] == '-')) {
3040
3041
            /* Operator '+', '-' */
3042
0
            tok_len = 1;
3043
0
            tok_type = LYXP_TOKEN_OPER_MATH;
3044
3045
0
        } else if (expr_str[parsed] == '=') {
3046
3047
            /* Operator '=' */
3048
0
            tok_len = 1;
3049
0
            tok_type = LYXP_TOKEN_OPER_EQUAL;
3050
3051
0
        } else if ((expr_str[parsed] == '<') || (expr_str[parsed] == '>')) {
3052
3053
            /* Operator '<', '>' */
3054
0
            tok_len = 1;
3055
0
            tok_type = LYXP_TOKEN_OPER_COMP;
3056
3057
0
        } else if (expr->used && (expr->tokens[expr->used - 1] != LYXP_TOKEN_AT) &&
3058
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_PAR1) &&
3059
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_BRACK1) &&
3060
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_COMMA) &&
3061
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_OPER_LOG) &&
3062
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_OPER_EQUAL) &&
3063
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_OPER_NEQUAL) &&
3064
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_OPER_COMP) &&
3065
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_OPER_MATH) &&
3066
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_OPER_UNI) &&
3067
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_OPER_PATH) &&
3068
0
                (expr->tokens[expr->used - 1] != LYXP_TOKEN_OPER_RPATH)) {
3069
3070
            /* Operator '*', 'or', 'and', 'mod', or 'div' */
3071
0
            if (expr_str[parsed] == '*') {
3072
0
                tok_len = 1;
3073
0
                tok_type = LYXP_TOKEN_OPER_MATH;
3074
3075
0
            } else if (!strncmp(&expr_str[parsed], "or", 2)) {
3076
0
                tok_len = 2;
3077
0
                tok_type = LYXP_TOKEN_OPER_LOG;
3078
3079
0
            } else if (!strncmp(&expr_str[parsed], "and", 3)) {
3080
0
                tok_len = 3;
3081
0
                tok_type = LYXP_TOKEN_OPER_LOG;
3082
3083
0
            } else if (!strncmp(&expr_str[parsed], "mod", 3) || !strncmp(&expr_str[parsed], "div", 3)) {
3084
0
                tok_len = 3;
3085
0
                tok_type = LYXP_TOKEN_OPER_MATH;
3086
3087
0
            } else if (prev_ntype_check || prev_func_check) {
3088
0
                LOGVAL(ctx, lnode, LYVE_XPATH,
3089
0
                        "Invalid character 0x%x ('%c'), perhaps \"%.*s\" is supposed to be a function call.",
3090
0
                        expr_str[parsed], expr_str[parsed], (int)expr->tok_len[expr->used - 1],
3091
0
                        &expr->expr[expr->tok_pos[expr->used - 1]]);
3092
0
                ret = LY_EVALID;
3093
0
                goto error;
3094
0
            } else {
3095
0
                LOGVAL(ctx, lnode, LY_VCODE_XP_INEXPR, expr_str[parsed], (uint32_t)(parsed + 1), expr_str);
3096
0
                ret = LY_EVALID;
3097
0
                goto error;
3098
0
            }
3099
0
        } else {
3100
3101
            /* (AxisName '::')? ((NCName ':')? '*' | QName) or NodeType/FunctionName */
3102
0
            if (expr_str[parsed] == '*') {
3103
0
                ncname_len = 1;
3104
0
            } else {
3105
0
                ncname_len = parse_ncname(&expr_str[parsed]);
3106
0
                if (ncname_len < 1) {
3107
0
                    LOGVAL(ctx, lnode, LY_VCODE_XP_INEXPR, expr_str[parsed - ncname_len],
3108
0
                            (uint32_t)(parsed - ncname_len + 1), expr_str);
3109
0
                    ret = LY_EVALID;
3110
0
                    goto error;
3111
0
                }
3112
0
            }
3113
0
            tok_len = ncname_len;
3114
3115
0
            has_axis = 0;
3116
0
            if (!strncmp(&expr_str[parsed + tok_len], "::", 2)) {
3117
                /* axis */
3118
0
                if (expr_parse_axis(&expr_str[parsed], ncname_len)) {
3119
0
                    LOGVAL(ctx, lnode, LY_VCODE_XP_INEXPR, expr_str[parsed], (uint32_t)(parsed + 1), expr_str);
3120
0
                    ret = LY_EVALID;
3121
0
                    goto error;
3122
0
                }
3123
0
                tok_type = LYXP_TOKEN_AXISNAME;
3124
3125
0
                LY_CHECK_GOTO(ret = exp_add_token(ctx, expr, tok_type, parsed, tok_len), error);
3126
0
                parsed += tok_len;
3127
3128
                /* '::' */
3129
0
                tok_len = 2;
3130
0
                tok_type = LYXP_TOKEN_DCOLON;
3131
3132
0
                LY_CHECK_GOTO(ret = exp_add_token(ctx, expr, tok_type, parsed, tok_len), error);
3133
0
                parsed += tok_len;
3134
3135
0
                if (expr_str[parsed] == '*') {
3136
0
                    ncname_len = 1;
3137
0
                } else {
3138
0
                    ncname_len = parse_ncname(&expr_str[parsed]);
3139
0
                    if (ncname_len < 1) {
3140
0
                        LOGVAL(ctx, lnode, LY_VCODE_XP_INEXPR, expr_str[parsed - ncname_len],
3141
0
                                (uint32_t)(parsed - ncname_len + 1), expr_str);
3142
0
                        ret = LY_EVALID;
3143
0
                        goto error;
3144
0
                    }
3145
0
                }
3146
0
                tok_len = ncname_len;
3147
3148
0
                has_axis = 1;
3149
0
            }
3150
3151
0
            if (expr_str[parsed + tok_len] == ':') {
3152
0
                ++tok_len;
3153
0
                if (expr_str[parsed + tok_len] == '*') {
3154
0
                    ++tok_len;
3155
0
                } else {
3156
0
                    ncname_len = parse_ncname(&expr_str[parsed + tok_len]);
3157
0
                    if (ncname_len < 1) {
3158
0
                        LOGVAL(ctx, lnode, LY_VCODE_XP_INEXPR, expr_str[parsed - ncname_len],
3159
0
                                (uint32_t)(parsed - ncname_len + 1), expr_str);
3160
0
                        ret = LY_EVALID;
3161
0
                        goto error;
3162
0
                    }
3163
0
                    tok_len += ncname_len;
3164
0
                }
3165
                /* remove old flags to prevent ambiguities */
3166
0
                prev_ntype_check = 0;
3167
0
                prev_func_check = 0;
3168
0
                tok_type = LYXP_TOKEN_NAMETEST;
3169
0
            } else {
3170
                /* if not '*', there is no prefix so it can still be NodeType/FunctionName, we can't finally decide now */
3171
0
                prev_ntype_check = (expr_str[parsed] == '*') ? 0 : 1;
3172
0
                prev_func_check = (prev_ntype_check && !has_axis) ? 1 : 0;
3173
0
                tok_type = LYXP_TOKEN_NAMETEST;
3174
0
            }
3175
0
        }
3176
3177
        /* store the token, move on to the next one */
3178
0
        LY_CHECK_GOTO(ret = exp_add_token(ctx, expr, tok_type, parsed, tok_len), error);
3179
0
        parsed += tok_len;
3180
0
        while (is_xmlws(expr_str[parsed])) {
3181
0
            ++parsed;
3182
0
        }
3183
3184
0
    } while (expr_str[parsed]);
3185
3186
0
    if (reparse) {
3187
        /* prealloc repeat */
3188
0
        expr->repeat = calloc(expr->size, sizeof *expr->repeat);
3189
0
        LY_CHECK_ERR_GOTO(!expr->repeat, LOGMEM(ctx); ret = LY_EMEM, error);
3190
3191
        /* fill repeat */
3192
0
        LY_CHECK_ERR_GOTO(reparse_or_expr(ctx, expr, &tok_idx, 0), ret = LY_EVALID, error);
3193
0
        if (expr->used > tok_idx) {
3194
0
            LOGVAL(ctx, lnode, LYVE_XPATH, "Unparsed characters \"%s\" left at the end of an XPath expression.",
3195
0
                    &expr->expr[expr->tok_pos[tok_idx]]);
3196
0
            ret = LY_EVALID;
3197
0
            goto error;
3198
0
        }
3199
0
    }
3200
3201
0
    print_expr_struct_debug(expr);
3202
0
    *expr_p = expr;
3203
0
    return LY_SUCCESS;
3204
3205
0
error:
3206
0
    lyxp_expr_free(expr);
3207
0
    return ret;
3208
0
}
3209
3210
LY_ERR
3211
lyxp_expr_dup(const struct ly_ctx *ctx, const struct lyxp_expr *exp, uint32_t start_idx, uint32_t end_idx,
3212
        struct lyxp_expr **dup_p)
3213
0
{
3214
0
    LY_ERR ret = LY_SUCCESS;
3215
0
    struct lyxp_expr *dup = NULL;
3216
0
    uint32_t used = 0, i, j, expr_len;
3217
0
    const char *expr_start;
3218
3219
0
    assert((!start_idx && !end_idx) || ((start_idx < exp->used) && (end_idx < exp->used) && (start_idx <= end_idx)));
3220
3221
0
    if (!exp) {
3222
0
        goto cleanup;
3223
0
    }
3224
3225
0
    if (!start_idx && !end_idx) {
3226
0
        end_idx = exp->used - 1;
3227
0
    }
3228
3229
0
    expr_start = exp->expr + exp->tok_pos[start_idx];
3230
0
    expr_len = (exp->tok_pos[end_idx] + exp->tok_len[end_idx]) - exp->tok_pos[start_idx];
3231
3232
0
    dup = calloc(1, sizeof *dup);
3233
0
    LY_CHECK_ERR_GOTO(!dup, LOGMEM(ctx); ret = LY_EMEM, cleanup);
3234
3235
0
    if (exp->used) {
3236
0
        used = (end_idx - start_idx) + 1;
3237
3238
0
        dup->tokens = malloc(used * sizeof *dup->tokens);
3239
0
        LY_CHECK_ERR_GOTO(!dup->tokens, LOGMEM(ctx); ret = LY_EMEM, cleanup);
3240
0
        memcpy(dup->tokens, exp->tokens + start_idx, used * sizeof *dup->tokens);
3241
3242
0
        dup->tok_pos = malloc(used * sizeof *dup->tok_pos);
3243
0
        LY_CHECK_ERR_GOTO(!dup->tok_pos, LOGMEM(ctx); ret = LY_EMEM, cleanup);
3244
0
        memcpy(dup->tok_pos, exp->tok_pos + start_idx, used * sizeof *dup->tok_pos);
3245
3246
        /* fix the indices in the expression */
3247
0
        for (i = 0; i < used; ++i) {
3248
0
            dup->tok_pos[i] -= expr_start - exp->expr;
3249
0
        }
3250
3251
0
        dup->tok_len = malloc(used * sizeof *dup->tok_len);
3252
0
        LY_CHECK_ERR_GOTO(!dup->tok_len, LOGMEM(ctx); ret = LY_EMEM, cleanup);
3253
0
        memcpy(dup->tok_len, exp->tok_len + start_idx, used * sizeof *dup->tok_len);
3254
3255
0
        if (exp->repeat) {
3256
0
            dup->repeat = malloc(used * sizeof *dup->repeat);
3257
0
            LY_CHECK_ERR_GOTO(!dup->repeat, LOGMEM(ctx); ret = LY_EMEM, cleanup);
3258
0
            for (i = start_idx; i <= end_idx; ++i) {
3259
0
                if (!exp->repeat[i]) {
3260
0
                    dup->repeat[i - start_idx] = NULL;
3261
0
                } else {
3262
0
                    for (j = 0; exp->repeat[i][j]; ++j) {}
3263
                    /* the ending 0 as well */
3264
0
                    ++j;
3265
3266
0
                    dup->repeat[i - start_idx] = malloc(j * sizeof **dup->repeat);
3267
0
                    LY_CHECK_ERR_GOTO(!dup->repeat[i - start_idx], LOGMEM(ctx); ret = LY_EMEM, cleanup);
3268
0
                    memcpy(dup->repeat[i - start_idx], exp->repeat[i], j * sizeof **dup->repeat);
3269
0
                }
3270
0
            }
3271
0
        }
3272
0
    }
3273
3274
0
    dup->used = used;
3275
0
    dup->size = used;
3276
3277
    /* copy only subexpression */
3278
0
    dup->expr = strndup(expr_start, expr_len);
3279
0
    LY_CHECK_ERR_GOTO(!dup->expr, LOGMEM(ctx); ret = LY_EMEM, cleanup);
3280
3281
0
cleanup:
3282
0
    if (ret) {
3283
0
        lyxp_expr_free(dup);
3284
0
    } else {
3285
0
        *dup_p = dup;
3286
0
    }
3287
0
    return ret;
3288
0
}
3289
3290
/**
3291
 * @brief Get the last-added schema node that is currently in the context.
3292
 *
3293
 * @param[in] set Set to search in.
3294
 * @return Last-added schema context node, NULL if no node is in context.
3295
 */
3296
static struct lysc_node *
3297
warn_get_scnode_in_ctx(struct lyxp_set *set)
3298
0
{
3299
0
    uint32_t i;
3300
3301
0
    if (!set || (set->type != LYXP_SET_SCNODE_SET)) {
3302
0
        return NULL;
3303
0
    }
3304
3305
0
    i = set->used;
3306
0
    do {
3307
0
        --i;
3308
0
        if (set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_CTX) {
3309
            /* if there are more, simply return the first found (last added) */
3310
0
            return set->val.scnodes[i].scnode;
3311
0
        }
3312
0
    } while (i);
3313
3314
0
    return NULL;
3315
0
}
3316
3317
/**
3318
 * @brief Test whether a type is numeric - integer type or decimal64.
3319
 *
3320
 * @param[in] type Type to test.
3321
 * @return Boolean value whether @p type is numeric type or not.
3322
 */
3323
static ly_bool
3324
warn_is_numeric_type(struct lysc_type *type)
3325
0
{
3326
0
    struct lysc_type_union *uni;
3327
0
    ly_bool ret;
3328
0
    LY_ARRAY_COUNT_TYPE u;
3329
3330
0
    switch (type->basetype) {
3331
0
    case LY_TYPE_DEC64:
3332
0
    case LY_TYPE_INT8:
3333
0
    case LY_TYPE_UINT8:
3334
0
    case LY_TYPE_INT16:
3335
0
    case LY_TYPE_UINT16:
3336
0
    case LY_TYPE_INT32:
3337
0
    case LY_TYPE_UINT32:
3338
0
    case LY_TYPE_INT64:
3339
0
    case LY_TYPE_UINT64:
3340
0
        return 1;
3341
0
    case LY_TYPE_UNION:
3342
0
        uni = (struct lysc_type_union *)type;
3343
0
        LY_ARRAY_FOR(uni->types, u) {
3344
0
            ret = warn_is_numeric_type(uni->types[u]);
3345
0
            if (ret) {
3346
                /* found a suitable type */
3347
0
                return ret;
3348
0
            }
3349
0
        }
3350
        /* did not find any suitable type */
3351
0
        return 0;
3352
0
    case LY_TYPE_LEAFREF:
3353
0
        return warn_is_numeric_type(((struct lysc_type_leafref *)type)->realtype);
3354
0
    default:
3355
0
        return 0;
3356
0
    }
3357
0
}
3358
3359
/**
3360
 * @brief Test whether a type is string-like - no integers, decimal64 or binary.
3361
 *
3362
 * @param[in] type Type to test.
3363
 * @return Boolean value whether @p type's basetype is string type or not.
3364
 */
3365
static ly_bool
3366
warn_is_string_type(struct lysc_type *type)
3367
0
{
3368
0
    struct lysc_type_union *uni;
3369
0
    ly_bool ret;
3370
0
    LY_ARRAY_COUNT_TYPE u;
3371
3372
0
    switch (type->basetype) {
3373
0
    case LY_TYPE_BITS:
3374
0
    case LY_TYPE_ENUM:
3375
0
    case LY_TYPE_IDENT:
3376
0
    case LY_TYPE_INST:
3377
0
    case LY_TYPE_STRING:
3378
0
        return 1;
3379
0
    case LY_TYPE_UNION:
3380
0
        uni = (struct lysc_type_union *)type;
3381
0
        LY_ARRAY_FOR(uni->types, u) {
3382
0
            ret = warn_is_string_type(uni->types[u]);
3383
0
            if (ret) {
3384
                /* found a suitable type */
3385
0
                return ret;
3386
0
            }
3387
0
        }
3388
        /* did not find any suitable type */
3389
0
        return 0;
3390
0
    case LY_TYPE_LEAFREF:
3391
0
        return warn_is_string_type(((struct lysc_type_leafref *)type)->realtype);
3392
0
    default:
3393
0
        return 0;
3394
0
    }
3395
0
}
3396
3397
/**
3398
 * @brief Test whether a type is one specific type.
3399
 *
3400
 * @param[in] type Type to test.
3401
 * @param[in] base Expected type.
3402
 * @return Boolean value whether the given @p type is of the specific basetype @p base.
3403
 */
3404
static ly_bool
3405
warn_is_specific_type(struct lysc_type *type, LY_DATA_TYPE base)
3406
0
{
3407
0
    struct lysc_type_union *uni;
3408
0
    ly_bool ret;
3409
0
    LY_ARRAY_COUNT_TYPE u;
3410
3411
0
    if (type->basetype == base) {
3412
0
        return 1;
3413
0
    } else if (type->basetype == LY_TYPE_UNION) {
3414
0
        uni = (struct lysc_type_union *)type;
3415
0
        LY_ARRAY_FOR(uni->types, u) {
3416
0
            ret = warn_is_specific_type(uni->types[u], base);
3417
0
            if (ret) {
3418
                /* found a suitable type */
3419
0
                return ret;
3420
0
            }
3421
0
        }
3422
        /* did not find any suitable type */
3423
0
        return 0;
3424
0
    } else if (type->basetype == LY_TYPE_LEAFREF) {
3425
0
        return warn_is_specific_type(((struct lysc_type_leafref *)type)->realtype, base);
3426
0
    }
3427
3428
0
    return 0;
3429
0
}
3430
3431
/**
3432
 * @brief Get next type of a (union) type.
3433
 *
3434
 * @param[in] type Base type.
3435
 * @param[in] prev_type Previously returned type.
3436
 * @param[in,out] found Whether @p prev_type has already been found or not.
3437
 * @return Next type or NULL.
3438
 */
3439
static struct lysc_type *
3440
warn_is_equal_type_next_type(struct lysc_type *type, struct lysc_type *prev_type, ly_bool *found)
3441
0
{
3442
0
    struct lysc_type *next_type;
3443
0
    struct lysc_type_union *uni;
3444
0
    LY_ARRAY_COUNT_TYPE u;
3445
3446
0
    if (type->basetype == LY_TYPE_LEAFREF) {
3447
0
        type = ((struct lysc_type_leafref *)type)->realtype;
3448
0
    }
3449
3450
0
    if (type->basetype == LY_TYPE_UNION) {
3451
0
        uni = (struct lysc_type_union *)type;
3452
0
        LY_ARRAY_FOR(uni->types, u) {
3453
0
            next_type = warn_is_equal_type_next_type(uni->types[u], prev_type, found);
3454
0
            if (next_type) {
3455
0
                return next_type;
3456
0
            }
3457
0
        }
3458
0
    } else {
3459
0
        if (*found) {
3460
0
            return type;
3461
0
        } else if (prev_type == type) {
3462
0
            *found = 1;
3463
0
        }
3464
0
    }
3465
3466
0
    return NULL;
3467
0
}
3468
3469
/**
3470
 * @brief Test whether 2 types have a common type.
3471
 *
3472
 * @param[in] type1 First type.
3473
 * @param[in] type2 Second type.
3474
 * @return 1 if they do, 0 otherwise.
3475
 */
3476
static int
3477
warn_is_equal_type(struct lysc_type *type1, struct lysc_type *type2)
3478
0
{
3479
0
    struct lysc_type *t1, *t2;
3480
0
    ly_bool found1 = 1, found2 = 1;
3481
3482
0
    t1 = NULL;
3483
0
    while ((t1 = warn_is_equal_type_next_type(type1, t1, &found1))) {
3484
0
        found1 = 0;
3485
3486
0
        t2 = NULL;
3487
0
        while ((t2 = warn_is_equal_type_next_type(type2, t2, &found2))) {
3488
0
            found2 = 0;
3489
3490
0
            if (t2->basetype == t1->basetype) {
3491
                /* match found */
3492
0
                return 1;
3493
0
            }
3494
0
        }
3495
0
    }
3496
3497
0
    return 0;
3498
0
}
3499
3500
/**
3501
 * @brief Print warning with information about the XPath subexpression that caused previous warning.
3502
 *
3503
 * @param[in] ctx Context for logging.
3504
 * @param[in] tok_pos Index of the subexpression in the whole expression.
3505
 * @param[in] subexpr Subexpression start.
3506
 * @param[in] subexpr_len Length of @p subexpr to print.
3507
 * @param[in] cur_scnode Expression context node.
3508
 */
3509
static void
3510
warn_subexpr_log(const struct ly_ctx *ctx, uint32_t tok_pos, const char *subexpr, int subexpr_len,
3511
        const struct lysc_node *cur_scnode)
3512
0
{
3513
0
    char *path;
3514
3515
0
    path = lysc_path(cur_scnode, LYSC_PATH_LOG, NULL, 0);
3516
0
    LOGWRN(ctx, "Previous warning generated by XPath subexpression[%" PRIu32 "] \"%.*s\" with context node \"%s\".",
3517
0
            tok_pos, subexpr_len, subexpr, path);
3518
0
    free(path);
3519
0
}
3520
3521
/**
3522
 * @brief Check both operands of comparison operators.
3523
 *
3524
 * @param[in] ctx Context for errors.
3525
 * @param[in] set1 First operand set.
3526
 * @param[in] set2 Second operand set.
3527
 * @param[in] numbers_only Whether accept only numbers or other types are fine too (for '=' and '!=').
3528
 * @param[in] expr Start of the expression to print with the warning.
3529
 * @param[in] tok_pos Token position.
3530
 */
3531
static void
3532
warn_operands(struct ly_ctx *ctx, struct lyxp_set *set1, struct lyxp_set *set2, ly_bool numbers_only, const char *expr,
3533
        uint32_t tok_pos)
3534
0
{
3535
0
    struct lysc_node_leaf *node1, *node2;
3536
0
    ly_bool leaves = 1, warning = 0;
3537
3538
0
    node1 = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(set1);
3539
0
    node2 = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(set2);
3540
3541
0
    if (!node1 && !node2) {
3542
        /* no node-sets involved, nothing to do */
3543
0
        return;
3544
0
    }
3545
3546
0
    if (node1) {
3547
0
        if (!(node1->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3548
0
            LOGWRN(ctx, "Node type %s \"%s\" used as operand.", lys_nodetype2str(node1->nodetype), node1->name);
3549
0
            warning = 1;
3550
0
            leaves = 0;
3551
0
        } else if (numbers_only && !warn_is_numeric_type(node1->type)) {
3552
0
            LOGWRN(ctx, "Node \"%s\" is not of a numeric type, but used where it was expected.", node1->name);
3553
0
            warning = 1;
3554
0
        }
3555
0
    }
3556
3557
0
    if (node2) {
3558
0
        if (!(node2->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3559
0
            LOGWRN(ctx, "Node type %s \"%s\" used as operand.", lys_nodetype2str(node2->nodetype), node2->name);
3560
0
            warning = 1;
3561
0
            leaves = 0;
3562
0
        } else if (numbers_only && !warn_is_numeric_type(node2->type)) {
3563
0
            LOGWRN(ctx, "Node \"%s\" is not of a numeric type, but used where it was expected.", node2->name);
3564
0
            warning = 1;
3565
0
        }
3566
0
    }
3567
3568
0
    if (node1 && node2 && leaves && !numbers_only) {
3569
0
        if ((warn_is_numeric_type(node1->type) && !warn_is_numeric_type(node2->type)) ||
3570
0
                (!warn_is_numeric_type(node1->type) && warn_is_numeric_type(node2->type)) ||
3571
0
                (!warn_is_numeric_type(node1->type) && !warn_is_numeric_type(node2->type) &&
3572
0
                !warn_is_equal_type(node1->type, node2->type))) {
3573
0
            LOGWRN(ctx, "Incompatible types of operands \"%s\" and \"%s\" for comparison.", node1->name, node2->name);
3574
0
            warning = 1;
3575
0
        }
3576
0
    }
3577
3578
0
    if (warning) {
3579
0
        warn_subexpr_log(ctx, tok_pos, expr + tok_pos, 20, set1->cur_scnode);
3580
0
    }
3581
0
}
3582
3583
/**
3584
 * @brief Check that a value is valid for a leaf. If not applicable, does nothing.
3585
 *
3586
 * @param[in] exp Parsed XPath expression.
3587
 * @param[in] set Set with the leaf/leaf-list.
3588
 * @param[in] val_exp Index of the value (literal/number) in @p exp.
3589
 * @param[in] equal_exp Index of the start of the equality expression in @p exp.
3590
 * @param[in] last_equal_exp Index of the end of the equality expression in @p exp.
3591
 */
3592
static void
3593
warn_equality_value(const struct lyxp_expr *exp, struct lyxp_set *set, uint32_t val_exp, uint32_t equal_exp,
3594
        uint32_t last_equal_exp)
3595
0
{
3596
0
    struct lysc_node *scnode;
3597
0
    struct lysc_type *type;
3598
0
    char *value;
3599
0
    struct lyd_value storage;
3600
0
    LY_ERR rc;
3601
0
    struct ly_err_item *err = NULL;
3602
0
    struct lyplg_type *type_plg;
3603
3604
0
    if ((scnode = warn_get_scnode_in_ctx(set)) && (scnode->nodetype & (LYS_LEAF | LYS_LEAFLIST)) &&
3605
0
            ((exp->tokens[val_exp] == LYXP_TOKEN_LITERAL) || (exp->tokens[val_exp] == LYXP_TOKEN_NUMBER))) {
3606
        /* check that the node can have the specified value */
3607
0
        if (exp->tokens[val_exp] == LYXP_TOKEN_LITERAL) {
3608
0
            value = strndup(exp->expr + exp->tok_pos[val_exp] + 1, exp->tok_len[val_exp] - 2);
3609
0
        } else {
3610
0
            value = strndup(exp->expr + exp->tok_pos[val_exp], exp->tok_len[val_exp]);
3611
0
        }
3612
0
        if (!value) {
3613
0
            LOGMEM(set->ctx);
3614
0
            return;
3615
0
        }
3616
3617
0
        if ((((struct lysc_node_leaf *)scnode)->type->basetype == LY_TYPE_IDENT) && !strchr(value, ':')) {
3618
0
            LOGWRN(set->ctx, "Identityref \"%s\" comparison with identity \"%s\" without prefix, consider adding"
3619
0
                    " a prefix or best using \"derived-from(-or-self)()\" functions.", scnode->name, value);
3620
0
            warn_subexpr_log(set->ctx, exp->tok_pos[equal_exp], exp->expr + exp->tok_pos[equal_exp],
3621
0
                    (exp->tok_pos[last_equal_exp] - exp->tok_pos[equal_exp]) + exp->tok_len[last_equal_exp],
3622
0
                    set->cur_scnode);
3623
0
        }
3624
3625
0
        type = ((struct lysc_node_leaf *)scnode)->type;
3626
0
        if (type->basetype != LY_TYPE_IDENT) {
3627
0
            type_plg = LYSC_GET_TYPE_PLG(type->plugin_ref);
3628
0
            rc = type_plg->store(set->ctx, type, value, strlen(value) * 8, 0, set->format, set->prefix_data,
3629
0
                    LYD_HINT_DATA, scnode, &storage, NULL, &err);
3630
0
            if (rc == LY_EINCOMPLETE) {
3631
0
                rc = LY_SUCCESS;
3632
0
            }
3633
3634
0
            if (err) {
3635
0
                LOGWRN(set->ctx, "Invalid value \"%s\" which does not fit the type (%s).", value, err->msg);
3636
0
                ly_err_free(err);
3637
0
            } else if (rc != LY_SUCCESS) {
3638
0
                LOGWRN(set->ctx, "Invalid value \"%s\" which does not fit the type.", value);
3639
0
            }
3640
0
            if (rc != LY_SUCCESS) {
3641
0
                warn_subexpr_log(set->ctx, exp->tok_pos[equal_exp], exp->expr + exp->tok_pos[equal_exp],
3642
0
                        (exp->tok_pos[last_equal_exp] - exp->tok_pos[equal_exp]) + exp->tok_len[last_equal_exp],
3643
0
                        set->cur_scnode);
3644
0
            } else {
3645
0
                type_plg->free(set->ctx, &storage);
3646
0
            }
3647
0
        }
3648
0
        free(value);
3649
0
    }
3650
0
}
3651
3652
/*
3653
 * XPath functions
3654
 */
3655
3656
/**
3657
 * @brief Execute the YANG 1.1 bit-is-set(node-set, string) function. Returns LYXP_SET_BOOLEAN
3658
 *        depending on whether the first node bit value from the second argument is set.
3659
 *
3660
 * @param[in] args Array of arguments.
3661
 * @param[in] arg_count Count of elements in @p args.
3662
 * @param[in,out] set Context and result set at the same time.
3663
 * @param[in] options XPath options.
3664
 * @return LY_ERR
3665
 */
3666
static LY_ERR
3667
xpath_bit_is_set(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
3668
0
{
3669
0
    struct lyd_node_term *leaf;
3670
0
    struct lysc_node_leaf *sleaf;
3671
0
    struct lyd_value_bits *bits;
3672
0
    struct lyd_value *val;
3673
0
    LY_ERR rc = LY_SUCCESS;
3674
0
    LY_ARRAY_COUNT_TYPE u;
3675
3676
0
    if (options & LYXP_SCNODE_ALL) {
3677
0
        if (args[0]->type != LYXP_SET_SCNODE_SET) {
3678
0
            LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3679
0
        } else if ((sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
3680
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3681
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
3682
0
                        sleaf->name);
3683
0
            } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_BITS)) {
3684
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"bits\".", __func__, sleaf->name);
3685
0
            }
3686
0
        }
3687
3688
0
        if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
3689
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3690
0
                LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
3691
0
                        sleaf->name);
3692
0
            } else if (!warn_is_string_type(sleaf->type)) {
3693
0
                LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3694
0
            }
3695
0
        }
3696
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
3697
0
        return rc;
3698
0
    }
3699
3700
0
    if (args[0]->type != LYXP_SET_NODE_SET) {
3701
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "bit-is-set(node-set, string)");
3702
0
        return LY_EVALID;
3703
0
    }
3704
0
    rc = lyxp_set_cast(args[1], LYXP_SET_STRING);
3705
0
    LY_CHECK_RET(rc);
3706
3707
0
    set_fill_boolean(set, 0);
3708
0
    if (args[0]->used && (args[0]->val.nodes[0].node->schema->nodetype & LYD_NODE_TERM)) {
3709
0
        leaf = (struct lyd_node_term *)args[0]->val.nodes[0].node;
3710
0
        val = &leaf->value;
3711
0
        if (val->realtype->basetype == LY_TYPE_UNION) {
3712
0
            val = &val->subvalue->value;
3713
0
        }
3714
0
        if (val->realtype->basetype == LY_TYPE_BITS) {
3715
0
            LYD_VALUE_GET(val, bits);
3716
0
            LY_ARRAY_FOR(bits->items, u) {
3717
0
                if (!strcmp(bits->items[u]->name, args[1]->val.str)) {
3718
0
                    set_fill_boolean(set, 1);
3719
0
                    break;
3720
0
                }
3721
0
            }
3722
0
        }
3723
0
    }
3724
3725
0
    return LY_SUCCESS;
3726
0
}
3727
3728
/**
3729
 * @brief Execute the XPath boolean(object) function. Returns LYXP_SET_BOOLEAN
3730
 *        with the argument converted to boolean.
3731
 *
3732
 * @param[in] args Array of arguments.
3733
 * @param[in] arg_count Count of elements in @p args.
3734
 * @param[in,out] set Context and result set at the same time.
3735
 * @param[in] options XPath options.
3736
 * @return LY_ERR
3737
 */
3738
static LY_ERR
3739
xpath_boolean(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
3740
0
{
3741
0
    LY_ERR rc;
3742
3743
0
    if (options & LYXP_SCNODE_ALL) {
3744
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
3745
0
        return LY_SUCCESS;
3746
0
    }
3747
3748
0
    rc = lyxp_set_cast(args[0], LYXP_SET_BOOLEAN);
3749
0
    LY_CHECK_RET(rc);
3750
0
    set_fill_set(set, args[0]);
3751
3752
0
    return LY_SUCCESS;
3753
0
}
3754
3755
/**
3756
 * @brief Execute the XPath ceiling(number) function. Returns LYXP_SET_NUMBER
3757
 *        with the first argument rounded up to the nearest integer.
3758
 *
3759
 * @param[in] args Array of arguments.
3760
 * @param[in] arg_count Count of elements in @p args.
3761
 * @param[in,out] set Context and result set at the same time.
3762
 * @param[in] options XPath options.
3763
 * @return LY_ERR
3764
 */
3765
static LY_ERR
3766
xpath_ceiling(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
3767
0
{
3768
0
    struct lysc_node_leaf *sleaf;
3769
0
    LY_ERR rc = LY_SUCCESS;
3770
3771
0
    if (options & LYXP_SCNODE_ALL) {
3772
0
        if (args[0]->type != LYXP_SET_SCNODE_SET) {
3773
0
            LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3774
0
        } else if ((sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
3775
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3776
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
3777
0
                        sleaf->name);
3778
0
            } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_DEC64)) {
3779
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"decimal64\".", __func__, sleaf->name);
3780
0
            }
3781
0
        }
3782
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
3783
0
        return rc;
3784
0
    }
3785
3786
0
    rc = lyxp_set_cast(args[0], LYXP_SET_NUMBER);
3787
0
    LY_CHECK_RET(rc);
3788
0
    if ((long long)args[0]->val.num != args[0]->val.num) {
3789
0
        set_fill_number(set, ((long long)args[0]->val.num) + 1);
3790
0
    } else {
3791
0
        set_fill_number(set, args[0]->val.num);
3792
0
    }
3793
3794
0
    return LY_SUCCESS;
3795
0
}
3796
3797
/**
3798
 * @brief Execute the XPath concat(string, string, string*) function.
3799
 *        Returns LYXP_SET_STRING with the concatenation of all the arguments.
3800
 *
3801
 * @param[in] args Array of arguments.
3802
 * @param[in] arg_count Count of elements in @p args.
3803
 * @param[in,out] set Context and result set at the same time.
3804
 * @param[in] options XPath options.
3805
 * @return LY_ERR
3806
 */
3807
static LY_ERR
3808
xpath_concat(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
3809
0
{
3810
0
    uint32_t i;
3811
0
    char *str = NULL;
3812
0
    size_t used = 1;
3813
0
    LY_ERR rc = LY_SUCCESS;
3814
0
    struct lysc_node_leaf *sleaf;
3815
3816
0
    if (options & LYXP_SCNODE_ALL) {
3817
0
        for (i = 0; i < arg_count; ++i) {
3818
0
            if ((args[i]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[i]))) {
3819
0
                if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3820
0
                    LOGWRN(set->ctx, "Argument #%" PRIu32 " of %s is a %s node \"%s\".",
3821
0
                            i + 1, __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
3822
0
                } else if (!warn_is_string_type(sleaf->type)) {
3823
0
                    LOGWRN(set->ctx, "Argument #%" PRIu32 " of %s is node \"%s\", not of string-type.", i + 1, __func__,
3824
0
                            sleaf->name);
3825
0
                }
3826
0
            }
3827
0
        }
3828
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
3829
0
        return rc;
3830
0
    }
3831
3832
0
    for (i = 0; i < arg_count; ++i) {
3833
0
        rc = lyxp_set_cast(args[i], LYXP_SET_STRING);
3834
0
        if (rc != LY_SUCCESS) {
3835
0
            free(str);
3836
0
            return rc;
3837
0
        }
3838
3839
0
        str = ly_realloc(str, (used + strlen(args[i]->val.str)) * sizeof(char));
3840
0
        LY_CHECK_ERR_RET(!str, LOGMEM(set->ctx), LY_EMEM);
3841
0
        strcpy(str + used - 1, args[i]->val.str);
3842
0
        used += strlen(args[i]->val.str);
3843
0
    }
3844
3845
    /* free, kind of */
3846
0
    lyxp_set_free_content(set);
3847
0
    set->type = LYXP_SET_STRING;
3848
0
    set->val.str = str;
3849
3850
0
    return LY_SUCCESS;
3851
0
}
3852
3853
/**
3854
 * @brief Execute the XPath contains(string, string) function.
3855
 *        Returns LYXP_SET_BOOLEAN whether the second argument can
3856
 *        be found in the first or not.
3857
 *
3858
 * @param[in] args Array of arguments.
3859
 * @param[in] arg_count Count of elements in @p args.
3860
 * @param[in,out] set Context and result set at the same time.
3861
 * @param[in] options XPath options.
3862
 * @return LY_ERR
3863
 */
3864
static LY_ERR
3865
xpath_contains(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
3866
0
{
3867
0
    struct lysc_node_leaf *sleaf;
3868
0
    LY_ERR rc = LY_SUCCESS;
3869
3870
0
    if (options & LYXP_SCNODE_ALL) {
3871
0
        if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
3872
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3873
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
3874
0
                        sleaf->name);
3875
0
            } else if (!warn_is_string_type(sleaf->type)) {
3876
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3877
0
            }
3878
0
        }
3879
3880
0
        if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
3881
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3882
0
                LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
3883
0
                        sleaf->name);
3884
0
            } else if (!warn_is_string_type(sleaf->type)) {
3885
0
                LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3886
0
            }
3887
0
        }
3888
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
3889
0
        return rc;
3890
0
    }
3891
3892
0
    rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
3893
0
    LY_CHECK_RET(rc);
3894
0
    rc = lyxp_set_cast(args[1], LYXP_SET_STRING);
3895
0
    LY_CHECK_RET(rc);
3896
3897
0
    if (strstr(args[0]->val.str, args[1]->val.str)) {
3898
0
        set_fill_boolean(set, 1);
3899
0
    } else {
3900
0
        set_fill_boolean(set, 0);
3901
0
    }
3902
3903
0
    return LY_SUCCESS;
3904
0
}
3905
3906
/**
3907
 * @brief Execute the XPath count(node-set) function. Returns LYXP_SET_NUMBER
3908
 *        with the size of the node-set from the argument.
3909
 *
3910
 * @param[in] args Array of arguments.
3911
 * @param[in] arg_count Count of elements in @p args.
3912
 * @param[in,out] set Context and result set at the same time.
3913
 * @param[in] options XPath options.
3914
 * @return LY_ERR
3915
 */
3916
static LY_ERR
3917
xpath_count(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
3918
0
{
3919
0
    LY_ERR rc = LY_SUCCESS;
3920
3921
0
    if (options & LYXP_SCNODE_ALL) {
3922
0
        if (args[0]->type != LYXP_SET_SCNODE_SET) {
3923
0
            LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3924
0
        }
3925
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
3926
0
        return rc;
3927
0
    }
3928
3929
0
    if (args[0]->type != LYXP_SET_NODE_SET) {
3930
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "count(node-set)");
3931
0
        return LY_EVALID;
3932
0
    }
3933
3934
0
    set_fill_number(set, args[0]->used);
3935
0
    return LY_SUCCESS;
3936
0
}
3937
3938
/**
3939
 * @brief Execute the XPath current() function. Returns LYXP_SET_NODE_SET
3940
 *        with the context with the intial node.
3941
 *
3942
 * @param[in] args Array of arguments.
3943
 * @param[in] arg_count Count of elements in @p args.
3944
 * @param[in,out] set Context and result set at the same time.
3945
 * @param[in] options XPath options.
3946
 * @return LY_ERR
3947
 */
3948
static LY_ERR
3949
xpath_current(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
3950
0
{
3951
0
    if (arg_count || args) {
3952
0
        LOGVAL_XPATH(set, options, LY_VCODE_XP_INARGCOUNT, arg_count, LY_PRI_LENSTR("current()"));
3953
0
        return LY_EVALID;
3954
0
    }
3955
3956
0
    if (options & LYXP_SCNODE_ALL) {
3957
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
3958
3959
0
        if (set->cur_scnode) {
3960
0
            LY_CHECK_RET(lyxp_set_scnode_insert_node(set, set->cur_scnode, LYXP_NODE_ELEM, LYXP_AXIS_SELF, NULL));
3961
0
        } else {
3962
            /* root node */
3963
0
            LY_CHECK_RET(lyxp_set_scnode_insert_node(set, NULL, set->root_type, LYXP_AXIS_SELF, NULL));
3964
0
        }
3965
0
    } else {
3966
0
        lyxp_set_free_content(set);
3967
3968
0
        if (set->cur_node) {
3969
            /* position is filled later */
3970
0
            set_insert_node(set, set->cur_node, 0, LYXP_NODE_ELEM, 0);
3971
0
        } else {
3972
            /* root node */
3973
0
            set_insert_node(set, NULL, 0, set->root_type, 0);
3974
0
        }
3975
0
    }
3976
3977
0
    return LY_SUCCESS;
3978
0
}
3979
3980
/**
3981
 * @brief Executes deref function on specific type and value. It performs evaluation in recursive manner,
3982
 *        which supports usage of union types as deref targets. Returns LYXP_SET_NODE_SET with either
3983
 *        leafref or instance-identifier target node(s).
3984
 *
3985
 * @param[in] leaf The target deref data node
3986
 * @param[in] sleaf The target deref schema node
3987
 * @param[in] value The currently evaluated value of target deref node depending on current type
3988
 * @param[in] cur_type The currently evaluated type of target deref node
3989
 * @param[in] log Whether to generate log message or not
3990
 * @param[in,out] set Context and result set at the same time.
3991
 * @param[in] options XPath options.
3992
 * @return LY_ERR
3993
 */
3994
static LY_ERR
3995
xpath_deref_type(struct lyd_node_term *leaf, struct lysc_node_leaf *sleaf, struct lyd_value *value, struct lysc_type *cur_type, ly_bool log, struct lyxp_set *set)
3996
0
{
3997
0
    LY_ERR r;
3998
0
    LY_ERR ret = LY_SUCCESS;
3999
0
    char *errmsg = NULL;
4000
0
    struct lyd_node *node;
4001
0
    struct ly_set *targets = NULL;
4002
0
    uint32_t i;
4003
0
    const struct lysc_type_union *union_type;
4004
0
    LY_ARRAY_COUNT_TYPE u;
4005
4006
0
    if (sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
4007
0
        if (cur_type->basetype == LY_TYPE_LEAFREF) {
4008
            /* find leafref target */
4009
0
            r = lyplg_type_resolve_leafref((struct lysc_type_leafref *)cur_type, &leaf->node, value, set->tree,
4010
0
                    &targets, &errmsg);
4011
0
            if (r) {
4012
0
                if (log) {
4013
0
                    LOGERR(set->ctx, LY_EINVAL, "%s", errmsg);
4014
0
                }
4015
0
                free(errmsg);
4016
0
                ret = LY_EINVAL;
4017
0
                goto cleanup;
4018
0
            }
4019
4020
            /* insert nodes into set */
4021
0
            for (i = 0; i < targets->count; ++i) {
4022
0
                set_insert_node(set, targets->dnodes[i], 0, LYXP_NODE_ELEM, 0);
4023
0
            }
4024
0
        } else if (cur_type->basetype == LY_TYPE_INST) {
4025
0
            if (ly_path_eval(value->target, set->tree, NULL, &node)) {
4026
0
                if (log) {
4027
0
                    LOGERR(set->ctx, LY_EINVAL, "Invalid instance-identifier \"%s\" value - required instance not found.",
4028
0
                            lyd_get_value(&leaf->node));
4029
0
                }
4030
0
                ret = LY_EINVAL;
4031
0
                goto cleanup;
4032
0
            }
4033
4034
            /* insert it */
4035
0
            set_insert_node(set, node, 0, LYXP_NODE_ELEM, 0);
4036
0
        } else if (cur_type->basetype == LY_TYPE_UNION) {
4037
0
            union_type = (const struct lysc_type_union *)cur_type;
4038
0
            ret = LY_EINVAL;
4039
0
            LY_ARRAY_FOR(union_type->types, u) {
4040
0
                if (!xpath_deref_type(leaf, sleaf, &value->subvalue->value, union_type->types[u], 0, set)) {
4041
0
                    ret = LY_SUCCESS;
4042
0
                    goto cleanup;
4043
0
                }
4044
0
            }
4045
0
            if (log) {
4046
0
                LOGERR(set->ctx, LY_EINVAL, "Invalid leafref or instance-identifier \"%s\" value - required instance not found.",
4047
0
                        lyd_get_value(&leaf->node));
4048
0
            }
4049
0
        }
4050
0
    }
4051
4052
0
cleanup:
4053
0
    ly_set_free(targets, NULL);
4054
0
    return ret;
4055
0
}
4056
4057
/**
4058
 * @brief Execute the YANG 1.1 deref(node-set) function. Returns LYXP_SET_NODE_SET with either
4059
 *        leafref or instance-identifier target node(s).
4060
 *
4061
 * @param[in] args Array of arguments.
4062
 * @param[in] arg_count Count of elements in @p args.
4063
 * @param[in,out] set Context and result set at the same time.
4064
 * @param[in] options XPath options.
4065
 * @return LY_ERR
4066
 */
4067
static LY_ERR
4068
xpath_deref(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4069
0
{
4070
0
    struct lyd_node_term *leaf;
4071
0
    struct lysc_node_leaf *sleaf = NULL;
4072
0
    struct lysc_type_leafref *lref;
4073
0
    const struct lysc_node *target;
4074
0
    struct ly_path *p;
4075
0
    uint8_t oper;
4076
0
    LY_ERR r;
4077
0
    LY_ERR ret = LY_SUCCESS;
4078
4079
0
    if (options & LYXP_SCNODE_ALL) {
4080
0
        if (args[0]->type != LYXP_SET_SCNODE_SET) {
4081
0
            LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
4082
0
        } else if ((sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4083
0
            if (!(sleaf->nodetype & LYD_NODE_TERM)) {
4084
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
4085
0
                        sleaf->name);
4086
0
            } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_LEAFREF) &&
4087
0
                    !warn_is_specific_type(sleaf->type, LY_TYPE_INST)) {
4088
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"leafref\" nor \"instance-identifier\".",
4089
0
                        __func__, sleaf->name);
4090
0
            }
4091
0
        }
4092
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
4093
0
        if (sleaf && (sleaf->nodetype & LYD_NODE_TERM) && (sleaf->type->basetype == LY_TYPE_LEAFREF)) {
4094
0
            lref = (struct lysc_type_leafref *)sleaf->type;
4095
0
            oper = (sleaf->flags & LYS_IS_OUTPUT) ? LY_PATH_OPER_OUTPUT : LY_PATH_OPER_INPUT;
4096
4097
            /* it was already evaluated on schema, it must succeed */
4098
0
            r = ly_path_compile_leafref(set->ctx, &sleaf->node, lref->path, oper, LY_PATH_TARGET_MANY,
4099
0
                    LY_VALUE_SCHEMA_RESOLVED, lref->prefixes, &p);
4100
0
            if (!r) {
4101
                /* get the target node */
4102
0
                target = p[LY_ARRAY_COUNT(p) - 1].node;
4103
0
                ly_path_free(p);
4104
4105
0
                LY_CHECK_RET(lyxp_set_scnode_insert_node(set, target, LYXP_NODE_ELEM, LYXP_AXIS_SELF, NULL));
4106
0
            } /* else the target was found before but is disabled so it was removed */
4107
0
        }
4108
4109
0
        ret = LY_SUCCESS;
4110
0
        goto cleanup;
4111
0
    }
4112
4113
0
    if (args[0]->type != LYXP_SET_NODE_SET) {
4114
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "deref(node-set)");
4115
0
        ret = LY_EVALID;
4116
0
        goto cleanup;
4117
0
    }
4118
4119
0
    lyxp_set_free_content(set);
4120
0
    if (args[0]->used) {
4121
0
        leaf = (struct lyd_node_term *)args[0]->val.nodes[0].node;
4122
0
        sleaf = (struct lysc_node_leaf *)leaf->schema;
4123
0
        ret = xpath_deref_type(leaf, sleaf, &leaf->value, sleaf->type, 1, set);
4124
0
    }
4125
4126
0
cleanup:
4127
0
    return ret;
4128
0
}
4129
4130
/**
4131
 * @brief Get the module of an identity used in derived-from(-or-self)() functions.
4132
 *
4133
 * @param[in,out] qname Qualified node name. If includes prefix, it is skipped.
4134
 * @param[in,out] qname_len Length of @p qname, is updated accordingly.
4135
 * @param[in] set Set with general XPath context.
4136
 * @param[out] mod Module of the identity.
4137
 * @return LY_ERR
4138
 */
4139
static LY_ERR
4140
xpath_derived_ident_module(const char **qname, uint32_t *qname_len, const struct lyxp_set *set,
4141
        const struct lys_module **mod)
4142
0
{
4143
0
    LY_CHECK_RET(moveto_resolve_module(qname, qname_len, set, set->cur_node ? set->cur_node->schema : NULL, mod));
4144
0
    if (!*mod) {
4145
        /* unprefixed JSON identity */
4146
0
        assert(set->format == LY_VALUE_JSON);
4147
0
        *mod = set->cur_mod;
4148
0
    }
4149
4150
0
    return LY_SUCCESS;
4151
0
}
4152
4153
static LY_ERR
4154
xpath_derived_(struct lyxp_set **args, struct lyxp_set *set, uint32_t options, ly_bool self_match, const char *func)
4155
0
{
4156
0
    uint32_t i, id_len;
4157
0
    LY_ARRAY_COUNT_TYPE u;
4158
0
    struct lyd_node_term *leaf;
4159
0
    struct lysc_node_leaf *sleaf;
4160
0
    struct lyd_meta *meta;
4161
0
    struct lyd_value *val;
4162
0
    const struct lys_module *mod;
4163
0
    const char *id_name;
4164
0
    struct lysc_ident *id;
4165
0
    LY_ERR rc = LY_SUCCESS;
4166
0
    ly_bool found;
4167
4168
0
    if (options & LYXP_SCNODE_ALL) {
4169
0
        if (args[0]->type != LYXP_SET_SCNODE_SET) {
4170
0
            LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", func);
4171
0
        } else if ((sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4172
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4173
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", func, lys_nodetype2str(sleaf->nodetype),
4174
0
                        sleaf->name);
4175
0
            } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_IDENT)) {
4176
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"identityref\".", func, sleaf->name);
4177
0
            }
4178
0
        }
4179
4180
0
        if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
4181
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4182
0
                LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", func, lys_nodetype2str(sleaf->nodetype),
4183
0
                        sleaf->name);
4184
0
            } else if (!warn_is_string_type(sleaf->type)) {
4185
0
                LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", func, sleaf->name);
4186
0
            }
4187
0
        }
4188
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
4189
0
        return rc;
4190
0
    }
4191
4192
0
    if (args[0]->type != LYXP_SET_NODE_SET) {
4193
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "derived-from(-or-self)(node-set, string)");
4194
0
        return LY_EVALID;
4195
0
    }
4196
0
    rc = lyxp_set_cast(args[1], LYXP_SET_STRING);
4197
0
    LY_CHECK_RET(rc);
4198
4199
    /* parse the identity */
4200
0
    id_name = args[1]->val.str;
4201
0
    id_len = strlen(id_name);
4202
0
    rc = xpath_derived_ident_module(&id_name, &id_len, set, &mod);
4203
0
    LY_CHECK_RET(rc);
4204
4205
    /* find the identity */
4206
0
    found = 0;
4207
0
    LY_ARRAY_FOR(mod->identities, u) {
4208
0
        if (!ly_strncmp(mod->identities[u].name, id_name, id_len)) {
4209
            /* we have match */
4210
0
            found = 1;
4211
0
            break;
4212
0
        }
4213
0
    }
4214
0
    if (!found) {
4215
0
        LOGVAL_DXPATH(set, LYVE_XPATH, "Identity \"%.*s\" not found in module \"%s\".", (int)id_len, id_name, mod->name);
4216
0
        return LY_EVALID;
4217
0
    }
4218
0
    id = &mod->identities[u];
4219
4220
0
    set_fill_boolean(set, 0);
4221
0
    found = 0;
4222
0
    for (i = 0; i < args[0]->used; ++i) {
4223
0
        if ((args[0]->val.nodes[i].type != LYXP_NODE_ELEM) && (args[0]->val.nodes[i].type != LYXP_NODE_META)) {
4224
0
            continue;
4225
0
        }
4226
4227
0
        if (args[0]->val.nodes[i].type == LYXP_NODE_ELEM) {
4228
0
            leaf = (struct lyd_node_term *)args[0]->val.nodes[i].node;
4229
0
            sleaf = (struct lysc_node_leaf *)leaf->schema;
4230
0
            val = &leaf->value;
4231
0
            if (!sleaf || !(sleaf->nodetype & LYD_NODE_TERM)) {
4232
                /* uninteresting */
4233
0
                continue;
4234
0
            }
4235
0
        } else {
4236
0
            meta = args[0]->val.meta[i].meta;
4237
0
            val = &meta->value;
4238
0
        }
4239
4240
0
        if (val->realtype->basetype == LY_TYPE_UNION) {
4241
0
            val = &val->subvalue->value;
4242
0
        }
4243
0
        if (val->realtype->basetype != LY_TYPE_IDENT) {
4244
            /* uninteresting */
4245
0
            continue;
4246
0
        }
4247
4248
        /* check the identity itself */
4249
0
        if (self_match && (id == val->ident)) {
4250
0
            set_fill_boolean(set, 1);
4251
0
            found = 1;
4252
0
        }
4253
0
        if (!found && !lyplg_type_identity_isderived(id, val->ident)) {
4254
0
            set_fill_boolean(set, 1);
4255
0
            found = 1;
4256
0
        }
4257
4258
0
        if (found) {
4259
0
            break;
4260
0
        }
4261
0
    }
4262
4263
0
    return LY_SUCCESS;
4264
0
}
4265
4266
/**
4267
 * @brief Execute the YANG 1.1 derived-from(node-set, string) function. Returns LYXP_SET_BOOLEAN depending
4268
 *        on whether the first argument nodes contain a node of an identity derived from the second
4269
 *        argument identity.
4270
 *
4271
 * @param[in] args Array of arguments.
4272
 * @param[in] arg_count Count of elements in @p args.
4273
 * @param[in,out] set Context and result set at the same time.
4274
 * @param[in] options XPath options.
4275
 * @return LY_ERR
4276
 */
4277
static LY_ERR
4278
xpath_derived_from(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4279
0
{
4280
0
    return xpath_derived_(args, set, options, 0, __func__);
4281
0
}
4282
4283
/**
4284
 * @brief Execute the YANG 1.1 derived-from-or-self(node-set, string) function. Returns LYXP_SET_BOOLEAN depending
4285
 *        on whether the first argument nodes contain a node of an identity that either is or is derived from
4286
 *        the second argument identity.
4287
 *
4288
 * @param[in] args Array of arguments.
4289
 * @param[in] arg_count Count of elements in @p args.
4290
 * @param[in,out] set Context and result set at the same time.
4291
 * @param[in] options XPath options.
4292
 * @return LY_ERR
4293
 */
4294
static LY_ERR
4295
xpath_derived_from_or_self(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4296
0
{
4297
0
    return xpath_derived_(args, set, options, 1, __func__);
4298
0
}
4299
4300
/**
4301
 * @brief Execute the YANG 1.1 enum-value(node-set) function. Returns LYXP_SET_NUMBER
4302
 *        with the integer value of the first node's enum value, otherwise NaN.
4303
 *
4304
 * @param[in] args Array of arguments.
4305
 * @param[in] arg_count Count of elements in @p args.
4306
 * @param[in,out] set Context and result set at the same time.
4307
 * @param[in] options XPath options.
4308
 * @return LY_ERR
4309
 */
4310
static LY_ERR
4311
xpath_enum_value(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4312
0
{
4313
0
    struct lyd_node_term *leaf;
4314
0
    struct lysc_node_leaf *sleaf;
4315
0
    LY_ERR rc = LY_SUCCESS;
4316
4317
0
    if (options & LYXP_SCNODE_ALL) {
4318
0
        if (args[0]->type != LYXP_SET_SCNODE_SET) {
4319
0
            LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
4320
0
        } else if ((sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4321
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4322
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
4323
0
                        sleaf->name);
4324
0
            } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_ENUM)) {
4325
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"enumeration\".", __func__, sleaf->name);
4326
0
            }
4327
0
        }
4328
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
4329
0
        return rc;
4330
0
    }
4331
4332
0
    if (args[0]->type != LYXP_SET_NODE_SET) {
4333
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "enum-value(node-set)");
4334
0
        return LY_EVALID;
4335
0
    }
4336
4337
0
    set_fill_number(set, NAN);
4338
0
    if (args[0]->used) {
4339
0
        leaf = (struct lyd_node_term *)args[0]->val.nodes[0].node;
4340
0
        sleaf = (struct lysc_node_leaf *)leaf->schema;
4341
0
        if ((sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST)) && (sleaf->type->basetype == LY_TYPE_ENUM)) {
4342
0
            set_fill_number(set, leaf->value.enum_item->value);
4343
0
        }
4344
0
    }
4345
4346
0
    return LY_SUCCESS;
4347
0
}
4348
4349
/**
4350
 * @brief Execute the XPath false() function. Returns LYXP_SET_BOOLEAN
4351
 *        with false value.
4352
 *
4353
 * @param[in] args Array of arguments.
4354
 * @param[in] arg_count Count of elements in @p args.
4355
 * @param[in,out] set Context and result set at the same time.
4356
 * @param[in] options XPath options.
4357
 * @return LY_ERR
4358
 */
4359
static LY_ERR
4360
xpath_false(struct lyxp_set **UNUSED(args), uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4361
0
{
4362
0
    if (options & LYXP_SCNODE_ALL) {
4363
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
4364
0
        return LY_SUCCESS;
4365
0
    }
4366
4367
0
    set_fill_boolean(set, 0);
4368
0
    return LY_SUCCESS;
4369
0
}
4370
4371
/**
4372
 * @brief Execute the XPath floor(number) function. Returns LYXP_SET_NUMBER
4373
 *        with the first argument floored (truncated).
4374
 *
4375
 * @param[in] args Array of arguments.
4376
 * @param[in] arg_count Count of elements in @p args.
4377
 * @param[in,out] set Context and result set at the same time.
4378
 * @param[in] options XPath options.
4379
 * @return LY_ERR
4380
 */
4381
static LY_ERR
4382
xpath_floor(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4383
0
{
4384
0
    struct lysc_node_leaf *sleaf;
4385
0
    LY_ERR rc = LY_SUCCESS;
4386
4387
0
    if (options & LYXP_SCNODE_ALL) {
4388
0
        if (args[0]->type != LYXP_SET_SCNODE_SET) {
4389
0
            LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
4390
0
        } else if ((sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4391
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4392
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
4393
0
                        sleaf->name);
4394
0
            } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_DEC64)) {
4395
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"decimal64\".", __func__, sleaf->name);
4396
0
            }
4397
0
        }
4398
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
4399
0
        return rc;
4400
0
    }
4401
4402
0
    rc = lyxp_set_cast(args[0], LYXP_SET_NUMBER);
4403
0
    LY_CHECK_RET(rc);
4404
0
    if (isfinite(args[0]->val.num)) {
4405
0
        set_fill_number(set, (long long)args[0]->val.num);
4406
0
    }
4407
4408
0
    return LY_SUCCESS;
4409
0
}
4410
4411
/**
4412
 * @brief Execute the XPath lang(string) function. Returns LYXP_SET_BOOLEAN
4413
 *        whether the language of the text matches the one from the argument.
4414
 *
4415
 * @param[in] args Array of arguments.
4416
 * @param[in] arg_count Count of elements in @p args.
4417
 * @param[in,out] set Context and result set at the same time.
4418
 * @param[in] options XPath options.
4419
 * @return LY_ERR
4420
 */
4421
static LY_ERR
4422
xpath_lang(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4423
0
{
4424
0
    const struct lyd_node *node;
4425
0
    struct lysc_node_leaf *sleaf;
4426
0
    struct lyd_meta *meta = NULL;
4427
0
    const char *val;
4428
0
    LY_ERR rc = LY_SUCCESS;
4429
4430
0
    if (options & LYXP_SCNODE_ALL) {
4431
0
        if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4432
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4433
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
4434
0
                        sleaf->name);
4435
0
            } else if (!warn_is_string_type(sleaf->type)) {
4436
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4437
0
            }
4438
0
        }
4439
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
4440
0
        return rc;
4441
0
    }
4442
4443
0
    rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
4444
0
    LY_CHECK_RET(rc);
4445
4446
0
    if (set->type != LYXP_SET_NODE_SET) {
4447
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INCTX, print_set_type(set), "lang(string)");
4448
0
        return LY_EVALID;
4449
0
    } else if (!set->used) {
4450
0
        set_fill_boolean(set, 0);
4451
0
        return LY_SUCCESS;
4452
0
    }
4453
4454
0
    switch (set->val.nodes[0].type) {
4455
0
    case LYXP_NODE_ELEM:
4456
0
    case LYXP_NODE_TEXT:
4457
0
        node = set->val.nodes[0].node;
4458
0
        break;
4459
0
    case LYXP_NODE_META:
4460
0
        node = set->val.meta[0].meta->parent;
4461
0
        break;
4462
0
    default:
4463
        /* nothing to do with roots */
4464
0
        set_fill_boolean(set, 0);
4465
0
        return LY_SUCCESS;
4466
0
    }
4467
4468
    /* find lang metadata */
4469
0
    for ( ; node; node = node->parent) {
4470
0
        for (meta = node->meta; meta; meta = meta->next) {
4471
            /* annotations */
4472
0
            if (meta->name && !strcmp(meta->name, "lang") && !strcmp(meta->annotation->module->name, "xml")) {
4473
0
                break;
4474
0
            }
4475
0
        }
4476
4477
0
        if (meta) {
4478
0
            break;
4479
0
        }
4480
0
    }
4481
4482
    /* compare languages */
4483
0
    if (!meta) {
4484
0
        set_fill_boolean(set, 0);
4485
0
    } else {
4486
0
        uint64_t i;
4487
4488
0
        val = lyd_get_meta_value(meta);
4489
0
        for (i = 0; args[0]->val.str[i]; ++i) {
4490
0
            if (tolower(args[0]->val.str[i]) != tolower(val[i])) {
4491
0
                set_fill_boolean(set, 0);
4492
0
                break;
4493
0
            }
4494
0
        }
4495
0
        if (!args[0]->val.str[i]) {
4496
0
            if (!val[i] || (val[i] == '-')) {
4497
0
                set_fill_boolean(set, 1);
4498
0
            } else {
4499
0
                set_fill_boolean(set, 0);
4500
0
            }
4501
0
        }
4502
0
    }
4503
4504
0
    return LY_SUCCESS;
4505
0
}
4506
4507
/**
4508
 * @brief Execute the XPath last() function. Returns LYXP_SET_NUMBER
4509
 *        with the context size.
4510
 *
4511
 * @param[in] args Array of arguments.
4512
 * @param[in] arg_count Count of elements in @p args.
4513
 * @param[in,out] set Context and result set at the same time.
4514
 * @param[in] options XPath options.
4515
 * @return LY_ERR
4516
 */
4517
static LY_ERR
4518
xpath_last(struct lyxp_set **UNUSED(args), uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4519
0
{
4520
0
    if (options & LYXP_SCNODE_ALL) {
4521
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
4522
0
        return LY_SUCCESS;
4523
0
    }
4524
4525
0
    if (set->type != LYXP_SET_NODE_SET) {
4526
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INCTX, print_set_type(set), "last()");
4527
0
        return LY_EVALID;
4528
0
    } else if (!set->used) {
4529
0
        set_fill_number(set, 0);
4530
0
        return LY_SUCCESS;
4531
0
    }
4532
4533
0
    set_fill_number(set, set->ctx_size);
4534
0
    return LY_SUCCESS;
4535
0
}
4536
4537
/**
4538
 * @brief Execute the XPath local-name(node-set?) function. Returns LYXP_SET_STRING
4539
 *        with the node name without namespace from the argument or the context.
4540
 *
4541
 * @param[in] args Array of arguments.
4542
 * @param[in] arg_count Count of elements in @p args.
4543
 * @param[in,out] set Context and result set at the same time.
4544
 * @param[in] options XPath options.
4545
 * @return LY_ERR
4546
 */
4547
static LY_ERR
4548
xpath_local_name(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
4549
0
{
4550
0
    struct lyxp_set_node *item;
4551
4552
    /* suppress unused variable warning */
4553
0
    (void)options;
4554
4555
0
    if (options & LYXP_SCNODE_ALL) {
4556
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
4557
0
        return LY_SUCCESS;
4558
0
    }
4559
4560
0
    if (arg_count) {
4561
0
        if (args[0]->type != LYXP_SET_NODE_SET) {
4562
0
            LOGVAL_DXPATH(set, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "local-name(node-set?)");
4563
0
            return LY_EVALID;
4564
0
        } else if (!args[0]->used) {
4565
0
            set_fill_string(set, "", 0);
4566
0
            return LY_SUCCESS;
4567
0
        }
4568
4569
        /* we need the set sorted, it affects the result */
4570
0
        assert(!set_sort(args[0]));
4571
4572
0
        item = &args[0]->val.nodes[0];
4573
0
    } else {
4574
0
        if (set->type != LYXP_SET_NODE_SET) {
4575
0
            LOGVAL_DXPATH(set, LY_VCODE_XP_INCTX, print_set_type(set), "local-name(node-set?)");
4576
0
            return LY_EVALID;
4577
0
        } else if (!set->used) {
4578
0
            set_fill_string(set, "", 0);
4579
0
            return LY_SUCCESS;
4580
0
        }
4581
4582
        /* we need the set sorted, it affects the result */
4583
0
        assert(!set_sort(set));
4584
4585
0
        item = &set->val.nodes[0];
4586
0
    }
4587
4588
0
    switch (item->type) {
4589
0
    case LYXP_NODE_NONE:
4590
0
        LOGINT_RET(set->ctx);
4591
0
    case LYXP_NODE_ROOT:
4592
0
    case LYXP_NODE_ROOT_CONFIG:
4593
0
    case LYXP_NODE_TEXT:
4594
0
        set_fill_string(set, "", 0);
4595
0
        break;
4596
0
    case LYXP_NODE_ELEM:
4597
0
        set_fill_string(set, LYD_NAME(item->node), strlen(LYD_NAME(item->node)));
4598
0
        break;
4599
0
    case LYXP_NODE_META:
4600
0
        set_fill_string(set, ((struct lyd_meta *)item->node)->name, strlen(((struct lyd_meta *)item->node)->name));
4601
0
        break;
4602
0
    }
4603
4604
0
    return LY_SUCCESS;
4605
0
}
4606
4607
/**
4608
 * @brief Execute the XPath name(node-set?) function. Returns LYXP_SET_STRING
4609
 *        with the node name fully qualified (with namespace) from the argument or the context.
4610
 *
4611
 * @param[in] args Array of arguments.
4612
 * @param[in] arg_count Count of elements in @p args.
4613
 * @param[in,out] set Context and result set at the same time.
4614
 * @param[in] options XPath options.
4615
 * @return LY_ERR
4616
 */
4617
static LY_ERR
4618
xpath_name(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
4619
0
{
4620
0
    struct lyxp_set_node *item;
4621
0
    const struct lys_module *mod = NULL;
4622
0
    char *str;
4623
0
    const char *name = NULL;
4624
4625
0
    if (options & LYXP_SCNODE_ALL) {
4626
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
4627
0
        return LY_SUCCESS;
4628
0
    }
4629
4630
0
    if (arg_count) {
4631
0
        if (args[0]->type != LYXP_SET_NODE_SET) {
4632
0
            LOGVAL_DXPATH(set, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "name(node-set?)");
4633
0
            return LY_EVALID;
4634
0
        } else if (!args[0]->used) {
4635
0
            set_fill_string(set, "", 0);
4636
0
            return LY_SUCCESS;
4637
0
        }
4638
4639
        /* we need the set sorted, it affects the result */
4640
0
        assert(!set_sort(args[0]));
4641
4642
0
        item = &args[0]->val.nodes[0];
4643
0
    } else {
4644
0
        if (set->type != LYXP_SET_NODE_SET) {
4645
0
            LOGVAL_DXPATH(set, LY_VCODE_XP_INCTX, print_set_type(set), "name(node-set?)");
4646
0
            return LY_EVALID;
4647
0
        } else if (!set->used) {
4648
0
            set_fill_string(set, "", 0);
4649
0
            return LY_SUCCESS;
4650
0
        }
4651
4652
        /* we need the set sorted, it affects the result */
4653
0
        assert(!set_sort(set));
4654
4655
0
        item = &set->val.nodes[0];
4656
0
    }
4657
4658
0
    switch (item->type) {
4659
0
    case LYXP_NODE_NONE:
4660
0
        LOGINT_RET(set->ctx);
4661
0
    case LYXP_NODE_ROOT:
4662
0
    case LYXP_NODE_ROOT_CONFIG:
4663
0
    case LYXP_NODE_TEXT:
4664
        /* keep NULL */
4665
0
        break;
4666
0
    case LYXP_NODE_ELEM:
4667
0
        mod = lyd_node_module(item->node);
4668
0
        name = LYD_NAME(item->node);
4669
0
        break;
4670
0
    case LYXP_NODE_META:
4671
0
        mod = ((struct lyd_meta *)item->node)->annotation->module;
4672
0
        name = ((struct lyd_meta *)item->node)->name;
4673
0
        break;
4674
0
    }
4675
4676
0
    if (mod && name) {
4677
0
        int rc = asprintf(&str, "%s:%s", ly_get_prefix(mod, set->format, set->prefix_data), name);
4678
4679
0
        LY_CHECK_ERR_RET(rc == -1, LOGMEM(set->ctx), LY_EMEM);
4680
0
        set_fill_string(set, str, strlen(str));
4681
0
        free(str);
4682
0
    } else {
4683
0
        set_fill_string(set, "", 0);
4684
0
    }
4685
4686
0
    return LY_SUCCESS;
4687
0
}
4688
4689
/**
4690
 * @brief Execute the XPath namespace-uri(node-set?) function. Returns LYXP_SET_STRING
4691
 *        with the namespace of the node from the argument or the context.
4692
 *
4693
 * @param[in] args Array of arguments.
4694
 * @param[in] arg_count Count of elements in @p args.
4695
 * @param[in,out] set Context and result set at the same time.
4696
 * @param[in] options XPath options.
4697
 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4698
 */
4699
static LY_ERR
4700
xpath_namespace_uri(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
4701
0
{
4702
0
    struct lyxp_set_node *item;
4703
0
    const struct lys_module *mod;
4704
4705
    /* suppress unused variable warning */
4706
0
    (void)options;
4707
4708
0
    if (options & LYXP_SCNODE_ALL) {
4709
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
4710
0
        return LY_SUCCESS;
4711
0
    }
4712
4713
0
    if (arg_count) {
4714
0
        if (args[0]->type != LYXP_SET_NODE_SET) {
4715
0
            LOGVAL_DXPATH(set, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "namespace-uri(node-set?)");
4716
0
            return LY_EVALID;
4717
0
        } else if (!args[0]->used) {
4718
0
            set_fill_string(set, "", 0);
4719
0
            return LY_SUCCESS;
4720
0
        }
4721
4722
        /* we need the set sorted, it affects the result */
4723
0
        assert(!set_sort(args[0]));
4724
4725
0
        item = &args[0]->val.nodes[0];
4726
0
    } else {
4727
0
        if (set->type != LYXP_SET_NODE_SET) {
4728
0
            LOGVAL_DXPATH(set, LY_VCODE_XP_INCTX, print_set_type(set), "namespace-uri(node-set?)");
4729
0
            return LY_EVALID;
4730
0
        } else if (!set->used) {
4731
0
            set_fill_string(set, "", 0);
4732
0
            return LY_SUCCESS;
4733
0
        }
4734
4735
        /* we need the set sorted, it affects the result */
4736
0
        assert(!set_sort(set));
4737
4738
0
        item = &set->val.nodes[0];
4739
0
    }
4740
4741
0
    switch (item->type) {
4742
0
    case LYXP_NODE_NONE:
4743
0
        LOGINT_RET(set->ctx);
4744
0
    case LYXP_NODE_ROOT:
4745
0
    case LYXP_NODE_ROOT_CONFIG:
4746
0
    case LYXP_NODE_TEXT:
4747
0
        set_fill_string(set, "", 0);
4748
0
        break;
4749
0
    case LYXP_NODE_ELEM:
4750
0
    case LYXP_NODE_META:
4751
0
        if (item->type == LYXP_NODE_ELEM) {
4752
0
            mod = lyd_node_module(item->node);
4753
0
        } else { /* LYXP_NODE_META */
4754
            /* annotations */
4755
0
            mod = ((struct lyd_meta *)item->node)->annotation->module;
4756
0
        }
4757
4758
0
        set_fill_string(set, mod->ns, strlen(mod->ns));
4759
0
        break;
4760
0
    }
4761
4762
0
    return LY_SUCCESS;
4763
0
}
4764
4765
/**
4766
 * @brief Execute the XPath normalize-space(string?) function. Returns LYXP_SET_STRING
4767
 *        with normalized value (no leading, trailing, double white spaces) of the node
4768
 *        from the argument or the context.
4769
 *
4770
 * @param[in] args Array of arguments.
4771
 * @param[in] arg_count Count of elements in @p args.
4772
 * @param[in,out] set Context and result set at the same time.
4773
 * @param[in] options XPath options.
4774
 * @return LY_ERR
4775
 */
4776
static LY_ERR
4777
xpath_normalize_space(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
4778
0
{
4779
0
    uint32_t i, new_used;
4780
0
    char *new;
4781
0
    ly_bool have_spaces = 0, space_before = 0;
4782
0
    struct lysc_node_leaf *sleaf;
4783
0
    LY_ERR rc = LY_SUCCESS;
4784
4785
0
    if (options & LYXP_SCNODE_ALL) {
4786
0
        if (arg_count && (args[0]->type == LYXP_SET_SCNODE_SET) &&
4787
0
                (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4788
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4789
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
4790
0
                        sleaf->name);
4791
0
            } else if (!warn_is_string_type(sleaf->type)) {
4792
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4793
0
            }
4794
0
        }
4795
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
4796
0
        return rc;
4797
0
    }
4798
4799
0
    if (arg_count) {
4800
0
        set_fill_set(set, args[0]);
4801
0
    }
4802
0
    rc = lyxp_set_cast(set, LYXP_SET_STRING);
4803
0
    LY_CHECK_RET(rc);
4804
4805
    /* is there any normalization necessary? */
4806
0
    for (i = 0; set->val.str[i]; ++i) {
4807
0
        if (is_xmlws(set->val.str[i])) {
4808
0
            if ((i == 0) || space_before || (!set->val.str[i + 1])) {
4809
0
                have_spaces = 1;
4810
0
                break;
4811
0
            }
4812
0
            space_before = 1;
4813
0
        } else {
4814
0
            space_before = 0;
4815
0
        }
4816
0
    }
4817
4818
    /* yep, there is */
4819
0
    if (have_spaces) {
4820
        /* it's enough, at least one character will go, makes space for ending '\0' */
4821
0
        new = malloc(strlen(set->val.str) * sizeof(char));
4822
0
        LY_CHECK_ERR_RET(!new, LOGMEM(set->ctx), LY_EMEM);
4823
0
        new_used = 0;
4824
4825
0
        space_before = 0;
4826
0
        for (i = 0; set->val.str[i]; ++i) {
4827
0
            if (is_xmlws(set->val.str[i])) {
4828
0
                if ((i == 0) || space_before) {
4829
0
                    space_before = 1;
4830
0
                    continue;
4831
0
                } else {
4832
0
                    space_before = 1;
4833
0
                }
4834
0
            } else {
4835
0
                space_before = 0;
4836
0
            }
4837
4838
0
            new[new_used] = (space_before ? ' ' : set->val.str[i]);
4839
0
            ++new_used;
4840
0
        }
4841
4842
        /* at worst there is one trailing space now */
4843
0
        if (new_used && is_xmlws(new[new_used - 1])) {
4844
0
            --new_used;
4845
0
        }
4846
4847
0
        new = ly_realloc(new, (new_used + 1) * sizeof(char));
4848
0
        LY_CHECK_ERR_RET(!new, LOGMEM(set->ctx), LY_EMEM);
4849
0
        new[new_used] = '\0';
4850
4851
0
        free(set->val.str);
4852
0
        set->val.str = new;
4853
0
    }
4854
4855
0
    return LY_SUCCESS;
4856
0
}
4857
4858
/**
4859
 * @brief Execute the XPath not(boolean) function. Returns LYXP_SET_BOOLEAN
4860
 *        with the argument converted to boolean and logically inverted.
4861
 *
4862
 * @param[in] args Array of arguments.
4863
 * @param[in] arg_count Count of elements in @p args.
4864
 * @param[in,out] set Context and result set at the same time.
4865
 * @param[in] options XPath options.
4866
 * @return LY_ERR
4867
 */
4868
static LY_ERR
4869
xpath_not(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4870
0
{
4871
0
    if (options & LYXP_SCNODE_ALL) {
4872
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
4873
0
        return LY_SUCCESS;
4874
0
    }
4875
4876
0
    lyxp_set_cast(args[0], LYXP_SET_BOOLEAN);
4877
0
    if (args[0]->val.bln) {
4878
0
        set_fill_boolean(set, 0);
4879
0
    } else {
4880
0
        set_fill_boolean(set, 1);
4881
0
    }
4882
4883
0
    return LY_SUCCESS;
4884
0
}
4885
4886
/**
4887
 * @brief Execute the XPath number(object?) function. Returns LYXP_SET_NUMBER
4888
 *        with the number representation of either the argument or the context.
4889
 *
4890
 * @param[in] args Array of arguments.
4891
 * @param[in] arg_count Count of elements in @p args.
4892
 * @param[in,out] set Context and result set at the same time.
4893
 * @param[in] options XPath options.
4894
 * @return LY_ERR
4895
 */
4896
static LY_ERR
4897
xpath_number(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
4898
0
{
4899
0
    LY_ERR rc;
4900
4901
0
    if (options & LYXP_SCNODE_ALL) {
4902
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
4903
0
        return LY_SUCCESS;
4904
0
    }
4905
4906
0
    if (arg_count) {
4907
0
        rc = lyxp_set_cast(args[0], LYXP_SET_NUMBER);
4908
0
        LY_CHECK_RET(rc);
4909
0
        set_fill_set(set, args[0]);
4910
0
    } else {
4911
0
        rc = lyxp_set_cast(set, LYXP_SET_NUMBER);
4912
0
        LY_CHECK_RET(rc);
4913
0
    }
4914
4915
0
    return LY_SUCCESS;
4916
0
}
4917
4918
/**
4919
 * @brief Execute the XPath position() function. Returns LYXP_SET_NUMBER
4920
 *        with the context position.
4921
 *
4922
 * @param[in] args Array of arguments.
4923
 * @param[in] arg_count Count of elements in @p args.
4924
 * @param[in,out] set Context and result set at the same time.
4925
 * @param[in] options XPath options.
4926
 * @return LY_ERR
4927
 */
4928
static LY_ERR
4929
xpath_position(struct lyxp_set **UNUSED(args), uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4930
0
{
4931
0
    if (options & LYXP_SCNODE_ALL) {
4932
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
4933
0
        return LY_SUCCESS;
4934
0
    }
4935
4936
0
    if (set->type != LYXP_SET_NODE_SET) {
4937
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INCTX, print_set_type(set), "position()");
4938
0
        return LY_EVALID;
4939
0
    } else if (!set->used) {
4940
0
        set_fill_number(set, 0);
4941
0
        return LY_SUCCESS;
4942
0
    }
4943
4944
0
    set_fill_number(set, set->ctx_pos);
4945
4946
0
    return LY_SUCCESS;
4947
0
}
4948
4949
/**
4950
 * @brief Execute the YANG 1.1 re-match(string, string) function. Returns LYXP_SET_BOOLEAN
4951
 *        depending on whether the second argument regex matches the first argument string. For details refer to
4952
 *        YANG 1.1 RFC section 10.2.1.
4953
 *
4954
 * @param[in] args Array of arguments.
4955
 * @param[in] arg_count Count of elements in @p args.
4956
 * @param[in,out] set Context and result set at the same time.
4957
 * @param[in] options XPath options.
4958
 * @return LY_ERR
4959
 */
4960
static LY_ERR
4961
xpath_re_match(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
4962
0
{
4963
0
    LY_ERR rc = LY_SUCCESS;
4964
0
    struct lysc_node_leaf *sleaf;
4965
0
    struct ly_err_item *err = NULL;
4966
4967
0
    if (options & LYXP_SCNODE_ALL) {
4968
0
        if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4969
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4970
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4971
0
            } else if (!warn_is_string_type(sleaf->type)) {
4972
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4973
0
            }
4974
0
        }
4975
4976
0
        if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
4977
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4978
0
                LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4979
0
            } else if (!warn_is_string_type(sleaf->type)) {
4980
0
                LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4981
0
            }
4982
0
        }
4983
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
4984
0
        return rc;
4985
0
    }
4986
4987
0
    rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
4988
0
    LY_CHECK_RET(rc);
4989
0
    rc = lyxp_set_cast(args[1], LYXP_SET_STRING);
4990
0
    LY_CHECK_RET(rc);
4991
4992
    /* validate the pattern */
4993
0
    rc = ly_pat_match(NULL, args[1]->val.str, 0, args[0]->val.str, strlen(args[0]->val.str), &err);
4994
0
    if (rc && (rc != LY_ENOT)) {
4995
        /* error */
4996
0
        ly_err_print(set->ctx, err, set->cur_node, NULL);
4997
0
        ly_err_free(err);
4998
0
        return rc;
4999
0
    }
5000
5001
0
    if (rc == LY_ENOT) {
5002
0
        ly_err_free(err);
5003
0
        set_fill_boolean(set, 0);
5004
0
    } else {
5005
0
        set_fill_boolean(set, 1);
5006
0
    }
5007
5008
0
    return LY_SUCCESS;
5009
0
}
5010
5011
/**
5012
 * @brief Execute the XPath round(number) function. Returns LYXP_SET_NUMBER
5013
 *        with the rounded first argument. For details refer to
5014
 *        http://www.w3.org/TR/1999/REC-xpath-19991116/#function-round.
5015
 *
5016
 * @param[in] args Array of arguments.
5017
 * @param[in] arg_count Count of elements in @p args.
5018
 * @param[in,out] set Context and result set at the same time.
5019
 * @param[in] options XPath options.
5020
 * @return LY_ERR
5021
 */
5022
static LY_ERR
5023
xpath_round(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
5024
0
{
5025
0
    struct lysc_node_leaf *sleaf;
5026
0
    LY_ERR rc = LY_SUCCESS;
5027
5028
0
    if (options & LYXP_SCNODE_ALL) {
5029
0
        if (args[0]->type != LYXP_SET_SCNODE_SET) {
5030
0
            LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
5031
0
        } else if ((sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
5032
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5033
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype),
5034
0
                        sleaf->name);
5035
0
            } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_DEC64)) {
5036
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"decimal64\".", __func__, sleaf->name);
5037
0
            }
5038
0
        }
5039
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5040
0
        return rc;
5041
0
    }
5042
5043
0
    rc = lyxp_set_cast(args[0], LYXP_SET_NUMBER);
5044
0
    LY_CHECK_RET(rc);
5045
5046
    /* cover only the cases where floor can't be used */
5047
0
    if ((args[0]->val.num == -0.0f) || ((args[0]->val.num < 0) && (args[0]->val.num >= -0.5))) {
5048
0
        set_fill_number(set, -0.0f);
5049
0
    } else {
5050
0
        args[0]->val.num += 0.5;
5051
0
        rc = xpath_floor(args, 1, args[0], options);
5052
0
        LY_CHECK_RET(rc);
5053
0
        set_fill_number(set, args[0]->val.num);
5054
0
    }
5055
5056
0
    return LY_SUCCESS;
5057
0
}
5058
5059
/**
5060
 * @brief Execute the XPath starts-with(string, string) function.
5061
 *        Returns LYXP_SET_BOOLEAN whether the second argument is
5062
 *        the prefix of the first or not.
5063
 *
5064
 * @param[in] args Array of arguments.
5065
 * @param[in] arg_count Count of elements in @p args.
5066
 * @param[in,out] set Context and result set at the same time.
5067
 * @param[in] options XPath options.
5068
 * @return LY_ERR
5069
 */
5070
static LY_ERR
5071
xpath_starts_with(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
5072
0
{
5073
0
    struct lysc_node_leaf *sleaf;
5074
0
    LY_ERR rc = LY_SUCCESS;
5075
5076
0
    if (options & LYXP_SCNODE_ALL) {
5077
0
        if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
5078
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5079
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5080
0
            } else if (!warn_is_string_type(sleaf->type)) {
5081
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5082
0
            }
5083
0
        }
5084
5085
0
        if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
5086
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5087
0
                LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5088
0
            } else if (!warn_is_string_type(sleaf->type)) {
5089
0
                LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5090
0
            }
5091
0
        }
5092
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5093
0
        return rc;
5094
0
    }
5095
5096
0
    rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
5097
0
    LY_CHECK_RET(rc);
5098
0
    rc = lyxp_set_cast(args[1], LYXP_SET_STRING);
5099
0
    LY_CHECK_RET(rc);
5100
5101
0
    if (strncmp(args[0]->val.str, args[1]->val.str, strlen(args[1]->val.str))) {
5102
0
        set_fill_boolean(set, 0);
5103
0
    } else {
5104
0
        set_fill_boolean(set, 1);
5105
0
    }
5106
5107
0
    return LY_SUCCESS;
5108
0
}
5109
5110
/**
5111
 * @brief Execute the XPath string(object?) function. Returns LYXP_SET_STRING
5112
 *        with the string representation of either the argument or the context.
5113
 *
5114
 * @param[in] args Array of arguments.
5115
 * @param[in] arg_count Count of elements in @p args.
5116
 * @param[in,out] set Context and result set at the same time.
5117
 * @param[in] options XPath options.
5118
 * @return LY_ERR
5119
 */
5120
static LY_ERR
5121
xpath_string(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
5122
0
{
5123
0
    LY_ERR rc;
5124
5125
0
    if (options & LYXP_SCNODE_ALL) {
5126
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5127
0
        return LY_SUCCESS;
5128
0
    }
5129
5130
0
    if (arg_count) {
5131
0
        rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
5132
0
        LY_CHECK_RET(rc);
5133
0
        set_fill_set(set, args[0]);
5134
0
    } else {
5135
0
        rc = lyxp_set_cast(set, LYXP_SET_STRING);
5136
0
        LY_CHECK_RET(rc);
5137
0
    }
5138
5139
0
    return LY_SUCCESS;
5140
0
}
5141
5142
/**
5143
 * @brief Execute the XPath string-length(string?) function. Returns LYXP_SET_NUMBER
5144
 *        with the length of the string in either the argument or the context.
5145
 *
5146
 * @param[in] args Array of arguments.
5147
 * @param[in] arg_count Count of elements in @p args.
5148
 * @param[in,out] set Context and result set at the same time.
5149
 * @param[in] options XPath options.
5150
 * @return LY_ERR
5151
 */
5152
static LY_ERR
5153
xpath_string_length(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
5154
0
{
5155
0
    struct lysc_node_leaf *sleaf;
5156
0
    LY_ERR rc = LY_SUCCESS;
5157
5158
0
    if (options & LYXP_SCNODE_ALL) {
5159
0
        if (arg_count && (args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
5160
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5161
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5162
0
            } else if (!warn_is_string_type(sleaf->type)) {
5163
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5164
0
            }
5165
0
        }
5166
0
        if (!arg_count && (set->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(set))) {
5167
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5168
0
                LOGWRN(set->ctx, "Argument #0 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5169
0
            } else if (!warn_is_string_type(sleaf->type)) {
5170
0
                LOGWRN(set->ctx, "Argument #0 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5171
0
            }
5172
0
        }
5173
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5174
0
        return rc;
5175
0
    }
5176
5177
0
    if (arg_count) {
5178
0
        rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
5179
0
        LY_CHECK_RET(rc);
5180
0
        set_fill_number(set, strlen(args[0]->val.str));
5181
0
    } else {
5182
0
        rc = lyxp_set_cast(set, LYXP_SET_STRING);
5183
0
        LY_CHECK_RET(rc);
5184
0
        set_fill_number(set, strlen(set->val.str));
5185
0
    }
5186
5187
0
    return LY_SUCCESS;
5188
0
}
5189
5190
/**
5191
 * @brief Execute the XPath substring(string, number, number?) function.
5192
 *        Returns LYXP_SET_STRING substring of the first argument starting
5193
 *        on the second argument index ending on the third argument index,
5194
 *        indexed from 1. For exact definition refer to
5195
 *        http://www.w3.org/TR/1999/REC-xpath-19991116/#function-substring.
5196
 *
5197
 * @param[in] args Array of arguments.
5198
 * @param[in] arg_count Count of elements in @p args.
5199
 * @param[in,out] set Context and result set at the same time.
5200
 * @param[in] options XPath options.
5201
 * @return LY_ERR
5202
 */
5203
static LY_ERR
5204
xpath_substring(struct lyxp_set **args, uint32_t arg_count, struct lyxp_set *set, uint32_t options)
5205
0
{
5206
0
    int64_t start;
5207
0
    int32_t len;
5208
0
    uint32_t str_start, str_len, pos;
5209
0
    struct lysc_node_leaf *sleaf;
5210
0
    LY_ERR rc = LY_SUCCESS;
5211
5212
0
    if (options & LYXP_SCNODE_ALL) {
5213
0
        if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
5214
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5215
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5216
0
            } else if (!warn_is_string_type(sleaf->type)) {
5217
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5218
0
            }
5219
0
        }
5220
5221
0
        if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
5222
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5223
0
                LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5224
0
            } else if (!warn_is_numeric_type(sleaf->type)) {
5225
0
                LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of numeric type.", __func__, sleaf->name);
5226
0
            }
5227
0
        }
5228
5229
0
        if ((arg_count == 3) && (args[2]->type == LYXP_SET_SCNODE_SET) &&
5230
0
                (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[2]))) {
5231
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5232
0
                LOGWRN(set->ctx, "Argument #3 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5233
0
            } else if (!warn_is_numeric_type(sleaf->type)) {
5234
0
                LOGWRN(set->ctx, "Argument #3 of %s is node \"%s\", not of numeric type.", __func__, sleaf->name);
5235
0
            }
5236
0
        }
5237
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5238
0
        return rc;
5239
0
    }
5240
5241
0
    rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
5242
0
    LY_CHECK_RET(rc);
5243
5244
    /* start */
5245
0
    if (xpath_round(&args[1], 1, args[1], options)) {
5246
0
        return -1;
5247
0
    }
5248
0
    if (isfinite(args[1]->val.num)) {
5249
0
        start = args[1]->val.num - 1;
5250
0
    } else if (isinf(args[1]->val.num) && signbit(args[1]->val.num)) {
5251
0
        start = INT32_MIN;
5252
0
    } else {
5253
0
        start = INT32_MAX;
5254
0
    }
5255
5256
    /* len */
5257
0
    if (arg_count == 3) {
5258
0
        rc = xpath_round(&args[2], 1, args[2], options);
5259
0
        LY_CHECK_RET(rc);
5260
0
        if (isnan(args[2]->val.num) || signbit(args[2]->val.num)) {
5261
0
            len = 0;
5262
0
        } else if (isfinite(args[2]->val.num)) {
5263
0
            len = args[2]->val.num;
5264
0
        } else {
5265
0
            len = INT32_MAX;
5266
0
        }
5267
0
    } else {
5268
0
        len = INT32_MAX;
5269
0
    }
5270
5271
    /* find matching character positions */
5272
0
    str_start = 0;
5273
0
    str_len = 0;
5274
0
    for (pos = 0; args[0]->val.str[pos]; ++pos) {
5275
0
        if (pos < start) {
5276
0
            ++str_start;
5277
0
        } else if (pos < start + len) {
5278
0
            ++str_len;
5279
0
        } else {
5280
0
            break;
5281
0
        }
5282
0
    }
5283
5284
0
    set_fill_string(set, args[0]->val.str + str_start, str_len);
5285
0
    return LY_SUCCESS;
5286
0
}
5287
5288
/**
5289
 * @brief Execute the XPath substring-after(string, string) function.
5290
 *        Returns LYXP_SET_STRING with the string succeeding the occurance
5291
 *        of the second argument in the first or an empty string.
5292
 *
5293
 * @param[in] args Array of arguments.
5294
 * @param[in] arg_count Count of elements in @p args.
5295
 * @param[in,out] set Context and result set at the same time.
5296
 * @param[in] options XPath options.
5297
 * @return LY_ERR
5298
 */
5299
static LY_ERR
5300
xpath_substring_after(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
5301
0
{
5302
0
    char *ptr;
5303
0
    struct lysc_node_leaf *sleaf;
5304
0
    LY_ERR rc = LY_SUCCESS;
5305
5306
0
    if (options & LYXP_SCNODE_ALL) {
5307
0
        if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
5308
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5309
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5310
0
            } else if (!warn_is_string_type(sleaf->type)) {
5311
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5312
0
            }
5313
0
        }
5314
5315
0
        if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
5316
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5317
0
                LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5318
0
            } else if (!warn_is_string_type(sleaf->type)) {
5319
0
                LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5320
0
            }
5321
0
        }
5322
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5323
0
        return rc;
5324
0
    }
5325
5326
0
    rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
5327
0
    LY_CHECK_RET(rc);
5328
0
    rc = lyxp_set_cast(args[1], LYXP_SET_STRING);
5329
0
    LY_CHECK_RET(rc);
5330
5331
0
    ptr = strstr(args[0]->val.str, args[1]->val.str);
5332
0
    if (ptr) {
5333
0
        set_fill_string(set, ptr + strlen(args[1]->val.str), strlen(ptr + strlen(args[1]->val.str)));
5334
0
    } else {
5335
0
        set_fill_string(set, "", 0);
5336
0
    }
5337
5338
0
    return LY_SUCCESS;
5339
0
}
5340
5341
/**
5342
 * @brief Execute the XPath substring-before(string, string) function.
5343
 *        Returns LYXP_SET_STRING with the string preceding the occurance
5344
 *        of the second argument in the first or an empty string.
5345
 *
5346
 * @param[in] args Array of arguments.
5347
 * @param[in] arg_count Count of elements in @p args.
5348
 * @param[in,out] set Context and result set at the same time.
5349
 * @param[in] options XPath options.
5350
 * @return LY_ERR
5351
 */
5352
static LY_ERR
5353
xpath_substring_before(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
5354
0
{
5355
0
    char *ptr;
5356
0
    struct lysc_node_leaf *sleaf;
5357
0
    LY_ERR rc = LY_SUCCESS;
5358
5359
0
    if (options & LYXP_SCNODE_ALL) {
5360
0
        if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
5361
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5362
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5363
0
            } else if (!warn_is_string_type(sleaf->type)) {
5364
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5365
0
            }
5366
0
        }
5367
5368
0
        if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
5369
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5370
0
                LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5371
0
            } else if (!warn_is_string_type(sleaf->type)) {
5372
0
                LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5373
0
            }
5374
0
        }
5375
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5376
0
        return rc;
5377
0
    }
5378
5379
0
    rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
5380
0
    LY_CHECK_RET(rc);
5381
0
    rc = lyxp_set_cast(args[1], LYXP_SET_STRING);
5382
0
    LY_CHECK_RET(rc);
5383
5384
0
    ptr = strstr(args[0]->val.str, args[1]->val.str);
5385
0
    if (ptr) {
5386
0
        set_fill_string(set, args[0]->val.str, ptr - args[0]->val.str);
5387
0
    } else {
5388
0
        set_fill_string(set, "", 0);
5389
0
    }
5390
5391
0
    return LY_SUCCESS;
5392
0
}
5393
5394
/**
5395
 * @brief Execute the XPath sum(node-set) function. Returns LYXP_SET_NUMBER
5396
 *        with the sum of all the nodes in the context.
5397
 *
5398
 * @param[in] args Array of arguments.
5399
 * @param[in] arg_count Count of elements in @p args.
5400
 * @param[in,out] set Context and result set at the same time.
5401
 * @param[in] options XPath options.
5402
 * @return LY_ERR
5403
 */
5404
static LY_ERR
5405
xpath_sum(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
5406
0
{
5407
0
    long double num;
5408
0
    char *str;
5409
0
    uint32_t i;
5410
0
    struct lyxp_set set_item;
5411
0
    struct lysc_node_leaf *sleaf;
5412
0
    LY_ERR rc = LY_SUCCESS;
5413
5414
0
    if (options & LYXP_SCNODE_ALL) {
5415
0
        if (args[0]->type == LYXP_SET_SCNODE_SET) {
5416
0
            for (i = 0; i < args[0]->used; ++i) {
5417
0
                if (args[0]->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_CTX) {
5418
0
                    sleaf = (struct lysc_node_leaf *)args[0]->val.scnodes[i].scnode;
5419
0
                    if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5420
0
                        LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__,
5421
0
                                lys_nodetype2str(sleaf->nodetype), sleaf->name);
5422
0
                    } else if (!warn_is_numeric_type(sleaf->type)) {
5423
0
                        LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of numeric type.", __func__, sleaf->name);
5424
0
                    }
5425
0
                }
5426
0
            }
5427
0
        }
5428
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5429
0
        return rc;
5430
0
    }
5431
5432
0
    set_fill_number(set, 0);
5433
5434
0
    if (args[0]->type != LYXP_SET_NODE_SET) {
5435
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "sum(node-set)");
5436
0
        return LY_EVALID;
5437
0
    } else if (!args[0]->used) {
5438
0
        return LY_SUCCESS;
5439
0
    }
5440
5441
0
    set_init(&set_item, set);
5442
5443
0
    set_item.type = LYXP_SET_NODE_SET;
5444
0
    set_item.val.nodes = calloc(1, sizeof *set_item.val.nodes);
5445
0
    LY_CHECK_ERR_RET(!set_item.val.nodes, LOGMEM(set->ctx), LY_EMEM);
5446
5447
0
    set_item.used = 1;
5448
0
    set_item.size = 1;
5449
5450
0
    for (i = 0; i < args[0]->used; ++i) {
5451
0
        set_item.val.nodes[0] = args[0]->val.nodes[i];
5452
5453
0
        rc = cast_node_set_to_string(&set_item, &str);
5454
0
        LY_CHECK_RET(rc);
5455
0
        num = cast_string_to_number(str);
5456
0
        free(str);
5457
0
        set->val.num += num;
5458
0
    }
5459
5460
0
    free(set_item.val.nodes);
5461
5462
0
    return LY_SUCCESS;
5463
0
}
5464
5465
/**
5466
 * @brief Execute the XPath translate(string, string, string) function.
5467
 *        Returns LYXP_SET_STRING with the first argument with the characters
5468
 *        from the second argument replaced by those on the corresponding
5469
 *        positions in the third argument.
5470
 *
5471
 * @param[in] args Array of arguments.
5472
 * @param[in] arg_count Count of elements in @p args.
5473
 * @param[in,out] set Context and result set at the same time.
5474
 * @param[in] options XPath options.
5475
 * @return LY_ERR
5476
 */
5477
static LY_ERR
5478
xpath_translate(struct lyxp_set **args, uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
5479
0
{
5480
0
    uint32_t i, j, new_used;
5481
0
    char *new;
5482
0
    ly_bool have_removed;
5483
0
    struct lysc_node_leaf *sleaf;
5484
0
    LY_ERR rc = LY_SUCCESS;
5485
5486
0
    if (options & LYXP_SCNODE_ALL) {
5487
0
        if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
5488
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5489
0
                LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5490
0
            } else if (!warn_is_string_type(sleaf->type)) {
5491
0
                LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5492
0
            }
5493
0
        }
5494
5495
0
        if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
5496
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5497
0
                LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5498
0
            } else if (!warn_is_string_type(sleaf->type)) {
5499
0
                LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5500
0
            }
5501
0
        }
5502
5503
0
        if ((args[2]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[2]))) {
5504
0
            if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5505
0
                LOGWRN(set->ctx, "Argument #3 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5506
0
            } else if (!warn_is_string_type(sleaf->type)) {
5507
0
                LOGWRN(set->ctx, "Argument #3 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5508
0
            }
5509
0
        }
5510
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5511
0
        return rc;
5512
0
    }
5513
5514
0
    rc = lyxp_set_cast(args[0], LYXP_SET_STRING);
5515
0
    LY_CHECK_RET(rc);
5516
0
    rc = lyxp_set_cast(args[1], LYXP_SET_STRING);
5517
0
    LY_CHECK_RET(rc);
5518
0
    rc = lyxp_set_cast(args[2], LYXP_SET_STRING);
5519
0
    LY_CHECK_RET(rc);
5520
5521
0
    new = malloc((strlen(args[0]->val.str) + 1) * sizeof(char));
5522
0
    LY_CHECK_ERR_RET(!new, LOGMEM(set->ctx), LY_EMEM);
5523
0
    new_used = 0;
5524
5525
0
    have_removed = 0;
5526
0
    for (i = 0; args[0]->val.str[i]; ++i) {
5527
0
        ly_bool found = 0;
5528
5529
0
        for (j = 0; args[1]->val.str[j]; ++j) {
5530
0
            if (args[0]->val.str[i] == args[1]->val.str[j]) {
5531
                /* removing this char */
5532
0
                if (j >= strlen(args[2]->val.str)) {
5533
0
                    have_removed = 1;
5534
0
                    found = 1;
5535
0
                    break;
5536
0
                }
5537
                /* replacing this char */
5538
0
                new[new_used] = args[2]->val.str[j];
5539
0
                ++new_used;
5540
0
                found = 1;
5541
0
                break;
5542
0
            }
5543
0
        }
5544
5545
        /* copying this char */
5546
0
        if (!found) {
5547
0
            new[new_used] = args[0]->val.str[i];
5548
0
            ++new_used;
5549
0
        }
5550
0
    }
5551
5552
0
    if (have_removed) {
5553
0
        new = ly_realloc(new, (new_used + 1) * sizeof(char));
5554
0
        LY_CHECK_ERR_RET(!new, LOGMEM(set->ctx), LY_EMEM);
5555
0
    }
5556
0
    new[new_used] = '\0';
5557
5558
0
    lyxp_set_free_content(set);
5559
0
    set->type = LYXP_SET_STRING;
5560
0
    set->val.str = new;
5561
5562
0
    return LY_SUCCESS;
5563
0
}
5564
5565
/**
5566
 * @brief Execute the XPath true() function. Returns LYXP_SET_BOOLEAN
5567
 *        with true value.
5568
 *
5569
 * @param[in] args Array of arguments.
5570
 * @param[in] arg_count Count of elements in @p args.
5571
 * @param[in,out] set Context and result set at the same time.
5572
 * @param[in] options XPath options.
5573
 * @return LY_ERR
5574
 */
5575
static LY_ERR
5576
xpath_true(struct lyxp_set **UNUSED(args), uint32_t UNUSED(arg_count), struct lyxp_set *set, uint32_t options)
5577
0
{
5578
0
    if (options & LYXP_SCNODE_ALL) {
5579
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
5580
0
        return LY_SUCCESS;
5581
0
    }
5582
5583
0
    set_fill_boolean(set, 1);
5584
0
    return LY_SUCCESS;
5585
0
}
5586
5587
/**
5588
 * @brief Execute the XPath node() processing instruction (node type). Returns LYXP_SET_NODE_SET
5589
 *        with only nodes from the context.
5590
 *
5591
 * @param[in,out] set Context and result set at the same time.
5592
 * @param[in] axis Axis to search on.
5593
 * @param[in] options XPath options.
5594
 * @return LY_ERR
5595
 */
5596
static LY_ERR
5597
xpath_pi_node(struct lyxp_set *set, enum lyxp_axis axis, uint32_t options)
5598
0
{
5599
0
    if (options & LYXP_SCNODE_ALL) {
5600
0
        return moveto_scnode(set, NULL, NULL, 0, axis, options);
5601
0
    }
5602
5603
0
    if (set->type != LYXP_SET_NODE_SET) {
5604
0
        lyxp_set_free_content(set);
5605
0
        return LY_SUCCESS;
5606
0
    }
5607
5608
    /* just like moving to a node with no restrictions */
5609
0
    return moveto_node(set, NULL, NULL, 0, axis, options);
5610
0
}
5611
5612
/**
5613
 * @brief Execute the XPath text() processing instruction (node type). Returns LYXP_SET_NODE_SET
5614
 *        with the text content of the nodes in the context.
5615
 *
5616
 * @param[in,out] set Context and result set at the same time.
5617
 * @param[in] axis Axis to search on.
5618
 * @param[in] options XPath options.
5619
 * @return LY_ERR
5620
 */
5621
static LY_ERR
5622
xpath_pi_text(struct lyxp_set *set, enum lyxp_axis axis, uint32_t options)
5623
0
{
5624
0
    uint32_t i;
5625
5626
0
    if (options & LYXP_SCNODE_ALL) {
5627
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
5628
0
        return LY_SUCCESS;
5629
0
    }
5630
5631
0
    if (set->type != LYXP_SET_NODE_SET) {
5632
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INCTX, print_set_type(set), "text()");
5633
0
        return LY_EVALID;
5634
0
    }
5635
5636
0
    if (axis != LYXP_AXIS_CHILD) {
5637
        /* even following and preceding axescan return text nodes, but whatever */
5638
0
        lyxp_set_free_content(set);
5639
0
        return LY_SUCCESS;
5640
0
    }
5641
5642
0
    for (i = 0; i < set->used; ++i) {
5643
0
        switch (set->val.nodes[i].type) {
5644
0
        case LYXP_NODE_NONE:
5645
0
            LOGINT_RET(set->ctx);
5646
0
        case LYXP_NODE_ELEM:
5647
0
            if (!set->val.nodes[i].node->schema || (set->val.nodes[i].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5648
0
                set->val.nodes[i].type = LYXP_NODE_TEXT;
5649
0
                break;
5650
0
            }
5651
        /* fall through */
5652
0
        case LYXP_NODE_ROOT:
5653
0
        case LYXP_NODE_ROOT_CONFIG:
5654
0
        case LYXP_NODE_TEXT:
5655
0
        case LYXP_NODE_META:
5656
0
            set_remove_node_none(set, i);
5657
0
            break;
5658
0
        }
5659
0
    }
5660
0
    set_remove_nodes_none(set);
5661
5662
0
    return LY_SUCCESS;
5663
0
}
5664
5665
/**
5666
 * @brief Skip prefix and return corresponding module. Logs directly.
5667
 *
5668
 * XPath @p set is expected to be a (sc)node set!
5669
 *
5670
 * @param[in,out] qname Qualified node name. If includes prefix, it is skipped.
5671
 * @param[in,out] qname_len Length of @p qname, is updated accordingly.
5672
 * @param[in] set Set with general XPath context.
5673
 * @param[in] ctx_scnode Current context schema node (parent).
5674
 * @param[out] moveto_mod Expected module of a matching node.
5675
 * @return LY_ERR
5676
 */
5677
static LY_ERR
5678
moveto_resolve_module(const char **qname, uint32_t *qname_len, const struct lyxp_set *set,
5679
        const struct lysc_node *ctx_scnode, const struct lys_module **moveto_mod)
5680
0
{
5681
0
    const struct lys_module *mod = NULL;
5682
0
    const char *ptr;
5683
0
    size_t pref_len;
5684
5685
0
    assert((set->type == LYXP_SET_NODE_SET) || (set->type == LYXP_SET_SCNODE_SET));
5686
5687
0
    if ((ptr = ly_strnchr(*qname, ':', *qname_len))) {
5688
        /* specific module */
5689
0
        pref_len = ptr - *qname;
5690
0
        mod = ly_resolve_prefix(set->ctx, *qname, pref_len, set->format, set->prefix_data);
5691
5692
        /* check for errors and non-implemented modules, as they are not valid */
5693
0
        if (!mod || !mod->implemented) {
5694
0
            if (set->type == LYXP_SET_NODE_SET) {
5695
0
                LOGVAL_DXPATH(set, LY_VCODE_XP_INMOD, (int)pref_len, *qname);
5696
0
            } else {
5697
0
                LOGVAL_SXPATH(set, LY_VCODE_XP_INMOD, (int)pref_len, *qname);
5698
0
            }
5699
0
            return LY_EVALID;
5700
0
        }
5701
5702
0
        *qname += pref_len + 1;
5703
0
        *qname_len -= pref_len + 1;
5704
0
    } else if (((*qname)[0] == '*') && (*qname_len == 1)) {
5705
        /* all modules - special case */
5706
0
        mod = NULL;
5707
0
    } else {
5708
0
        switch (set->format) {
5709
0
        case LY_VALUE_SCHEMA:
5710
0
        case LY_VALUE_SCHEMA_RESOLVED:
5711
            /* current module */
5712
0
            mod = set->cur_mod;
5713
0
            break;
5714
0
        case LY_VALUE_CANON:
5715
0
        case LY_VALUE_CBOR:
5716
0
        case LY_VALUE_JSON:
5717
0
        case LY_VALUE_LYB:
5718
0
        case LY_VALUE_STR_NS:
5719
            /* inherit parent (context node) module */
5720
0
            if (ctx_scnode) {
5721
0
                mod = ctx_scnode->module;
5722
0
            } else {
5723
                /* JSON XPath is our own format (except for identityref), which supports node names matching all the modules */
5724
0
                mod = NULL;
5725
0
            }
5726
0
            break;
5727
0
        case LY_VALUE_XML:
5728
            /* all nodes need to be prefixed */
5729
0
            assert(set->type == LYXP_SET_NODE_SET);
5730
0
            LOGVAL_DXPATH(set, LYVE_DATA, "Non-prefixed node \"%.*s\" in XML xpath found.", (int)*qname_len, *qname);
5731
0
            return LY_EVALID;
5732
0
        }
5733
0
    }
5734
5735
0
    *moveto_mod = mod;
5736
0
    return LY_SUCCESS;
5737
0
}
5738
5739
/**
5740
 * @brief Move context @p set to the root. Handles absolute path.
5741
 *        Result is LYXP_SET_NODE_SET.
5742
 *
5743
 * @param[in,out] set Set to use.
5744
 * @param[in] options Xpath options.
5745
 * @return LY_ERR value.
5746
 */
5747
static LY_ERR
5748
moveto_root(struct lyxp_set *set, uint32_t options)
5749
0
{
5750
0
    assert(!(options & LYXP_SKIP_EXPR));
5751
5752
0
    if (options & LYXP_SCNODE_ALL) {
5753
0
        set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
5754
0
        LY_CHECK_RET(lyxp_set_scnode_insert_node(set, NULL, set->root_type, LYXP_AXIS_SELF, NULL));
5755
0
    } else {
5756
0
        lyxp_set_free_content(set);
5757
0
        set_insert_node(set, NULL, 0, set->root_type, 0);
5758
0
        set->non_child_axis = 0;
5759
0
    }
5760
5761
0
    return LY_SUCCESS;
5762
0
}
5763
5764
/**
5765
 * @brief Check @p node as a part of NameTest processing.
5766
 *
5767
 * @param[in] node Node to check.
5768
 * @param[in] node_type Node type of @p node.
5769
 * @param[in] set Set to read general context from.
5770
 * @param[in] node_name Node name to move to, NULL for any node.
5771
 * @param[in] node_name_len Length of @p node_name.
5772
 * @param[in] moveto_mod Expected module of the node, NULL for no prefix.
5773
 * @param[in] options XPath options.
5774
 * @return LY_ERR (LY_ENOT if node does not match, LY_EINCOMPLETE on unresolved when,
5775
 * LY_EINVAL if neither node nor any children match)
5776
 */
5777
static LY_ERR
5778
moveto_node_check(const struct lyd_node *node, enum lyxp_node_type node_type, const struct lyxp_set *set,
5779
        const char *node_name, uint32_t node_name_len, const struct lys_module *moveto_mod, uint32_t options)
5780
0
{
5781
0
    const struct lysc_node *schema;
5782
5783
0
    if ((node_type == LYXP_NODE_ROOT_CONFIG) || (node_type == LYXP_NODE_ROOT)) {
5784
0
        assert(node_type == set->root_type);
5785
5786
0
        if (node_name || moveto_mod) {
5787
            /* root will not match a specific node */
5788
0
            return LY_ENOT;
5789
0
        }
5790
0
        return LY_SUCCESS;
5791
0
    } else if (node_type != LYXP_NODE_ELEM) {
5792
        /* other types will not match */
5793
0
        return LY_ENOT;
5794
0
    }
5795
5796
    /* get schema node even of an opaque node */
5797
0
    schema = lyd_node_schema(node);
5798
0
    if (!schema) {
5799
        /* unknown opaque node never matches */
5800
0
        return LY_ENOT;
5801
0
    }
5802
5803
    /* module check */
5804
0
    if (moveto_mod) {
5805
0
        if ((set->ctx == LYD_CTX(node)) && (schema->module != moveto_mod)) {
5806
0
            return LY_ENOT;
5807
0
        } else if ((set->ctx != LYD_CTX(node)) && strcmp(schema->module->name, moveto_mod->name)) {
5808
0
            return LY_ENOT;
5809
0
        }
5810
0
    }
5811
5812
    /* context check */
5813
0
    if ((set->root_type == LYXP_NODE_ROOT_CONFIG) && (schema->flags & LYS_CONFIG_R)) {
5814
0
        return LY_EINVAL;
5815
0
    } else if (set->context_op && (schema->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF)) && (schema != set->context_op)) {
5816
0
        return LY_EINVAL;
5817
0
    }
5818
5819
    /* name check */
5820
0
    if (node_name && ly_strncmp(schema->name, node_name, node_name_len)) {
5821
0
        return LY_ENOT;
5822
0
    }
5823
5824
    /* when check, accept the context node because it should only be the path ".", we have checked the when is valid before */
5825
0
    if (!(options & LYXP_IGNORE_WHEN) && lysc_has_when(schema) &&
5826
0
            !(node->flags & (LYD_WHEN_TRUE | LYD_WHEN_FALSE)) && (node != set->cur_node)) {
5827
0
        return LY_EINCOMPLETE;
5828
0
    }
5829
0
    if ((node->flags & LYD_WHEN_FALSE) && (node != set->cur_node)) {
5830
        /* when-false node is treated as non-existent for XPath purposes */
5831
0
        return LY_ENOT;
5832
0
    }
5833
5834
    /* match */
5835
0
    return LY_SUCCESS;
5836
0
}
5837
5838
const struct lyd_node *
5839
lyxp_node_first_doc_root_child(const struct lyd_node *cur_node, const struct lyd_node *tree)
5840
0
{
5841
0
    const struct lyd_node *top_node = NULL, *first = NULL;
5842
0
    const struct ly_ctx *ctx;
5843
0
    const char *mod_name, *name;
5844
0
    const struct lysc_node *schema;
5845
0
    struct lysc_ext_instance *ext;
5846
0
    struct lyplg_ext *plg_ext = NULL;
5847
5848
0
    assert(cur_node || (tree && !tree->parent));
5849
5850
0
    if (!cur_node) {
5851
        /* search in all the trees */
5852
0
        return lyd_first_sibling(tree);
5853
0
    }
5854
5855
    /* try to find an ext instance data node */
5856
0
    top_node = cur_node;
5857
0
    while (top_node->parent && !(top_node->flags & LYD_EXT)) {
5858
0
        top_node = top_node->parent;
5859
0
    }
5860
5861
0
    if (top_node->flags & LYD_EXT) {
5862
0
        ctx = cur_node ? LYD_CTX(cur_node) : LYD_CTX(tree);
5863
0
        mod_name = top_node->schema->module->name;
5864
0
        name = LYD_NAME(top_node);
5865
5866
        /* do not set XPath, we are just looking for a specific ext instance that created these data */
5867
0
        if (!lys_find_child_node_ext(ctx, NULL, NULL, NULL, mod_name, strlen(mod_name), LY_VALUE_JSON, NULL, name,
5868
0
                strlen(name), 0, &schema, &ext)) {
5869
            /* try to find an extension instance callback */
5870
0
            plg_ext = LYSC_GET_EXT_PLG(ext->def->plugin_ref);
5871
0
        }
5872
0
    }
5873
5874
0
    if (plg_ext && plg_ext->node_xpath) {
5875
        /* use the ext instance callback */
5876
0
        plg_ext->node_xpath(ext, cur_node, &first);
5877
0
    } else {
5878
        /* search in all the trees */
5879
0
        first = lyd_first_sibling(top_node);
5880
0
    }
5881
5882
0
    return first;
5883
0
}
5884
5885
/**
5886
 * @brief Get the next node in a forward DFS.
5887
 *
5888
 * @param[in] iter Last returned node.
5889
 * @param[in] stop Node to stop the search on and not return.
5890
 * @return Next node, NULL if there are no more.
5891
 */
5892
static const struct lyd_node *
5893
moveto_axis_node_next_dfs_forward(const struct lyd_node *iter, const struct lyd_node *stop)
5894
0
{
5895
0
    const struct lyd_node *next = NULL;
5896
5897
    /* 1) child */
5898
0
    next = lyd_child_any(iter);
5899
0
    if (!next) {
5900
0
        if (iter == stop) {
5901
            /* reached stop, no more descendants */
5902
0
            return NULL;
5903
0
        }
5904
        /* 2) child next sibling */
5905
0
        next = iter->next;
5906
0
    }
5907
0
    while (!next) {
5908
0
        iter = iter->parent;
5909
0
        if ((!stop && !iter) || (stop && (iter->parent == stop->parent))) {
5910
0
            return NULL;
5911
0
        }
5912
0
        next = iter->next;
5913
0
    }
5914
5915
0
    return next;
5916
0
}
5917
5918
/**
5919
 * @brief Get the next node in a backward DFS.
5920
 *
5921
 * @param[in] iter Last returned node.
5922
 * @param[in] stop Node to stop the search on and not return.
5923
 * @return Next node, NULL if there are no more.
5924
 */
5925
static const struct lyd_node *
5926
moveto_axis_node_next_dfs_backward(const struct lyd_node *iter, const struct lyd_node *stop)
5927
0
{
5928
0
    const struct lyd_node *next = NULL;
5929
5930
    /* 1) previous sibling innermost last child */
5931
0
    next = iter->prev->next ? iter->prev : NULL;
5932
0
    while (next && lyd_child_any(next)) {
5933
0
        next = lyd_child_any(next);
5934
0
        next = next->prev;
5935
0
    }
5936
5937
0
    if (!next) {
5938
        /* 2) parent */
5939
0
        iter = iter->parent;
5940
0
        if ((!stop && !iter) || (stop && (iter->parent == stop->parent))) {
5941
0
            return NULL;
5942
0
        }
5943
0
        next = iter;
5944
0
    }
5945
5946
0
    return next;
5947
0
}
5948
5949
/**
5950
 * @brief Get the first node on an axis for a context node.
5951
 *
5952
 * @param[in,out] iter NULL, updated to the next node.
5953
 * @param[in,out] iter_type Node type 0 of @p iter, updated to the node type of the next node.
5954
 * @param[in] node Context node.
5955
 * @param[in] node_type Type of @p node.
5956
 * @param[in] axis Axis to use.
5957
 * @param[in] set XPath set with the general context.
5958
 * @return LY_SUCCESS on success.
5959
 * @return LY_ENOTFOUND if no next node found.
5960
 */
5961
static LY_ERR
5962
moveto_axis_node_next_first(const struct lyd_node **iter, enum lyxp_node_type *iter_type, const struct lyd_node *node,
5963
        enum lyxp_node_type node_type, enum lyxp_axis axis, struct lyxp_set *set)
5964
0
{
5965
0
    const struct lyd_node *next = NULL;
5966
0
    enum lyxp_node_type next_type = 0;
5967
5968
0
    assert(!*iter);
5969
0
    assert(!*iter_type);
5970
5971
0
    switch (axis) {
5972
0
    case LYXP_AXIS_ANCESTOR_OR_SELF:
5973
0
    case LYXP_AXIS_DESCENDANT_OR_SELF:
5974
0
    case LYXP_AXIS_SELF:
5975
        /* return the context node */
5976
0
        next = node;
5977
0
        next_type = node_type;
5978
0
        break;
5979
5980
0
    case LYXP_AXIS_ANCESTOR:
5981
0
    case LYXP_AXIS_PARENT:
5982
0
        if (node_type == LYXP_NODE_ELEM) {
5983
0
            next = node->parent;
5984
0
            next_type = next ? LYXP_NODE_ELEM : set->root_type;
5985
0
        } else if (node_type == LYXP_NODE_TEXT) {
5986
0
            next = node;
5987
0
            next_type = LYXP_NODE_ELEM;
5988
0
        } else if (node_type == LYXP_NODE_META) {
5989
0
            next = ((struct lyd_meta *)node)->parent;
5990
0
            next_type = LYXP_NODE_ELEM;
5991
0
        } /* else root does not have a parent */
5992
0
        break;
5993
5994
0
    case LYXP_AXIS_CHILD:
5995
0
        if ((node_type == LYXP_NODE_ROOT_CONFIG) || (node_type == LYXP_NODE_ROOT)) {
5996
0
            assert(!node);
5997
5998
            /* start from the first document root child */
5999
0
            next = lyxp_node_first_doc_root_child(set->cur_node, set->tree);
6000
0
            next_type = next ? LYXP_NODE_ELEM : 0;
6001
0
        } else {
6002
            /* search in children */
6003
0
            next = lyd_child_any(node);
6004
0
            next_type = next ? LYXP_NODE_ELEM : 0;
6005
0
        }
6006
0
        break;
6007
6008
0
    case LYXP_AXIS_DESCENDANT:
6009
0
        if ((node_type == LYXP_NODE_ROOT_CONFIG) || (node_type == LYXP_NODE_ROOT)) {
6010
            /* start from the first document root child */
6011
0
            next = lyxp_node_first_doc_root_child(set->cur_node, set->tree);
6012
0
            next_type = LYXP_NODE_ELEM;
6013
0
        } else if (node_type == LYXP_NODE_ELEM) {
6014
            /* start from the context node */
6015
0
            next = moveto_axis_node_next_dfs_forward(node, node);
6016
0
            next_type = next ? LYXP_NODE_ELEM : 0;
6017
0
        } /* else no children */
6018
0
        break;
6019
6020
0
    case LYXP_AXIS_FOLLOWING:
6021
0
    case LYXP_AXIS_FOLLOWING_SIBLING:
6022
0
        if (node_type == LYXP_NODE_ELEM) {
6023
            /* first next sibling */
6024
0
            next = node->next;
6025
0
            next_type = next ? LYXP_NODE_ELEM : 0;
6026
0
        } /* else no sibling */
6027
0
        break;
6028
6029
0
    case LYXP_AXIS_PRECEDING:
6030
0
        if ((node_type == LYXP_NODE_ELEM) && node->prev->next) {
6031
            /* skip ancestors */
6032
0
            next = moveto_axis_node_next_dfs_backward(node, NULL);
6033
0
            assert(next);
6034
0
            next_type = LYXP_NODE_ELEM;
6035
0
        } /* else no sibling */
6036
0
        break;
6037
6038
0
    case LYXP_AXIS_PRECEDING_SIBLING:
6039
0
        if (node_type == LYXP_NODE_ELEM) {
6040
            /* first previous sibling */
6041
0
            next = node->prev->next ? node->prev : NULL;
6042
0
            next_type = next ? LYXP_NODE_ELEM : 0;
6043
0
        } /* else no sibling */
6044
0
        break;
6045
6046
0
    case LYXP_AXIS_ATTRIBUTE:
6047
        /* handled specially */
6048
0
        assert(0);
6049
0
        LOGINT(set->ctx);
6050
0
        break;
6051
0
    }
6052
6053
0
    *iter = next;
6054
0
    *iter_type = next_type;
6055
0
    return next_type ? LY_SUCCESS : LY_ENOTFOUND;
6056
0
}
6057
6058
/**
6059
 * @brief Iterate over all nodes on an axis for a context node.
6060
 *
6061
 * @param[in,out] iter Last returned node, start with NULL, updated to the next node.
6062
 * @param[in,out] iter_type Node type of @p iter, start with 0, updated to the node type of the next node.
6063
 * @param[in] node Context node.
6064
 * @param[in] node_type Type of @p node.
6065
 * @param[in] axis Axis to use.
6066
 * @param[in] set XPath set with the general context.
6067
 * @return LY_SUCCESS on success.
6068
 * @return LY_ENOTFOUND if no next node found.
6069
 */
6070
static LY_ERR
6071
moveto_axis_node_next(const struct lyd_node **iter, enum lyxp_node_type *iter_type, const struct lyd_node *node,
6072
        enum lyxp_node_type node_type, enum lyxp_axis axis, struct lyxp_set *set)
6073
0
{
6074
0
    const struct lyd_node *next = NULL;
6075
0
    enum lyxp_node_type next_type = 0;
6076
6077
0
    if (!*iter_type) {
6078
        /* first returned node */
6079
0
        return moveto_axis_node_next_first(iter, iter_type, node, node_type, axis, set);
6080
0
    }
6081
6082
0
    switch (axis) {
6083
0
    case LYXP_AXIS_ANCESTOR_OR_SELF:
6084
0
        if ((*iter == node) && (*iter_type == node_type)) {
6085
            /* fake first ancestor, we returned self before */
6086
0
            *iter = NULL;
6087
0
            *iter_type = 0;
6088
0
            return moveto_axis_node_next_first(iter, iter_type, node, node_type, LYXP_AXIS_ANCESTOR, set);
6089
0
        } /* else continue ancestor */
6090
6091
    /* fallthrough */
6092
0
    case LYXP_AXIS_ANCESTOR:
6093
0
        if (*iter_type == LYXP_NODE_ELEM) {
6094
            /* iter parent */
6095
0
            next = (*iter)->parent;
6096
0
            next_type = next ? LYXP_NODE_ELEM : set->root_type;
6097
0
        } /* else root, no ancestors */
6098
0
        break;
6099
6100
0
    case LYXP_AXIS_CHILD:
6101
0
        assert(*iter_type == LYXP_NODE_ELEM);
6102
6103
        /* next sibling (child) */
6104
0
        next = (*iter)->next;
6105
0
        next_type = next ? LYXP_NODE_ELEM : 0;
6106
0
        break;
6107
6108
0
    case LYXP_AXIS_DESCENDANT_OR_SELF:
6109
0
        if ((*iter == node) && (*iter_type == node_type)) {
6110
            /* fake first descendant, we returned self before */
6111
0
            *iter = NULL;
6112
0
            *iter_type = 0;
6113
0
            return moveto_axis_node_next_first(iter, iter_type, node, node_type, LYXP_AXIS_DESCENDANT, set);
6114
0
        } /* else continue descendant */
6115
6116
    /* fallthrough */
6117
0
    case LYXP_AXIS_DESCENDANT:
6118
0
        assert(*iter_type == LYXP_NODE_ELEM);
6119
0
        next = moveto_axis_node_next_dfs_forward(*iter, node);
6120
0
        next_type = next ? LYXP_NODE_ELEM : 0;
6121
0
        break;
6122
6123
0
    case LYXP_AXIS_FOLLOWING:
6124
0
        assert(*iter_type == LYXP_NODE_ELEM);
6125
0
        next = moveto_axis_node_next_dfs_forward(*iter, NULL);
6126
0
        next_type = next ? LYXP_NODE_ELEM : 0;
6127
0
        break;
6128
6129
0
    case LYXP_AXIS_FOLLOWING_SIBLING:
6130
0
        assert(*iter_type == LYXP_NODE_ELEM);
6131
6132
        /* next sibling */
6133
0
        next = (*iter)->next;
6134
0
        next_type = next ? LYXP_NODE_ELEM : 0;
6135
0
        break;
6136
6137
0
    case LYXP_AXIS_PARENT:
6138
0
    case LYXP_AXIS_SELF:
6139
        /* parent/self was returned before */
6140
0
        break;
6141
6142
0
    case LYXP_AXIS_PRECEDING:
6143
0
        assert(*iter_type == LYXP_NODE_ELEM);
6144
0
        next = moveto_axis_node_next_dfs_backward(*iter, NULL);
6145
0
        next_type = next ? LYXP_NODE_ELEM : 0;
6146
0
        break;
6147
6148
0
    case LYXP_AXIS_PRECEDING_SIBLING:
6149
0
        assert(*iter_type == LYXP_NODE_ELEM);
6150
6151
        /* previous sibling */
6152
0
        next = (*iter)->prev->next ? (*iter)->prev : NULL;
6153
0
        next_type = next ? LYXP_NODE_ELEM : 0;
6154
0
        break;
6155
6156
0
    case LYXP_AXIS_ATTRIBUTE:
6157
        /* handled specially */
6158
0
        assert(0);
6159
0
        LOGINT(set->ctx);
6160
0
        break;
6161
0
    }
6162
6163
0
    *iter = next;
6164
0
    *iter_type = next_type;
6165
0
    return next_type ? LY_SUCCESS : LY_ENOTFOUND;
6166
0
}
6167
6168
/**
6169
 * @brief Move context @p set to a node. Result is LYXP_SET_NODE_SET. Context position aware.
6170
 *
6171
 * @param[in,out] set Set to use.
6172
 * @param[in] moveto_mod Matching node module, NULL for no prefix.
6173
 * @param[in] ncname Matching node name, NULL for any.
6174
 * @param[in] ncname_len Length of @p ncname.
6175
 * @param[in] axis Axis to search on.
6176
 * @param[in] options XPath options.
6177
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
6178
 */
6179
static LY_ERR
6180
moveto_node(struct lyxp_set *set, const struct lys_module *moveto_mod, const char *ncname,
6181
        uint32_t ncname_len, enum lyxp_axis axis, uint32_t options)
6182
0
{
6183
0
    LY_ERR r, rc = LY_SUCCESS;
6184
0
    const struct lyd_node *iter;
6185
0
    enum lyxp_node_type iter_type;
6186
0
    struct lyxp_set result;
6187
0
    uint32_t i;
6188
6189
0
    if (options & LYXP_SKIP_EXPR) {
6190
0
        return LY_SUCCESS;
6191
0
    }
6192
6193
0
    if (set->type != LYXP_SET_NODE_SET) {
6194
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
6195
0
        return LY_EVALID;
6196
0
    }
6197
6198
    /* init result set */
6199
0
    set_init(&result, set);
6200
6201
0
    for (i = 0; i < set->used; ++i) {
6202
        /* iterate over all the nodes on the axis of the node */
6203
0
        iter = NULL;
6204
0
        iter_type = 0;
6205
0
        while (!moveto_axis_node_next(&iter, &iter_type, set->val.nodes[i].node, set->val.nodes[i].type, axis, set)) {
6206
0
            r = moveto_node_check(iter, iter_type, set, ncname, ncname_len, moveto_mod, options);
6207
0
            if (r == LY_EINCOMPLETE) {
6208
0
                rc = r;
6209
0
                goto cleanup;
6210
0
            } else if (r) {
6211
0
                continue;
6212
0
            }
6213
6214
            /* check for duplicates if they are possible */
6215
0
            switch (axis) {
6216
0
            case LYXP_AXIS_ANCESTOR:
6217
0
            case LYXP_AXIS_ANCESTOR_OR_SELF:
6218
0
            case LYXP_AXIS_DESCENDANT:
6219
0
            case LYXP_AXIS_DESCENDANT_OR_SELF:
6220
0
            case LYXP_AXIS_FOLLOWING:
6221
0
            case LYXP_AXIS_FOLLOWING_SIBLING:
6222
0
            case LYXP_AXIS_PARENT:
6223
0
            case LYXP_AXIS_PRECEDING:
6224
0
            case LYXP_AXIS_PRECEDING_SIBLING:
6225
0
                result.non_child_axis = 1;
6226
0
                if (set_dup_node_check(&result, iter, iter_type, -1)) {
6227
0
                    continue;
6228
0
                }
6229
0
                break;
6230
0
            case LYXP_AXIS_CHILD:
6231
0
            case LYXP_AXIS_SELF:
6232
0
                break;
6233
0
            case LYXP_AXIS_ATTRIBUTE:
6234
                /* handled specially */
6235
0
                assert(0);
6236
0
                LOGINT(set->ctx);
6237
0
                break;
6238
0
            }
6239
6240
            /* matching node */
6241
0
            set_insert_node(&result, iter, 0, iter_type, result.used);
6242
0
        }
6243
0
    }
6244
6245
    /* move result to the set */
6246
0
    lyxp_set_free_content(set);
6247
0
    *set = result;
6248
0
    result.type = LYXP_SET_NUMBER;
6249
6250
    /* sort the final set if the document order could have been broken */
6251
0
    if (set->non_child_axis) {
6252
0
        set_sort(set);
6253
0
    } else {
6254
0
        assert(!set_sort(set));
6255
0
    }
6256
6257
0
cleanup:
6258
0
    lyxp_set_free_content(&result);
6259
0
    return rc;
6260
0
}
6261
6262
/**
6263
 * @brief Move context @p set to child nodes using hashes. Result is LYXP_SET_NODE_SET. Context position aware.
6264
 *
6265
 * @param[in,out] set Set to use.
6266
 * @param[in] scnode Matching node schema.
6267
 * @param[in] predicates If @p scnode is ::LYS_LIST or ::LYS_LEAFLIST, the predicates specifying a single instance.
6268
 * @param[in] options XPath options.
6269
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
6270
 */
6271
static LY_ERR
6272
moveto_node_hash_child(struct lyxp_set *set, const struct lysc_node *scnode, const struct ly_path_predicate *predicates,
6273
        uint32_t options)
6274
0
{
6275
0
    LY_ERR ret = LY_SUCCESS, r;
6276
0
    uint32_t i;
6277
0
    const struct lyd_node *siblings;
6278
0
    struct lyxp_set result;
6279
0
    struct lyd_node *sub, *inst = NULL;
6280
6281
0
    assert(scnode && (!(scnode->nodetype & (LYS_LIST | LYS_LEAFLIST)) || predicates));
6282
6283
    /* init result set */
6284
0
    set_init(&result, set);
6285
6286
0
    if (options & LYXP_SKIP_EXPR) {
6287
0
        goto cleanup;
6288
0
    }
6289
6290
0
    if (set->type != LYXP_SET_NODE_SET) {
6291
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
6292
0
        ret = LY_EVALID;
6293
0
        goto cleanup;
6294
0
    }
6295
6296
    /* context check for all the nodes since we have the schema node */
6297
0
    if ((set->root_type == LYXP_NODE_ROOT_CONFIG) && (scnode->flags & LYS_CONFIG_R)) {
6298
0
        lyxp_set_free_content(set);
6299
0
        goto cleanup;
6300
0
    } else if (set->context_op && (scnode->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF)) &&
6301
0
            (scnode != set->context_op)) {
6302
0
        lyxp_set_free_content(set);
6303
0
        goto cleanup;
6304
0
    }
6305
6306
    /* create specific data instance if needed */
6307
0
    if (scnode->nodetype == LYS_LIST) {
6308
0
        LY_CHECK_GOTO(ret = lyd_create_list(scnode, predicates, NULL, 1, &inst), cleanup);
6309
0
    } else if (scnode->nodetype == LYS_LEAFLIST) {
6310
0
        LY_CHECK_GOTO(ret = lyd_create_term(scnode, NULL, predicates[0].value, strlen(predicates[0].value) * 8, 1, 1,
6311
0
                NULL, LY_VALUE_CANON, NULL, LYD_HINT_DATA, NULL, &inst), cleanup);
6312
0
    }
6313
6314
0
    for (i = 0; i < set->used; ++i) {
6315
0
        siblings = NULL;
6316
6317
0
        if ((set->val.nodes[i].type == LYXP_NODE_ROOT_CONFIG) || (set->val.nodes[i].type == LYXP_NODE_ROOT)) {
6318
0
            assert(!set->val.nodes[i].node);
6319
6320
            /* search in all the trees */
6321
0
            siblings = set->tree;
6322
0
        } else if (set->val.nodes[i].type == LYXP_NODE_ELEM) {
6323
            /* search in children */
6324
0
            siblings = lyd_child(set->val.nodes[i].node);
6325
0
        }
6326
6327
        /* find the node using hashes */
6328
0
        if (inst) {
6329
0
            r = lyd_find_sibling_first(siblings, inst, &sub);
6330
0
        } else {
6331
0
            r = lyd_find_sibling_val(siblings, scnode, NULL, 0, &sub);
6332
0
        }
6333
0
        if (r == LY_ENOTFOUND) {
6334
            /* may still be an opaque node */
6335
0
            r = lyd_find_sibling_opaq_next(siblings, scnode->name, &sub);
6336
0
        }
6337
0
        LY_CHECK_ERR_GOTO(r && (r != LY_ENOTFOUND), ret = r, cleanup);
6338
6339
        /* when check */
6340
0
        if (!(options & LYXP_IGNORE_WHEN) && sub && lysc_has_when(sub->schema) &&
6341
0
                !(sub->flags & (LYD_WHEN_TRUE | LYD_WHEN_FALSE))) {
6342
0
            ret = LY_EINCOMPLETE;
6343
0
            goto cleanup;
6344
0
        }
6345
0
        if (sub && (sub->flags & LYD_WHEN_FALSE)) {
6346
            /* when-false node is treated as non-existent */
6347
0
            sub = NULL;
6348
0
        }
6349
6350
0
        if (sub) {
6351
            /* pos filled later */
6352
0
            set_insert_node(&result, sub, 0, LYXP_NODE_ELEM, result.used);
6353
0
        }
6354
0
    }
6355
6356
    /* move result to the set */
6357
0
    lyxp_set_free_content(set);
6358
0
    *set = result;
6359
0
    result.type = LYXP_SET_NUMBER;
6360
0
    assert(!set_sort(set));
6361
6362
0
cleanup:
6363
0
    lyxp_set_free_content(&result);
6364
0
    lyd_free_tree(inst);
6365
0
    return ret;
6366
0
}
6367
6368
/**
6369
 * @brief Check @p node as a part of schema NameTest processing.
6370
 *
6371
 * @param[in] node Schema node to check.
6372
 * @param[in] ctx_scnode Context node.
6373
 * @param[in] set Set to read general context from.
6374
 * @param[in] node_name Node name to move to, NULL for any nodes.
6375
 * @param[in] node_name_len Length of @p node_name.
6376
 * @param[in] moveto_mod Expected module of the node, NULL for no prefix.
6377
 * @return LY_ERR (LY_ENOT if node does not match, LY_EINVAL if neither node nor any children match)
6378
 */
6379
static LY_ERR
6380
moveto_scnode_check(const struct lysc_node *node, const struct lysc_node *ctx_scnode, const struct lyxp_set *set,
6381
        const char *node_name, uint32_t node_name_len, const struct lys_module *moveto_mod)
6382
0
{
6383
0
    if (!moveto_mod && node_name) {
6384
0
        switch (set->format) {
6385
0
        case LY_VALUE_SCHEMA:
6386
0
        case LY_VALUE_SCHEMA_RESOLVED:
6387
            /* use current module */
6388
0
            moveto_mod = set->cur_mod;
6389
0
            break;
6390
0
        case LY_VALUE_CBOR:
6391
0
        case LY_VALUE_JSON:
6392
0
        case LY_VALUE_LYB:
6393
0
        case LY_VALUE_STR_NS:
6394
            /* inherit module of the context node, if any */
6395
0
            if (ctx_scnode) {
6396
0
                moveto_mod = ctx_scnode->module;
6397
0
            }
6398
0
            break;
6399
0
        case LY_VALUE_CANON:
6400
0
        case LY_VALUE_XML:
6401
            /* not defined */
6402
0
            LOGINT(set->ctx);
6403
0
            return LY_EINVAL;
6404
0
        }
6405
0
    }
6406
6407
0
    if (!node) {
6408
        /* root will not match a specific node */
6409
0
        if (node_name || moveto_mod) {
6410
0
            return LY_ENOT;
6411
0
        }
6412
0
        return LY_SUCCESS;
6413
0
    }
6414
6415
    /* module check */
6416
0
    if (moveto_mod && (node->module != moveto_mod)) {
6417
0
        return LY_ENOT;
6418
0
    }
6419
6420
    /* context check */
6421
0
    if ((set->root_type == LYXP_NODE_ROOT_CONFIG) && (node->flags & LYS_CONFIG_R)) {
6422
0
        return LY_EINVAL;
6423
0
    } else if (set->context_op && (node->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF)) && (node != set->context_op)) {
6424
0
        return LY_EINVAL;
6425
0
    }
6426
6427
    /* name check */
6428
0
    if (node_name && ly_strncmp(node->name, node_name, node_name_len)) {
6429
0
        return LY_ENOT;
6430
0
    }
6431
6432
    /* match */
6433
0
    return LY_SUCCESS;
6434
0
}
6435
6436
/**
6437
 * @brief Get the next node in a forward schema node DFS.
6438
 *
6439
 * @param[in] iter Last returned node.
6440
 * @param[in] stop Node to stop the search on and not return.
6441
 * @param[in] getnext_opts Options for ::lys_getnext().
6442
 * @return Next node, NULL if there are no more.
6443
 */
6444
static const struct lysc_node *
6445
moveto_axis_scnode_next_dfs_forward(const struct lysc_node *iter, const struct lysc_node *stop, uint32_t getnext_opts)
6446
0
{
6447
0
    const struct lysc_node *next = NULL;
6448
6449
0
    next = lysc_node_child(iter);
6450
0
    if (!next) {
6451
        /* no children, try siblings */
6452
0
        if ((iter == stop) || !lysc_data_parent(iter)) {
6453
            /* we are done, no next element to process */
6454
0
            return NULL;
6455
0
        }
6456
6457
0
        next = lys_getnext(iter, lysc_data_parent(iter), NULL, getnext_opts);
6458
0
    }
6459
0
    while (!next && iter) {
6460
        /* parent is already processed, go to its sibling */
6461
0
        iter = iter->parent;
6462
0
        if ((iter == stop) || !lysc_data_parent(iter)) {
6463
            /* we are done, no next element to process */
6464
0
            return NULL;
6465
0
        }
6466
0
        next = lys_getnext(iter, lysc_data_parent(iter), NULL, getnext_opts);
6467
0
    }
6468
6469
0
    return next;
6470
0
}
6471
6472
/**
6473
 * @brief Consider schema node based on its in_ctx enum value.
6474
 *
6475
 * @param[in,out] in_ctx In_ctx enum of the schema node, may be updated.
6476
 * @param[in] axis Axis to use.
6477
 * @return LY_SUCCESS on success.
6478
 * @return LY_ENOT if the node should not be returned.
6479
 */
6480
static LY_ERR
6481
moveto_axis_scnode_next_in_ctx(int32_t *in_ctx, enum lyxp_axis axis)
6482
0
{
6483
0
    switch (axis) {
6484
0
    case LYXP_AXIS_SELF:
6485
0
        if ((*in_ctx == LYXP_SET_SCNODE_START) || (*in_ctx == LYXP_SET_SCNODE_ATOM_CTX)) {
6486
            /* additionally put the start node into context */
6487
0
            *in_ctx = LYXP_SET_SCNODE_ATOM_CTX;
6488
0
            return LY_SUCCESS;
6489
0
        }
6490
0
        break;
6491
0
    case LYXP_AXIS_PARENT:
6492
0
    case LYXP_AXIS_ANCESTOR_OR_SELF:
6493
0
    case LYXP_AXIS_ANCESTOR:
6494
0
    case LYXP_AXIS_DESCENDANT_OR_SELF:
6495
0
    case LYXP_AXIS_DESCENDANT:
6496
0
    case LYXP_AXIS_FOLLOWING:
6497
0
    case LYXP_AXIS_FOLLOWING_SIBLING:
6498
0
    case LYXP_AXIS_PRECEDING:
6499
0
    case LYXP_AXIS_PRECEDING_SIBLING:
6500
0
    case LYXP_AXIS_CHILD:
6501
0
        if (*in_ctx == LYXP_SET_SCNODE_START) {
6502
            /* remember that context node was used */
6503
0
            *in_ctx = LYXP_SET_SCNODE_START_USED;
6504
0
            return LY_SUCCESS;
6505
0
        } else if (*in_ctx == LYXP_SET_SCNODE_ATOM_CTX) {
6506
            /* traversed */
6507
0
            *in_ctx = LYXP_SET_SCNODE_ATOM_NODE;
6508
0
            return LY_SUCCESS;
6509
0
        }
6510
0
        break;
6511
0
    case LYXP_AXIS_ATTRIBUTE:
6512
        /* unreachable */
6513
0
        assert(0);
6514
0
        LOGINT(NULL);
6515
0
        break;
6516
0
    }
6517
6518
0
    return LY_ENOT;
6519
0
}
6520
6521
/**
6522
 * @brief Get previous sibling for a schema node.
6523
 *
6524
 * @param[in] scnode Schema node.
6525
 * @param[in] getnext_opts Options for ::lys_getnext().
6526
 * @return Previous sibling, NULL if none.
6527
 */
6528
static const struct lysc_node *
6529
moveto_axis_scnode_preceding_sibling(const struct lysc_node *scnode, uint32_t getnext_opts)
6530
0
{
6531
0
    const struct lysc_node *next = NULL, *prev = NULL;
6532
6533
0
    while ((next = lys_getnext(next, lysc_data_parent(scnode), scnode->module->compiled, getnext_opts))) {
6534
0
        if (next == scnode) {
6535
0
            break;
6536
0
        }
6537
6538
0
        prev = next;
6539
0
    }
6540
6541
0
    return prev;
6542
0
}
6543
6544
/**
6545
 * @brief Get the first schema node on an axis for a context node.
6546
 *
6547
 * @param[in,out] iter Last returned node, start with NULL, updated to the next node.
6548
 * @param[in,out] iter_type Node type of @p iter, start with 0, updated to the node type of the next node.
6549
 * @param[in,out] iter_mod Internal module iterator, do not change.
6550
 * @param[in,out] iter_mod_idx Internal module index iterator, do not change.
6551
 * @param[in] scnode Context node.
6552
 * @param[in] node_type Type of @p scnode.
6553
 * @param[in] in_ctx In_ctx enum of @p scnode.
6554
 * @param[in] axis Axis to use.
6555
 * @param[in] set XPath set with the general context.
6556
 * @param[in] getnext_opts Options for ::lys_getnext().
6557
 * @return LY_SUCCESS on success.
6558
 * @return LY_ENOTFOUND if no next node found.
6559
 */
6560
static LY_ERR
6561
moveto_axis_scnode_next_first(const struct lysc_node **iter, enum lyxp_node_type *iter_type, const struct lys_module **iter_mod,
6562
        uint32_t *iter_mod_idx, const struct lysc_node *scnode, enum lyxp_node_type node_type, enum lyxp_axis axis,
6563
        struct lyxp_set *set, uint32_t getnext_opts)
6564
0
{
6565
0
    const struct lysc_node *next = NULL;
6566
0
    enum lyxp_node_type next_type = 0;
6567
6568
0
    assert(!*iter);
6569
0
    assert(!*iter_type);
6570
6571
0
    *iter_mod = NULL;
6572
0
    *iter_mod_idx = 0;
6573
6574
0
    switch (axis) {
6575
0
    case LYXP_AXIS_ANCESTOR_OR_SELF:
6576
0
    case LYXP_AXIS_DESCENDANT_OR_SELF:
6577
0
    case LYXP_AXIS_SELF:
6578
0
        if ((node_type == LYXP_NODE_ROOT_CONFIG) || (node_type == LYXP_NODE_ROOT) || (node_type == LYXP_NODE_ELEM)) {
6579
            /* just return the node */
6580
0
            next = scnode;
6581
0
            next_type = node_type;
6582
0
        }
6583
0
        break;
6584
6585
0
    case LYXP_AXIS_ANCESTOR:
6586
0
    case LYXP_AXIS_PARENT:
6587
0
        if (node_type == LYXP_NODE_ELEM) {
6588
0
            next = lysc_data_parent(scnode);
6589
0
            next_type = next ? LYXP_NODE_ELEM : set->root_type;
6590
0
        } /* else no parent */
6591
0
        break;
6592
6593
0
    case LYXP_AXIS_DESCENDANT:
6594
0
    case LYXP_AXIS_CHILD:
6595
0
        if ((node_type == LYXP_NODE_ROOT_CONFIG) || (node_type == LYXP_NODE_ROOT)) {
6596
            /* it can actually be in any module, it's all <running>, and even if it's moveto_mod (if set),
6597
             * it can be in a top-level augment */
6598
0
            while ((*iter_mod = ly_ctx_get_module_iter(set->ctx, iter_mod_idx))) {
6599
                /* module may not be implemented or not compiled yet */
6600
0
                if (!(*iter_mod)->compiled) {
6601
0
                    continue;
6602
0
                }
6603
6604
                /* get next node */
6605
0
                if ((next = lys_getnext(NULL, NULL, (*iter_mod)->compiled, getnext_opts))) {
6606
0
                    next_type = LYXP_NODE_ELEM;
6607
0
                    break;
6608
0
                }
6609
0
            }
6610
0
        } else if (node_type == LYXP_NODE_ELEM) {
6611
            /* get next node */
6612
0
            next = lys_getnext(NULL, scnode, NULL, getnext_opts);
6613
0
            next_type = next ? LYXP_NODE_ELEM : 0;
6614
0
        }
6615
0
        break;
6616
6617
0
    case LYXP_AXIS_FOLLOWING:
6618
0
    case LYXP_AXIS_FOLLOWING_SIBLING:
6619
0
        if (node_type == LYXP_NODE_ELEM) {
6620
            /* first next sibling */
6621
0
            next = lys_getnext(scnode, lysc_data_parent(scnode), scnode->module->compiled, getnext_opts);
6622
0
            next_type = next ? LYXP_NODE_ELEM : 0;
6623
0
        } /* else no sibling */
6624
0
        break;
6625
6626
0
    case LYXP_AXIS_PRECEDING:
6627
0
    case LYXP_AXIS_PRECEDING_SIBLING:
6628
0
        if (node_type == LYXP_NODE_ELEM) {
6629
            /* first parent sibling */
6630
0
            next = lys_getnext(NULL, lysc_data_parent(scnode), scnode->module->compiled, getnext_opts);
6631
0
            if (next == scnode) {
6632
                /* no preceding sibling */
6633
0
                next = NULL;
6634
0
            }
6635
0
            next_type = next ? LYXP_NODE_ELEM : 0;
6636
0
        } /* else no sibling */
6637
0
        break;
6638
6639
0
    case LYXP_AXIS_ATTRIBUTE:
6640
        /* unreachable */
6641
0
        assert(0);
6642
0
        LOGINT(set->ctx);
6643
0
        break;
6644
0
    }
6645
6646
0
    *iter = next;
6647
0
    *iter_type = next_type;
6648
0
    return next_type ? LY_SUCCESS : LY_ENOTFOUND;
6649
0
}
6650
6651
/**
6652
 * @brief Iterate over all schema nodes on an axis for a context node.
6653
 *
6654
 * @param[in,out] iter Last returned node, start with NULL, updated to the next node.
6655
 * @param[in,out] iter_type Node type of @p iter, start with 0, updated to the node type of the next node.
6656
 * @param[in,out] iter_mod Internal module iterator, do not change.
6657
 * @param[in,out] iter_mod_idx Internal module index iterator, do not change.
6658
 * @param[in] scnode Context node.
6659
 * @param[in] node_type Type of @p scnode.
6660
 * @param[in] axis Axis to use.
6661
 * @param[in] set XPath set with the general context.
6662
 * @param[in] getnext_opts Options for ::lys_getnext().
6663
 * @return LY_SUCCESS on success.
6664
 * @return LY_ENOTFOUND if no next node found.
6665
 */
6666
static LY_ERR
6667
moveto_axis_scnode_next(const struct lysc_node **iter, enum lyxp_node_type *iter_type, const struct lys_module **iter_mod,
6668
        uint32_t *iter_mod_idx, const struct lysc_node *scnode, enum lyxp_node_type node_type, enum lyxp_axis axis,
6669
        struct lyxp_set *set, uint32_t getnext_opts)
6670
0
{
6671
0
    const struct lysc_node *next = NULL, *dfs_stop;
6672
0
    enum lyxp_node_type next_type = 0;
6673
6674
0
    if (!*iter_type) {
6675
        /* first returned node */
6676
0
        return moveto_axis_scnode_next_first(iter, iter_type, iter_mod, iter_mod_idx, scnode, node_type, axis, set,
6677
0
                getnext_opts);
6678
0
    }
6679
6680
0
    switch (axis) {
6681
0
    case LYXP_AXIS_PARENT:
6682
0
    case LYXP_AXIS_SELF:
6683
        /* parent/self was returned before */
6684
0
        break;
6685
6686
0
    case LYXP_AXIS_ANCESTOR_OR_SELF:
6687
0
        if ((*iter == scnode) && (*iter_type == node_type)) {
6688
            /* fake first ancestor, we returned self before */
6689
0
            *iter = NULL;
6690
0
            *iter_type = 0;
6691
0
            return moveto_axis_scnode_next_first(iter, iter_type, iter_mod, iter_mod_idx, scnode, node_type,
6692
0
                    LYXP_AXIS_ANCESTOR, set, getnext_opts);
6693
0
        } /* else continue ancestor */
6694
6695
    /* fallthrough */
6696
0
    case LYXP_AXIS_ANCESTOR:
6697
0
        if (*iter_type == LYXP_NODE_ELEM) {
6698
0
            next = lysc_data_parent(*iter);
6699
0
            next_type = next ? LYXP_NODE_ELEM : set->root_type;
6700
0
        } /* else no ancestor */
6701
0
        break;
6702
6703
0
    case LYXP_AXIS_DESCENDANT_OR_SELF:
6704
0
        if ((*iter == scnode) && (*iter_type == node_type)) {
6705
            /* fake first descendant, we returned self before */
6706
0
            *iter = NULL;
6707
0
            *iter_type = 0;
6708
0
            return moveto_axis_scnode_next_first(iter, iter_type, iter_mod, iter_mod_idx, scnode, node_type,
6709
0
                    LYXP_AXIS_DESCENDANT, set, getnext_opts);
6710
0
        } /* else DFS until context node */
6711
0
        dfs_stop = scnode;
6712
6713
    /* fallthrough */
6714
0
    case LYXP_AXIS_DESCENDANT:
6715
0
        if (axis == LYXP_AXIS_DESCENDANT) {
6716
            /* DFS until the context node */
6717
0
            dfs_stop = scnode;
6718
0
        }
6719
6720
    /* fallthrough */
6721
0
    case LYXP_AXIS_PRECEDING:
6722
0
        if (axis == LYXP_AXIS_PRECEDING) {
6723
            /* DFS until the previous sibling */
6724
0
            dfs_stop = moveto_axis_scnode_preceding_sibling(scnode, getnext_opts);
6725
0
            assert(dfs_stop);
6726
6727
0
            if (*iter == dfs_stop) {
6728
                /* we are done */
6729
0
                break;
6730
0
            }
6731
0
        }
6732
6733
    /* fallthrough */
6734
0
    case LYXP_AXIS_FOLLOWING:
6735
0
        if (axis == LYXP_AXIS_FOLLOWING) {
6736
            /* DFS through the whole module */
6737
0
            dfs_stop = NULL;
6738
0
        }
6739
6740
        /* nested nodes */
6741
0
        assert(*iter);
6742
0
        next = moveto_axis_scnode_next_dfs_forward(*iter, dfs_stop, getnext_opts);
6743
0
        if (next) {
6744
0
            next_type = LYXP_NODE_ELEM;
6745
0
            break;
6746
0
        } /* else get next top-level node just like a child */
6747
6748
    /* fallthrough */
6749
0
    case LYXP_AXIS_CHILD:
6750
0
    case LYXP_AXIS_FOLLOWING_SIBLING:
6751
0
        if (!*iter_mod) {
6752
            /* nodes from a single module */
6753
0
            if ((next = lys_getnext(*iter, lysc_data_parent(*iter), (*iter)->module->compiled, getnext_opts))) {
6754
0
                next_type = LYXP_NODE_ELEM;
6755
0
                break;
6756
0
            }
6757
6758
0
            assert(scnode);
6759
0
            if ((axis != LYXP_AXIS_CHILD) && !lysc_data_parent(scnode)) {
6760
                /* iterating over top-level nodes, find next */
6761
0
                while (lysc_data_parent(*iter)) {
6762
0
                    *iter = lysc_data_parent(*iter);
6763
0
                }
6764
0
                if ((next = lys_getnext(*iter, NULL, (*iter)->module->compiled, getnext_opts))) {
6765
0
                    next_type = LYXP_NODE_ELEM;
6766
0
                    break;
6767
0
                }
6768
0
            }
6769
0
        }
6770
6771
0
        while (*iter_mod) {
6772
            /* module top-level nodes */
6773
0
            if ((next = lys_getnext(*iter, NULL, (*iter_mod)->compiled, getnext_opts))) {
6774
0
                next_type = LYXP_NODE_ELEM;
6775
0
                break;
6776
0
            }
6777
6778
            /* get next module */
6779
0
            while ((*iter_mod = ly_ctx_get_module_iter(set->ctx, iter_mod_idx))) {
6780
                /* module may not be implemented or not compiled yet */
6781
0
                if ((*iter_mod)->compiled) {
6782
0
                    break;
6783
0
                }
6784
0
            }
6785
6786
            /* new module, start over */
6787
0
            *iter = NULL;
6788
0
        }
6789
0
        break;
6790
6791
0
    case LYXP_AXIS_PRECEDING_SIBLING:
6792
0
        assert(*iter);
6793
6794
        /* next parent sibling until scnode */
6795
0
        next = lys_getnext(*iter, lysc_data_parent(*iter), (*iter)->module->compiled, getnext_opts);
6796
0
        if (next == scnode) {
6797
            /* no previous sibling */
6798
0
            next = NULL;
6799
0
        }
6800
0
        next_type = next ? LYXP_NODE_ELEM : 0;
6801
0
        break;
6802
6803
0
    case LYXP_AXIS_ATTRIBUTE:
6804
        /* unreachable */
6805
0
        assert(0);
6806
0
        LOGINT(set->ctx);
6807
0
        break;
6808
0
    }
6809
6810
0
    *iter = next;
6811
0
    *iter_type = next_type;
6812
0
    return next_type ? LY_SUCCESS : LY_ENOTFOUND;
6813
0
}
6814
6815
/**
6816
 * @brief Move context @p set to a schema node. Result is LYXP_SET_SCNODE_SET (or LYXP_SET_EMPTY).
6817
 *
6818
 * @param[in,out] set Set to use.
6819
 * @param[in] moveto_mod Matching node module, NULL for no prefix.
6820
 * @param[in] ncname Matching node name, NULL for any.
6821
 * @param[in] ncname_len Length of @p ncname.
6822
 * @param[in] axis Axis to search on.
6823
 * @param[in] options XPath options.
6824
 * @return LY_ERR
6825
 */
6826
static LY_ERR
6827
moveto_scnode(struct lyxp_set *set, const struct lys_module *moveto_mod, const char *ncname,
6828
        uint32_t ncname_len, enum lyxp_axis axis, uint32_t options)
6829
0
{
6830
0
    LY_ERR r;
6831
0
    ly_bool temp_ctx = 0, is_node;
6832
0
    uint32_t getnext_opts, orig_used, i, mod_idx, idx;
6833
0
    const struct lys_module *mod = NULL;
6834
0
    const struct lysc_node *iter;
6835
0
    enum lyxp_node_type iter_type;
6836
6837
0
    if (options & LYXP_SKIP_EXPR) {
6838
0
        return LY_SUCCESS;
6839
0
    }
6840
6841
0
    if (set->type != LYXP_SET_SCNODE_SET) {
6842
0
        LOGVAL_SXPATH(set, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
6843
0
        return LY_EVALID;
6844
0
    }
6845
6846
    /* getnext opts */
6847
0
    getnext_opts = 0;
6848
0
    if (options & LYXP_SCNODE_OUTPUT) {
6849
0
        getnext_opts |= LYS_GETNEXT_OUTPUT;
6850
0
    }
6851
6852
0
    orig_used = set->used;
6853
0
    for (i = 0; i < orig_used; ++i) {
6854
        /* update in_ctx first */
6855
0
        if (moveto_axis_scnode_next_in_ctx(&set->val.scnodes[i].in_ctx, axis)) {
6856
            /* not usable, skip */
6857
0
            continue;
6858
0
        }
6859
6860
0
        iter = NULL;
6861
0
        iter_type = 0;
6862
0
        while (!moveto_axis_scnode_next(&iter, &iter_type, &mod, &mod_idx, set->val.scnodes[i].scnode,
6863
0
                set->val.scnodes[i].type, axis, set, getnext_opts)) {
6864
0
            if (moveto_scnode_check(iter, NULL, set, ncname, ncname_len, moveto_mod)) {
6865
0
                continue;
6866
0
            }
6867
6868
            /* insert */
6869
0
            LY_CHECK_RET(lyxp_set_scnode_insert_node(set, iter, iter_type, axis, &idx));
6870
6871
            /* we need to prevent these nodes from being considered in this moveto */
6872
0
            if ((idx < orig_used) && (idx > i)) {
6873
0
                set->val.scnodes[idx].in_ctx = LYXP_SET_SCNODE_ATOM_NEW_CTX;
6874
0
                temp_ctx = 1;
6875
0
            }
6876
0
        }
6877
6878
        /* only consider extension nodes after no local ones were found */
6879
0
        if ((set->val.scnodes[i].type == LYXP_NODE_ROOT) || (set->val.scnodes[i].type == LYXP_NODE_ROOT_CONFIG) ||
6880
0
                (set->val.scnodes[i].type == LYXP_NODE_ELEM)) {
6881
0
            is_node = 1;
6882
0
        } else {
6883
0
            is_node = 0;
6884
0
        }
6885
0
        if ((orig_used == set->used) && moveto_mod && ncname &&
6886
0
                ((axis == LYXP_AXIS_DESCENDANT) || (axis == LYXP_AXIS_CHILD)) && is_node) {
6887
0
            r = lys_find_child_node_ext(set->ctx, moveto_mod, NULL, set->val.scnodes[i].scnode, moveto_mod->name,
6888
0
                    strlen(moveto_mod->name), LY_VALUE_JSON, NULL, ncname, ncname_len, 1, &iter, NULL);
6889
0
            LY_CHECK_RET(r && (r != LY_ENOT), r);
6890
6891
0
            if (!r) {
6892
                /* there is a matching node from an extension, use it */
6893
0
                LY_CHECK_RET(lyxp_set_scnode_insert_node(set, iter, LYXP_NODE_ELEM, axis, &idx));
6894
0
                if ((idx < orig_used) && (idx > i)) {
6895
0
                    set->val.scnodes[idx].in_ctx = LYXP_SET_SCNODE_ATOM_NEW_CTX;
6896
0
                    temp_ctx = 1;
6897
0
                }
6898
0
            }
6899
0
        }
6900
0
    }
6901
6902
    /* correct temporary in_ctx values */
6903
0
    if (temp_ctx) {
6904
0
        for (i = 0; i < orig_used; ++i) {
6905
0
            if (set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_NEW_CTX) {
6906
0
                set->val.scnodes[i].in_ctx = LYXP_SET_SCNODE_ATOM_CTX;
6907
0
            }
6908
0
        }
6909
0
    }
6910
6911
0
    return LY_SUCCESS;
6912
0
}
6913
6914
/**
6915
 * @brief Move context @p set to a child node and all its descendants. Result is LYXP_SET_NODE_SET.
6916
 *        Context position aware.
6917
 *
6918
 * @param[in] set Set to use.
6919
 * @param[in] moveto_mod Matching node module, NULL for no prefix.
6920
 * @param[in] ncname Matching node name, NULL for any.
6921
 * @param[in] ncname_len Length of @p ncname.
6922
 * @param[in] options XPath options.
6923
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
6924
 */
6925
static LY_ERR
6926
moveto_node_alldesc_child(struct lyxp_set *set, const struct lys_module *moveto_mod,
6927
        const char *ncname, uint32_t ncname_len, uint32_t options)
6928
0
{
6929
0
    uint32_t i;
6930
0
    const struct lyd_node *elem;
6931
0
    struct lyxp_set ret_set;
6932
0
    LY_ERR rc;
6933
6934
0
    if (options & LYXP_SKIP_EXPR) {
6935
0
        return LY_SUCCESS;
6936
0
    }
6937
6938
0
    if (set->type != LYXP_SET_NODE_SET) {
6939
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
6940
0
        return LY_EVALID;
6941
0
    }
6942
6943
    /* replace the original nodes (and throws away all text and meta nodes, root is replaced by a child) */
6944
0
    rc = xpath_pi_node(set, LYXP_AXIS_CHILD, options);
6945
0
    LY_CHECK_RET(rc);
6946
6947
    /* this loop traverses all the nodes in the set and adds/keeps only those that match qname */
6948
0
    set_init(&ret_set, set);
6949
0
    for (i = 0; i < set->used; ++i) {
6950
0
        LYD_TREE_DFS_BEGIN(set->val.nodes[i].node, elem) {
6951
0
            rc = moveto_node_check(elem, LYXP_NODE_ELEM, set, ncname, ncname_len, moveto_mod, options);
6952
0
            if (!rc) {
6953
                /* add matching node into result set */
6954
0
                set_insert_node(&ret_set, elem, 0, LYXP_NODE_ELEM, ret_set.used);
6955
0
                if (set_dup_node_check(set, elem, LYXP_NODE_ELEM, i)) {
6956
                    /* the node is a duplicate, we'll process it later in the set */
6957
0
                    LYD_TREE_DFS_continue = 1;
6958
0
                }
6959
0
            } else if (rc == LY_EINCOMPLETE) {
6960
0
                return rc;
6961
0
            } else if (rc == LY_EINVAL) {
6962
0
                LYD_TREE_DFS_continue = 1;
6963
0
            }
6964
6965
0
            LYD_TREE_ANY_DFS_END(set->val.nodes[i].node, elem);
6966
0
        }
6967
0
    }
6968
6969
    /* make the temporary set the current one */
6970
0
    ret_set.ctx_pos = set->ctx_pos;
6971
0
    ret_set.ctx_size = set->ctx_size;
6972
0
    lyxp_set_free_content(set);
6973
0
    memcpy(set, &ret_set, sizeof *set);
6974
0
    assert(!set_sort(set));
6975
6976
0
    return LY_SUCCESS;
6977
0
}
6978
6979
/**
6980
 * @brief Move context @p set to a child schema node and all its descendants starting from a node.
6981
 * Result is LYXP_SET_NODE_SET.
6982
 *
6983
 * @param[in] set Set to use.
6984
 * @param[in] start Start node whose subtree to add.
6985
 * @param[in] start_idx Index of @p start in @p set.
6986
 * @param[in] moveto_mod Matching node module, NULL for no prefix.
6987
 * @param[in] ncname Matching node name, NULL for any.
6988
 * @param[in] ncname Length of @p ncname.
6989
 * @param[in] options XPath options.
6990
 * @return LY_ERR value.
6991
 */
6992
static LY_ERR
6993
moveto_scnode_dfs(struct lyxp_set *set, const struct lysc_node *start, uint32_t start_idx,
6994
        const struct lys_module *moveto_mod, const char *ncname, uint32_t ncname_len, uint32_t options)
6995
0
{
6996
0
    const struct lysc_node *next, *elem;
6997
0
    uint32_t idx;
6998
0
    LY_ERR rc;
6999
7000
    /* TREE DFS */
7001
0
    for (elem = next = start; elem; elem = next) {
7002
0
        if (elem->nodetype & (LYS_CHOICE | LYS_CASE)) {
7003
            /* schema-only nodes */
7004
0
            goto next_iter;
7005
0
        }
7006
7007
0
        rc = moveto_scnode_check(elem, start, set, ncname, ncname_len, moveto_mod);
7008
0
        if (!rc) {
7009
0
            if (lyxp_set_scnode_contains(set, elem, LYXP_NODE_ELEM, start_idx, &idx)) {
7010
0
                set->val.scnodes[idx].in_ctx = LYXP_SET_SCNODE_ATOM_CTX;
7011
0
                if (idx > start_idx) {
7012
                    /* we will process it later in the set */
7013
0
                    goto skip_children;
7014
0
                }
7015
0
            } else {
7016
0
                LY_CHECK_RET(lyxp_set_scnode_insert_node(set, elem, LYXP_NODE_ELEM, LYXP_AXIS_DESCENDANT, NULL));
7017
0
            }
7018
0
        } else if (rc == LY_EINVAL) {
7019
0
            goto skip_children;
7020
0
        }
7021
7022
0
next_iter:
7023
        /* TREE DFS NEXT ELEM */
7024
        /* select element for the next run - children first */
7025
0
        next = lysc_node_child(elem);
7026
0
        if (next && (next->nodetype == LYS_INPUT) && (options & LYXP_SCNODE_OUTPUT)) {
7027
0
            next = next->next;
7028
0
        } else if (next && (next->nodetype == LYS_OUTPUT) && !(options & LYXP_SCNODE_OUTPUT)) {
7029
0
            next = next->next;
7030
0
        }
7031
0
        if (!next) {
7032
0
skip_children:
7033
            /* no children, so try siblings, but only if it's not the start,
7034
             * that is considered to be the root and it's siblings are not traversed */
7035
0
            if (elem != start) {
7036
0
                next = elem->next;
7037
0
            } else {
7038
0
                break;
7039
0
            }
7040
0
        }
7041
0
        while (!next) {
7042
            /* no siblings, go back through the parents */
7043
0
            if (elem->parent == start) {
7044
                /* we are done, no next element to process */
7045
0
                break;
7046
0
            }
7047
            /* parent is already processed, go to its sibling */
7048
0
            elem = elem->parent;
7049
0
            next = elem->next;
7050
0
        }
7051
0
    }
7052
7053
0
    return LY_SUCCESS;
7054
0
}
7055
7056
/**
7057
 * @brief Move context @p set to a child schema node and all its descendants. Result is LYXP_SET_NODE_SET.
7058
 *
7059
 * @param[in] set Set to use.
7060
 * @param[in] moveto_mod Matching node module, NULL for no prefix.
7061
 * @param[in] ncname Matching node name, NULL for any.
7062
 * @param[in] ncname_len Length of @p ncname.
7063
 * @param[in] options XPath options.
7064
 * @return LY_ERR value.
7065
 */
7066
static LY_ERR
7067
moveto_scnode_alldesc_child(struct lyxp_set *set, const struct lys_module *moveto_mod,
7068
        const char *ncname, uint32_t ncname_len, uint32_t options)
7069
0
{
7070
0
    uint32_t i, orig_used, mod_idx;
7071
0
    const struct lys_module *mod;
7072
0
    const struct lysc_node *root;
7073
7074
0
    if (options & LYXP_SKIP_EXPR) {
7075
0
        return LY_SUCCESS;
7076
0
    }
7077
7078
0
    if (set->type != LYXP_SET_SCNODE_SET) {
7079
0
        LOGVAL_SXPATH(set, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
7080
0
        return LY_EVALID;
7081
0
    }
7082
7083
0
    orig_used = set->used;
7084
0
    for (i = 0; i < orig_used; ++i) {
7085
0
        if (set->val.scnodes[i].in_ctx != LYXP_SET_SCNODE_ATOM_CTX) {
7086
0
            if (set->val.scnodes[i].in_ctx != LYXP_SET_SCNODE_START) {
7087
0
                continue;
7088
0
            }
7089
7090
            /* remember context node */
7091
0
            set->val.scnodes[i].in_ctx = LYXP_SET_SCNODE_START_USED;
7092
0
        } else {
7093
0
            set->val.scnodes[i].in_ctx = LYXP_SET_SCNODE_ATOM_NODE;
7094
0
        }
7095
7096
0
        if ((set->val.scnodes[i].type == LYXP_NODE_ROOT_CONFIG) || (set->val.scnodes[i].type == LYXP_NODE_ROOT)) {
7097
            /* traverse all top-level nodes in all the modules */
7098
0
            mod_idx = 0;
7099
0
            while ((mod = ly_ctx_get_module_iter(set->ctx, &mod_idx))) {
7100
                /* module may not be implemented or not compiled yet */
7101
0
                if (!mod->compiled) {
7102
0
                    continue;
7103
0
                }
7104
7105
0
                root = NULL;
7106
                /* no getnext opts needed */
7107
0
                while ((root = lys_getnext(root, NULL, mod->compiled, 0))) {
7108
0
                    LY_CHECK_RET(moveto_scnode_dfs(set, root, i, moveto_mod, ncname, ncname_len, options));
7109
0
                }
7110
0
            }
7111
7112
0
        } else if (set->val.scnodes[i].type == LYXP_NODE_ELEM) {
7113
            /* add all the descendants recursively */
7114
0
            LY_CHECK_RET(moveto_scnode_dfs(set, set->val.scnodes[i].scnode, i, moveto_mod, ncname, ncname_len, options));
7115
0
        }
7116
0
    }
7117
7118
0
    return LY_SUCCESS;
7119
0
}
7120
7121
/**
7122
 * @brief Move context @p set to an attribute. Result is LYXP_SET_NODE_SET.
7123
 *        Indirectly context position aware.
7124
 *
7125
 * @param[in,out] set Set to use.
7126
 * @param[in] mod Matching metadata module, NULL for any.
7127
 * @param[in] ncname Matching metadata name, NULL for any.
7128
 * @param[in] ncname_len Length of @p ncname.
7129
 * @param[in] options XPath options.
7130
 * @return LY_ERR
7131
 */
7132
static LY_ERR
7133
moveto_attr(struct lyxp_set *set, const struct lys_module *mod, const char *ncname, uint32_t ncname_len, uint32_t options)
7134
0
{
7135
0
    struct lyd_meta *sub;
7136
7137
0
    if (options & LYXP_SKIP_EXPR) {
7138
0
        return LY_SUCCESS;
7139
0
    }
7140
7141
0
    if (set->type != LYXP_SET_NODE_SET) {
7142
0
        LOGVAL_DXPATH(set, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
7143
0
        return LY_EVALID;
7144
0
    }
7145
7146
0
    for (uint32_t i = 0; i < set->used; ) {
7147
0
        ly_bool replaced = 0;
7148
7149
        /* only attributes of an elem (not dummy) can be in the result, skip all the rest;
7150
         * our attributes are always qualified */
7151
0
        if (set->val.nodes[i].type == LYXP_NODE_ELEM) {
7152
0
            for (sub = set->val.nodes[i].node->meta; sub; sub = sub->next) {
7153
7154
                /* check "namespace" */
7155
0
                if (mod && (sub->annotation->module != mod)) {
7156
0
                    continue;
7157
0
                }
7158
7159
0
                if (!ncname || !ly_strncmp(sub->name, ncname, ncname_len)) {
7160
                    /* match */
7161
0
                    if (!replaced) {
7162
0
                        set->val.meta[i].meta = sub;
7163
0
                        set->val.meta[i].type = LYXP_NODE_META;
7164
                        /* pos does not change */
7165
0
                        replaced = 1;
7166
0
                    } else {
7167
0
                        set_insert_node(set, (struct lyd_node *)sub, set->val.nodes[i].pos, LYXP_NODE_META, i + 1);
7168
0
                    }
7169
0
                    ++i;
7170
0
                }
7171
0
            }
7172
0
        }
7173
7174
0
        if (!replaced) {
7175
            /* no match */
7176
0
            set_remove_node(set, i);
7177
0
        }
7178
0
    }
7179
7180
0
    return LY_SUCCESS;
7181
0
}
7182
7183
/**
7184
 * @brief Move context @p set1 to union with @p set2. @p set2 is emptied afterwards.
7185
 *        Result is LYXP_SET_NODE_SET. Context position aware.
7186
 *
7187
 * @param[in,out] set1 Set to use for the result.
7188
 * @param[in] set2 Set that is copied to @p set1.
7189
 * @return LY_ERR
7190
 */
7191
static LY_ERR
7192
moveto_union(struct lyxp_set *set1, struct lyxp_set *set2)
7193
0
{
7194
0
    LY_ERR rc;
7195
7196
0
    if ((set1->type != LYXP_SET_NODE_SET) || (set2->type != LYXP_SET_NODE_SET)) {
7197
0
        LOGVAL_DXPATH(set1, LY_VCODE_XP_INOP_2, "union", print_set_type(set1), print_set_type(set2));
7198
0
        return LY_EVALID;
7199
0
    }
7200
7201
    /* set2 is empty or both set1 and set2 */
7202
0
    if (!set2->used) {
7203
0
        return LY_SUCCESS;
7204
0
    }
7205
7206
0
    if (!set1->used) {
7207
        /* release hidden allocated data (lyxp_set.size) */
7208
0
        lyxp_set_free_content(set1);
7209
        /* direct copying of the entire structure */
7210
0
        memcpy(set1, set2, sizeof *set1);
7211
        /* dynamic memory belongs to set1 now, do not free */
7212
0
        memset(set2, 0, sizeof *set2);
7213
0
        return LY_SUCCESS;
7214
0
    }
7215
7216
    /* we assume sets are sorted */
7217
0
    assert(!set_sort(set1) && !set_sort(set2));
7218
7219
    /* sort, remove duplicates */
7220
0
    rc = set_sorted_merge(set1, set2);
7221
0
    LY_CHECK_RET(rc);
7222
7223
    /* final set must be sorted */
7224
0
    assert(!set_sort(set1));
7225
7226
0
    return LY_SUCCESS;
7227
0
}
7228
7229
/**
7230
 * @brief Move context @p set to an attribute in any of the descendants. Result is LYXP_SET_NODE_SET.
7231
 *        Context position aware.
7232
 *
7233
 * @param[in,out] set Set to use.
7234
 * @param[in] mod Matching metadata module, NULL for any.
7235
 * @param[in] ncname Matching metadata name, NULL for any.
7236
 * @param[in] ncname_len Length of @p ncname.
7237
 * @param[in] options XPath options.
7238
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7239
 */
7240
static int
7241
moveto_attr_alldesc(struct lyxp_set *set, const struct lys_module *mod, const char *ncname, uint32_t ncname_len,
7242
        uint32_t options)
7243
0
{
7244
0
    struct lyd_meta *sub;
7245
0
    struct lyxp_set *set_all_desc = NULL;
7246
0
    LY_ERR rc;
7247
7248
0
    if (options & LYXP_SKIP_EXPR) {
7249
0
        return LY_SUCCESS;
7250
0
    }
7251
7252
0
    if (set->type != LYXP_SET_NODE_SET) {
7253
0
        LOGVAL_XPATH(set, options, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
7254
0
        return LY_EVALID;
7255
0
    }
7256
7257
    /* can be optimized similarly to moveto_node_alldesc() and save considerable amount of memory,
7258
     * but it likely won't be used much, so it's a waste of time */
7259
    /* copy the context */
7260
0
    set_all_desc = set_copy(set);
7261
    /* get all descendant nodes (the original context nodes are removed) */
7262
0
    rc = moveto_node_alldesc_child(set_all_desc, NULL, NULL, 0, options);
7263
0
    if (rc != LY_SUCCESS) {
7264
0
        lyxp_set_free(set_all_desc);
7265
0
        return rc;
7266
0
    }
7267
    /* prepend the original context nodes */
7268
0
    rc = moveto_union(set, set_all_desc);
7269
0
    if (rc != LY_SUCCESS) {
7270
0
        lyxp_set_free(set_all_desc);
7271
0
        return rc;
7272
0
    }
7273
0
    lyxp_set_free(set_all_desc);
7274
7275
0
    for (uint32_t i = 0; i < set->used; ) {
7276
0
        ly_bool replaced = 0;
7277
7278
        /* only attributes of an elem can be in the result, skip all the rest,
7279
         * we have all attributes qualified in lyd tree */
7280
0
        if (set->val.nodes[i].type == LYXP_NODE_ELEM) {
7281
0
            for (sub = set->val.nodes[i].node->meta; sub; sub = sub->next) {
7282
                /* check "namespace" */
7283
0
                if (mod && (sub->annotation->module != mod)) {
7284
0
                    continue;
7285
0
                }
7286
7287
0
                if (!ncname || !ly_strncmp(sub->name, ncname, ncname_len)) {
7288
                    /* match */
7289
0
                    if (!replaced) {
7290
0
                        set->val.meta[i].meta = sub;
7291
0
                        set->val.meta[i].type = LYXP_NODE_META;
7292
                        /* pos does not change */
7293
0
                        replaced = 1;
7294
0
                    } else {
7295
0
                        set_insert_node(set, (struct lyd_node *)sub, set->val.meta[i].pos, LYXP_NODE_META, i + 1);
7296
0
                    }
7297
0
                    ++i;
7298
0
                }
7299
0
            }
7300
0
        }
7301
7302
0
        if (!replaced) {
7303
            /* no match */
7304
0
            set_remove_node(set, i);
7305
0
        }
7306
0
    }
7307
7308
0
    return LY_SUCCESS;
7309
0
}
7310
7311
/**
7312
 * @brief Move context @p set1 single item to the result of a comparison.
7313
 *
7314
 * @param[in] set1 First set with the item to compare.
7315
 * @param[in] idx1 Index of the item in @p set1.
7316
 * @param[in] set2 Second set.
7317
 * @param[in] op Comparison operator to process.
7318
 * @param[in] switch_operands Whether to switch sets as operands; whether it is `set1 op set2` or `set2 op set1`.
7319
 * @param[out] result Result of the comparison.
7320
 * @return LY_ERR value.
7321
 */
7322
static LY_ERR
7323
moveto_op_comp_item(const struct lyxp_set *set1, uint32_t idx1, struct lyxp_set *set2, const char *op,
7324
        ly_bool switch_operands, ly_bool *result)
7325
0
{
7326
0
    struct lyxp_set tmp1 = {0};
7327
0
    LY_ERR rc = LY_SUCCESS;
7328
7329
0
    assert(set1->type == LYXP_SET_NODE_SET);
7330
7331
    /* cast set1 */
7332
0
    switch (set2->type) {
7333
0
    case LYXP_SET_NUMBER:
7334
0
        rc = set_comp_cast(&tmp1, set1, LYXP_SET_NUMBER, idx1);
7335
0
        break;
7336
0
    case LYXP_SET_BOOLEAN:
7337
0
        rc = set_comp_cast(&tmp1, set1, LYXP_SET_BOOLEAN, idx1);
7338
0
        break;
7339
0
    default:
7340
0
        rc = set_comp_cast(&tmp1, set1, LYXP_SET_STRING, idx1);
7341
0
        break;
7342
0
    }
7343
0
    LY_CHECK_GOTO(rc, cleanup);
7344
7345
    /* canonize set2 */
7346
0
    LY_CHECK_GOTO(rc = set_comp_canonize(set2, &set1->val.nodes[idx1]), cleanup);
7347
7348
    /* compare recursively and store the result */
7349
0
    if (switch_operands) {
7350
0
        LY_CHECK_GOTO(rc = moveto_op_comp(set2, &tmp1, op, result), cleanup);
7351
0
    } else {
7352
0
        LY_CHECK_GOTO(rc = moveto_op_comp(&tmp1, set2, op, result), cleanup);
7353
0
    }
7354
7355
0
cleanup:
7356
0
    lyxp_set_free_content(&tmp1);
7357
0
    return rc;
7358
0
}
7359
7360
/**
7361
 * @brief Compare 2 XPath numbers.
7362
 *
7363
 * @param[in] set1 Set with the first number.
7364
 * @param[in] set2 Set with the second number.
7365
 * @param[out] cmp Result of the comparison.
7366
 * @return LY_ERR value.
7367
 */
7368
static LY_ERR
7369
moveto_num_cmp(const struct lyxp_set *set1, const struct lyxp_set *set2, int *cmp)
7370
0
{
7371
0
    LY_ERR rc = LY_SUCCESS;
7372
0
    char *str1 = NULL, *str2 = NULL;
7373
0
    long double num1, num2;
7374
0
    int r;
7375
0
    ly_bool neg = 0;
7376
7377
0
    assert(set1->type == LYXP_SET_NUMBER);
7378
0
    assert(set2->type == LYXP_SET_NUMBER);
7379
7380
    /* avoid issues with -0 */
7381
0
    num1 = (set1->val.num == 0) ? 0 : set1->val.num;
7382
0
    num2 = (set2->val.num == 0) ? 0 : set2->val.num;
7383
7384
0
    if (num1 < 0) {
7385
0
        if (num2 > 0) {
7386
            /* negative compared to positive */
7387
0
            *cmp = -1;
7388
0
            goto cleanup;
7389
0
        } else if (num2 < 0) {
7390
            /* both negative */
7391
0
            neg = 1;
7392
0
            num1 *= -1;
7393
0
            num2 *= -1;
7394
0
        }
7395
0
    } else if (num1 > 0) {
7396
0
        if (num2 < 0) {
7397
            /* positive compared to negative */
7398
0
            *cmp = 1;
7399
0
            goto cleanup;
7400
0
        }
7401
0
    }
7402
7403
    /* compare doubles using strings to avoid precision issues */
7404
0
    if (num1 > num2) {
7405
        /* print the bigger number first */
7406
0
        r = asprintf(&str1, "%Lf", num1);
7407
0
        LY_CHECK_ERR_GOTO(r == -1, LOGMEM(set1->ctx); rc = LY_EMEM, cleanup);
7408
7409
        /* print the smaller number with the same count of numbers */
7410
0
        r = asprintf(&str2, "%0*Lf", r, num2);
7411
0
        LY_CHECK_ERR_GOTO(r == -1, LOGMEM(set1->ctx); rc = LY_EMEM, cleanup);
7412
0
    } else {
7413
0
        r = asprintf(&str2, "%Lf", num2);
7414
0
        LY_CHECK_ERR_GOTO(r == -1, LOGMEM(set1->ctx); rc = LY_EMEM, cleanup);
7415
7416
0
        r = asprintf(&str1, "%0*Lf", r, num1);
7417
0
        LY_CHECK_ERR_GOTO(r == -1, LOGMEM(set1->ctx); rc = LY_EMEM, cleanup);
7418
0
    }
7419
7420
    /* compare */
7421
0
    *cmp = strcmp(str1, str2);
7422
0
    if (neg) {
7423
0
        *cmp *= -1;
7424
0
    }
7425
7426
0
cleanup:
7427
0
    free(str1);
7428
0
    free(str2);
7429
0
    return rc;
7430
0
}
7431
7432
/**
7433
 * @brief Move context @p set1 to the result of a comparison. Handles '=', '!=', '<=', '<', '>=', or '>'.
7434
 *        Result is LYXP_SET_BOOLEAN. Indirectly context position aware.
7435
 *
7436
 * @param[in] set1 Set acting as the first operand for @p op.
7437
 * @param[in] set2 Set acting as the second operand for @p op.
7438
 * @param[in] op Comparison operator to process.
7439
 * @param[out] result Result of the comparison.
7440
 * @return LY_ERR
7441
 */
7442
static LY_ERR
7443
moveto_op_comp(struct lyxp_set *set1, struct lyxp_set *set2, const char *op, ly_bool *result)
7444
0
{
7445
    /*
7446
     * NODE SET + NODE SET = NODE SET + STRING /(1 NODE SET) 2 STRING
7447
     * NODE SET + STRING = STRING + STRING     /1 STRING (2 STRING)
7448
     * NODE SET + NUMBER = NUMBER + NUMBER     /1 NUMBER (2 NUMBER)
7449
     * NODE SET + BOOLEAN = BOOLEAN + BOOLEAN  /1 BOOLEAN (2 BOOLEAN)
7450
     * STRING + NODE SET = STRING + STRING     /(1 STRING) 2 STRING
7451
     * NUMBER + NODE SET = NUMBER + NUMBER     /(1 NUMBER) 2 NUMBER
7452
     * BOOLEAN + NODE SET = BOOLEAN + BOOLEAN  /(1 BOOLEAN) 2 BOOLEAN
7453
     *
7454
     * '=' or '!='
7455
     * BOOLEAN + BOOLEAN
7456
     * BOOLEAN + STRING = BOOLEAN + BOOLEAN    /(1 BOOLEAN) 2 BOOLEAN
7457
     * BOOLEAN + NUMBER = BOOLEAN + BOOLEAN    /(1 BOOLEAN) 2 BOOLEAN
7458
     * STRING + BOOLEAN = BOOLEAN + BOOLEAN    /1 BOOLEAN (2 BOOLEAN)
7459
     * NUMBER + BOOLEAN = BOOLEAN + BOOLEAN    /1 BOOLEAN (2 BOOLEAN)
7460
     * NUMBER + NUMBER
7461
     * NUMBER + STRING = NUMBER + NUMBER       /(1 NUMBER) 2 NUMBER
7462
     * STRING + NUMBER = NUMBER + NUMBER       /1 NUMBER (2 NUMBER)
7463
     * STRING + STRING
7464
     *
7465
     * '<=', '<', '>=', '>'
7466
     * NUMBER + NUMBER
7467
     * BOOLEAN + BOOLEAN = NUMBER + NUMBER     /1 NUMBER, 2 NUMBER
7468
     * BOOLEAN + NUMBER = NUMBER + NUMBER      /1 NUMBER (2 NUMBER)
7469
     * BOOLEAN + STRING = NUMBER + NUMBER      /1 NUMBER, 2 NUMBER
7470
     * NUMBER + STRING = NUMBER + NUMBER       /(1 NUMBER) 2 NUMBER
7471
     * STRING + STRING = NUMBER + NUMBER       /1 NUMBER, 2 NUMBER
7472
     * STRING + NUMBER = NUMBER + NUMBER       /1 NUMBER (2 NUMBER)
7473
     * NUMBER + BOOLEAN = NUMBER + NUMBER      /(1 NUMBER) 2 NUMBER
7474
     * STRING + BOOLEAN = NUMBER + NUMBER      /(1 NUMBER) 2 NUMBER
7475
     */
7476
0
    uint32_t i;
7477
0
    int cmp;
7478
0
    LY_ERR rc;
7479
7480
    /* iterative evaluation with node-sets */
7481
0
    if ((set1->type == LYXP_SET_NODE_SET) || (set2->type == LYXP_SET_NODE_SET)) {
7482
0
        if (set1->type == LYXP_SET_NODE_SET) {
7483
0
            for (i = 0; i < set1->used; ++i) {
7484
                /* evaluate for the single item */
7485
0
                LY_CHECK_RET(moveto_op_comp_item(set1, i, set2, op, 0, result));
7486
7487
                /* lazy evaluation until true */
7488
0
                if (*result) {
7489
0
                    return LY_SUCCESS;
7490
0
                }
7491
0
            }
7492
0
        } else {
7493
0
            for (i = 0; i < set2->used; ++i) {
7494
                /* evaluate for the single item */
7495
0
                LY_CHECK_RET(moveto_op_comp_item(set2, i, set1, op, 1, result));
7496
7497
                /* lazy evaluation until true */
7498
0
                if (*result) {
7499
0
                    return LY_SUCCESS;
7500
0
                }
7501
0
            }
7502
0
        }
7503
7504
        /* false for all the nodes */
7505
0
        *result = 0;
7506
0
        return LY_SUCCESS;
7507
0
    }
7508
7509
    /* first convert properly */
7510
0
    if ((op[0] == '=') || (op[0] == '!')) {
7511
0
        if ((set1->type == LYXP_SET_BOOLEAN) || (set2->type == LYXP_SET_BOOLEAN)) {
7512
0
            lyxp_set_cast(set1, LYXP_SET_BOOLEAN);
7513
0
            lyxp_set_cast(set2, LYXP_SET_BOOLEAN);
7514
0
        } else if ((set1->type == LYXP_SET_NUMBER) || (set2->type == LYXP_SET_NUMBER)) {
7515
0
            rc = lyxp_set_cast(set1, LYXP_SET_NUMBER);
7516
0
            LY_CHECK_RET(rc);
7517
0
            rc = lyxp_set_cast(set2, LYXP_SET_NUMBER);
7518
0
            LY_CHECK_RET(rc);
7519
0
        } /* else we have 2 strings */
7520
0
    } else {
7521
0
        rc = lyxp_set_cast(set1, LYXP_SET_NUMBER);
7522
0
        LY_CHECK_RET(rc);
7523
0
        rc = lyxp_set_cast(set2, LYXP_SET_NUMBER);
7524
0
        LY_CHECK_RET(rc);
7525
0
    }
7526
7527
0
    assert(set1->type == set2->type);
7528
7529
    /* compute result */
7530
0
    if (op[0] == '=') {
7531
0
        if (set1->type == LYXP_SET_BOOLEAN) {
7532
0
            *result = (set1->val.bln == set2->val.bln);
7533
0
        } else if (set1->type == LYXP_SET_NUMBER) {
7534
0
            LY_CHECK_RET(moveto_num_cmp(set1, set2, &cmp));
7535
0
            *result = (cmp ? 0 : 1);
7536
0
        } else {
7537
0
            assert(set1->type == LYXP_SET_STRING);
7538
0
            *result = strcmp(set1->val.str, set2->val.str) ? 0 : 1;
7539
0
        }
7540
0
    } else if (op[0] == '!') {
7541
0
        if (set1->type == LYXP_SET_BOOLEAN) {
7542
0
            *result = (set1->val.bln != set2->val.bln);
7543
0
        } else if (set1->type == LYXP_SET_NUMBER) {
7544
0
            LY_CHECK_RET(moveto_num_cmp(set1, set2, &cmp));
7545
0
            *result = (cmp ? 1 : 0);
7546
0
        } else {
7547
0
            assert(set1->type == LYXP_SET_STRING);
7548
0
            *result = strcmp(set1->val.str, set2->val.str) ? 1 : 0;
7549
0
        }
7550
0
    } else {
7551
0
        LY_CHECK_RET(moveto_num_cmp(set1, set2, &cmp));
7552
7553
0
        if (op[0] == '<') {
7554
0
            if (op[1] == '=') {
7555
0
                *result = ((cmp <= 0) ? 1 : 0);
7556
0
            } else {
7557
0
                *result = ((cmp < 0) ? 1 : 0);
7558
0
            }
7559
0
        } else {
7560
0
            if (op[1] == '=') {
7561
0
                *result = ((cmp >= 0) ? 1 : 0);
7562
0
            } else {
7563
0
                *result = ((cmp > 0) ? 1 : 0);
7564
0
            }
7565
0
        }
7566
0
    }
7567
7568
0
    return LY_SUCCESS;
7569
0
}
7570
7571
/**
7572
 * @brief Move context @p set to the result of a basic operation. Handles '+', '-', unary '-', '*', 'div',
7573
 *        or 'mod'. Result is LYXP_SET_NUMBER. Indirectly context position aware.
7574
 *
7575
 * @param[in,out] set1 Set to use for the result.
7576
 * @param[in] set2 Set acting as the second operand for @p op.
7577
 * @param[in] op Operator to process.
7578
 * @return LY_ERR
7579
 */
7580
static LY_ERR
7581
moveto_op_math(struct lyxp_set *set1, struct lyxp_set *set2, const char *op)
7582
0
{
7583
0
    LY_ERR rc;
7584
7585
    /* unary '-' */
7586
0
    if (!set2 && (op[0] == '-')) {
7587
0
        rc = lyxp_set_cast(set1, LYXP_SET_NUMBER);
7588
0
        LY_CHECK_RET(rc);
7589
0
        set1->val.num *= -1;
7590
0
        lyxp_set_free(set2);
7591
0
        return LY_SUCCESS;
7592
0
    }
7593
7594
0
    assert(set1 && set2);
7595
7596
0
    rc = lyxp_set_cast(set1, LYXP_SET_NUMBER);
7597
0
    LY_CHECK_RET(rc);
7598
0
    rc = lyxp_set_cast(set2, LYXP_SET_NUMBER);
7599
0
    LY_CHECK_RET(rc);
7600
7601
0
    switch (op[0]) {
7602
    /* '+' */
7603
0
    case '+':
7604
0
        set1->val.num += set2->val.num;
7605
0
        break;
7606
7607
    /* '-' */
7608
0
    case '-':
7609
0
        set1->val.num -= set2->val.num;
7610
0
        break;
7611
7612
    /* '*' */
7613
0
    case '*':
7614
0
        set1->val.num *= set2->val.num;
7615
0
        break;
7616
7617
    /* 'div' */
7618
0
    case 'd':
7619
0
        set1->val.num /= set2->val.num;
7620
0
        break;
7621
7622
    /* 'mod' */
7623
0
    case 'm':
7624
0
        set1->val.num = fmodl(set1->val.num, set2->val.num);
7625
0
        break;
7626
7627
0
    default:
7628
0
        LOGINT_RET(set1->ctx);
7629
0
    }
7630
7631
0
    return LY_SUCCESS;
7632
0
}
7633
7634
/**
7635
 * @brief Evaluate Predicate. Logs directly on error.
7636
 *
7637
 * [9] Predicate ::= '[' Expr ']'
7638
 *
7639
 * @param[in] exp Parsed XPath expression.
7640
 * @param[in] tok_idx Position in the expression @p exp.
7641
 * @param[in,out] set Context and result set.
7642
 * @param[in] options XPath options.
7643
 * @param[in] axis Axis to search on.
7644
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7645
 */
7646
static LY_ERR
7647
eval_predicate(const struct lyxp_expr *exp, uint32_t *tok_idx, struct lyxp_set *set, uint32_t options, enum lyxp_axis axis)
7648
0
{
7649
0
    LY_ERR rc;
7650
0
    uint32_t i, orig_exp, orig_pos, orig_size;
7651
0
    int32_t pred_in_ctx;
7652
0
    ly_bool reverse_axis = 0;
7653
0
    struct lyxp_set set2 = {0};
7654
7655
    /* '[' */
7656
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
7657
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
7658
0
    ++(*tok_idx);
7659
7660
0
    if (options & LYXP_SKIP_EXPR) {
7661
0
only_parse:
7662
0
        rc = eval_expr_select(exp, tok_idx, 0, set, options | LYXP_SKIP_EXPR);
7663
0
        LY_CHECK_RET(rc);
7664
0
    } else if (set->type == LYXP_SET_NODE_SET) {
7665
        /* we (possibly) need the set sorted, it can affect the result (if the predicate result is a number) */
7666
0
        assert(!set_sort(set));
7667
7668
        /* empty set, nothing to evaluate */
7669
0
        if (!set->used) {
7670
0
            goto only_parse;
7671
0
        }
7672
7673
        /* decide forward or reverse axis */
7674
0
        switch (axis) {
7675
0
        case LYXP_AXIS_ANCESTOR:
7676
0
        case LYXP_AXIS_ANCESTOR_OR_SELF:
7677
0
        case LYXP_AXIS_PRECEDING:
7678
0
        case LYXP_AXIS_PRECEDING_SIBLING:
7679
0
            reverse_axis = 1;
7680
0
            break;
7681
0
        case LYXP_AXIS_DESCENDANT:
7682
0
        case LYXP_AXIS_DESCENDANT_OR_SELF:
7683
0
        case LYXP_AXIS_FOLLOWING:
7684
0
        case LYXP_AXIS_FOLLOWING_SIBLING:
7685
0
        case LYXP_AXIS_PARENT:
7686
0
        case LYXP_AXIS_CHILD:
7687
0
        case LYXP_AXIS_SELF:
7688
0
        case LYXP_AXIS_ATTRIBUTE:
7689
0
            reverse_axis = 0;
7690
0
            break;
7691
0
        }
7692
7693
0
        orig_exp = *tok_idx;
7694
0
        orig_pos = reverse_axis ? set->used + 1 : 0;
7695
0
        orig_size = set->used;
7696
0
        for (i = 0; i < set->used; ++i) {
7697
0
            set_init(&set2, set);
7698
0
            set_insert_node(&set2, set->val.nodes[i].node, set->val.nodes[i].pos, set->val.nodes[i].type, 0);
7699
7700
            /* remember the node context position for position() and context size for last() */
7701
0
            orig_pos += reverse_axis ? -1 : 1;
7702
7703
0
            set2.ctx_pos = orig_pos;
7704
0
            set2.ctx_size = orig_size;
7705
0
            *tok_idx = orig_exp;
7706
7707
0
            rc = eval_expr_select(exp, tok_idx, 0, &set2, options);
7708
0
            if (!rc && set2.not_found) {
7709
0
                set->not_found = 1;
7710
0
                break;
7711
0
            }
7712
0
            if (rc) {
7713
0
                lyxp_set_free_content(&set2);
7714
0
                return rc;
7715
0
            }
7716
7717
            /* number is a proximity position */
7718
0
            if (set2.type == LYXP_SET_NUMBER) {
7719
0
                if ((long long)set2.val.num == orig_pos) {
7720
0
                    set2.val.num = 1;
7721
0
                } else {
7722
0
                    set2.val.num = 0;
7723
0
                }
7724
0
            }
7725
0
            lyxp_set_cast(&set2, LYXP_SET_BOOLEAN);
7726
7727
            /* predicate satisfied or not? */
7728
0
            if (!set2.val.bln) {
7729
0
                set_remove_node_none(set, i);
7730
0
            }
7731
0
        }
7732
0
        set_remove_nodes_none(set);
7733
7734
0
    } else if (set->type == LYXP_SET_SCNODE_SET) {
7735
0
        for (i = 0; i < set->used; ++i) {
7736
0
            if (set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_CTX) {
7737
                /* there is a currently-valid node */
7738
0
                break;
7739
0
            }
7740
0
        }
7741
        /* empty set, nothing to evaluate */
7742
0
        if (i == set->used) {
7743
0
            goto only_parse;
7744
0
        }
7745
7746
0
        orig_exp = *tok_idx;
7747
7748
        /* set special in_ctx to all the valid snodes */
7749
0
        pred_in_ctx = set_scnode_new_in_ctx(set);
7750
7751
        /* use the valid snodes one-by-one */
7752
0
        for (i = 0; i < set->used; ++i) {
7753
0
            if (set->val.scnodes[i].in_ctx != pred_in_ctx) {
7754
0
                continue;
7755
0
            }
7756
0
            set->val.scnodes[i].in_ctx = LYXP_SET_SCNODE_ATOM_CTX;
7757
7758
0
            *tok_idx = orig_exp;
7759
7760
0
            rc = eval_expr_select(exp, tok_idx, 0, set, options);
7761
0
            if (!rc && set->not_found) {
7762
0
                break;
7763
0
            }
7764
0
            LY_CHECK_RET(rc);
7765
7766
0
            set->val.scnodes[i].in_ctx = pred_in_ctx;
7767
0
        }
7768
7769
        /* restore the state as it was before the predicate */
7770
0
        for (i = 0; i < set->used; ++i) {
7771
0
            if (set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_CTX) {
7772
0
                set->val.scnodes[i].in_ctx = LYXP_SET_SCNODE_ATOM_NODE;
7773
0
            } else if (set->val.scnodes[i].in_ctx == pred_in_ctx) {
7774
0
                set->val.scnodes[i].in_ctx = LYXP_SET_SCNODE_ATOM_CTX;
7775
0
            }
7776
0
        }
7777
7778
0
    } else {
7779
0
        set2.type = LYXP_SET_NODE_SET;
7780
0
        set_fill_set(&set2, set);
7781
7782
0
        rc = eval_expr_select(exp, tok_idx, 0, &set2, options);
7783
0
        if (rc) {
7784
0
            lyxp_set_free_content(&set2);
7785
0
            return rc;
7786
0
        }
7787
7788
0
        lyxp_set_cast(&set2, LYXP_SET_BOOLEAN);
7789
0
        if (!set2.val.bln) {
7790
0
            lyxp_set_free_content(set);
7791
0
        }
7792
0
        lyxp_set_free_content(&set2);
7793
0
    }
7794
7795
    /* ']' */
7796
0
    assert(exp->tokens[*tok_idx] == LYXP_TOKEN_BRACK2);
7797
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
7798
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
7799
0
    ++(*tok_idx);
7800
7801
0
    return LY_SUCCESS;
7802
0
}
7803
7804
/**
7805
 * @brief Evaluate Literal. Logs directly on error.
7806
 *
7807
 * @param[in] exp Parsed XPath expression.
7808
 * @param[in] tok_idx Position in the expression @p exp.
7809
 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7810
 */
7811
static void
7812
eval_literal(const struct lyxp_expr *exp, uint32_t *tok_idx, struct lyxp_set *set)
7813
0
{
7814
0
    if (set) {
7815
0
        if (exp->tok_len[*tok_idx] == 2) {
7816
0
            set_fill_string(set, "", 0);
7817
0
        } else {
7818
0
            set_fill_string(set, &exp->expr[exp->tok_pos[*tok_idx] + 1], exp->tok_len[*tok_idx] - 2);
7819
0
        }
7820
0
    }
7821
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7822
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
7823
0
    ++(*tok_idx);
7824
0
}
7825
7826
/**
7827
 * @brief Check that a nametest in a predicate matches a key node.
7828
 *
7829
 * @param[in] nametest Nametest to check.
7830
 * @param[in] len Length of @p nametest.
7831
 * @param[in] ctx_scnode Found schema node as the context for the predicate.
7832
 * @param[in] set Context set.
7833
 * @param[in] key Expected key node.
7834
 * @return LY_SUCCESS on success,
7835
 * @return LY_ENOT if a predicate could not be compiled.
7836
 * @return LY_ERR on any error.
7837
 */
7838
static LY_ERR
7839
eval_name_test_try_compile_predicate_key(const char *nametest, uint32_t len, const struct lysc_node *ctx_scnode,
7840
        const struct lyxp_set *set, const struct lysc_node *key)
7841
0
{
7842
0
    const struct lys_module *mod;
7843
7844
    /* prefix (module) */
7845
0
    LY_CHECK_RET(moveto_resolve_module(&nametest, &len, set, ctx_scnode, &mod));
7846
0
    if (mod && (mod != key->module)) {
7847
0
        return LY_ENOT;
7848
0
    }
7849
7850
    /* node name */
7851
0
    if (ly_strncmp(key->name, nametest, len)) {
7852
0
        return LY_ENOT;
7853
0
    }
7854
7855
0
    return LY_SUCCESS;
7856
0
}
7857
7858
/**
7859
 * @brief Append a simple predicate for the node.
7860
 *
7861
 * @param[in] exp Full parsed XPath expression.
7862
 * @param[in] tok_idx Predicate start index in @p exp.
7863
 * @param[in] end_tok_idx Predicate end index in @p exp.
7864
 * @param[in] ctx_scnode Found schema node as the context for the predicate.
7865
 * @param[in] set Context set.
7866
 * @param[in] pred_node Node with the value referenced in the predicate.
7867
 * @param[in,out] pred Predicate to append to.
7868
 * @param[in,out] pred_len Length of @p pred, is updated.
7869
 * @return LY_SUCCESS on success,
7870
 * @return LY_ENOT if a predicate could not be compiled.
7871
 * @return LY_ERR on any error.
7872
 */
7873
static LY_ERR
7874
eval_name_test_try_compile_predicate_append(const struct lyxp_expr *exp, uint32_t tok_idx, uint32_t end_tok_idx,
7875
        const struct lysc_node *ctx_scnode, const struct lyxp_set *set, const struct lysc_node *pred_node, char **pred,
7876
        uint32_t *pred_len)
7877
0
{
7878
0
    LY_ERR rc = LY_SUCCESS;
7879
0
    uint32_t i;
7880
0
    const struct lyd_node *siblings;
7881
0
    struct lyd_node *ctx_node;
7882
0
    const struct lysc_node *sparent, *cur_scnode;
7883
0
    struct lyxp_expr *val_exp = NULL;
7884
0
    struct lyxp_set set2 = {0};
7885
0
    char quot;
7886
7887
    /* duplicate the value expression */
7888
0
    LY_CHECK_GOTO(rc = lyxp_expr_dup(set->ctx, exp, tok_idx, end_tok_idx, &val_exp), cleanup);
7889
7890
    /* get its atoms */
7891
0
    cur_scnode = set->cur_node ? set->cur_node->schema : NULL;
7892
0
    LY_CHECK_GOTO(rc = lyxp_atomize(set->ctx, val_exp, set->cur_mod, set->format, set->prefix_data, cur_scnode,
7893
0
            ctx_scnode, &set2, LYXP_SCNODE), cleanup);
7894
7895
    /* check whether we can compile a single predicate (evaluation result value is always the same) */
7896
0
    for (i = 0; i < set2.used; ++i) {
7897
0
        if ((set2.val.scnodes[i].type != LYXP_NODE_ELEM) || (set2.val.scnodes[i].in_ctx < LYXP_SET_SCNODE_ATOM_NODE)) {
7898
            /* skip root and context node */
7899
0
            continue;
7900
0
        }
7901
7902
        /* 1) context node descendants are traversed - do best-effort detection of the value dependency on the
7903
         * context node instance */
7904
0
        if ((set2.val.scnodes[i].axis == LYXP_AXIS_CHILD) && (set2.val.scnodes[i].scnode->parent == ctx_scnode)) {
7905
            /* 1.1) context node child was accessed on the child axis, certain dependency */
7906
0
            rc = LY_ENOT;
7907
0
            goto cleanup;
7908
0
        }
7909
0
        if ((set2.val.scnodes[i].axis == LYXP_AXIS_DESCENDANT) || (set2.val.scnodes[i].axis == LYXP_AXIS_DESCENDANT_OR_SELF)) {
7910
0
            for (sparent = set2.val.scnodes[i].scnode->parent; sparent && (sparent != ctx_scnode); sparent = sparent->parent) {}
7911
0
            if (sparent) {
7912
                /* 1.2) context node descendant was accessed on the descendant axis, probable dependency */
7913
0
                rc = LY_ENOT;
7914
0
                goto cleanup;
7915
0
            }
7916
0
        }
7917
7918
        /* 2) multi-instance nodes (list or leaf-list) are traversed - all the instances need to be considered,
7919
         * but the current node can be safely ignored, it is always the same data instance */
7920
0
        if ((set2.val.scnodes[i].scnode->nodetype & (LYS_LIST | LYS_LEAFLIST)) && (cur_scnode != set2.val.scnodes[i].scnode)) {
7921
0
            rc = LY_ENOT;
7922
0
            goto cleanup;
7923
0
        }
7924
0
    }
7925
7926
    /* get any data instance of the context node, we checked it makes no difference */
7927
0
    siblings = set->val.nodes[0].node ? lyd_child_any(set->val.nodes[0].node) : set->tree;
7928
0
    LY_CHECK_GOTO(rc = lyd_find_sibling_schema(siblings, ctx_scnode, &ctx_node), cleanup);
7929
7930
    /* evaluate the value subexpression with the root context node */
7931
0
    lyxp_set_free_content(&set2);
7932
0
    LY_CHECK_GOTO(rc = lyxp_eval(set->ctx, val_exp, set->cur_mod, set->format, set->prefix_data, set->cur_node,
7933
0
            ctx_node, set->tree, NULL, &set2, 0), cleanup);
7934
7935
    /* cast it into a string */
7936
0
    LY_CHECK_GOTO(rc = lyxp_set_cast(&set2, LYXP_SET_STRING), cleanup);
7937
7938
    /* append the JSON predicate */
7939
0
    *pred = ly_realloc(*pred, *pred_len + 1 + strlen(pred_node->name) + 2 + strlen(set2.val.str) + 3);
7940
0
    LY_CHECK_ERR_GOTO(!*pred, LOGMEM(set->ctx); rc = LY_EMEM, cleanup);
7941
0
    LY_CHECK_GOTO(rc = ly_val_get_quot(set->ctx, set2.val.str, &quot), cleanup);
7942
0
    *pred_len += sprintf(*pred + *pred_len, "[%s=%c%s%c]", pred_node->name, quot, set2.val.str, quot);
7943
7944
0
cleanup:
7945
0
    lyxp_expr_free(val_exp);
7946
0
    lyxp_set_free_content(&set2);
7947
0
    return rc;
7948
0
}
7949
7950
/**
7951
 * @brief Try to compile list or leaf-list predicate in the known format to be used for hash-based instance search.
7952
 *
7953
 * @param[in] exp Full parsed XPath expression.
7954
 * @param[in,out] tok_idx Index in @p exp at the beginning of the predicate, is updated on success.
7955
 * @param[in] ctx_scnode Found schema node as the context for the predicate.
7956
 * @param[in] set Context set.
7957
 * @param[out] predicates Parsed predicates.
7958
 * @return LY_SUCCESS on success,
7959
 * @return LY_ENOT if a predicate could not be compiled.
7960
 * @return LY_ERR on any error.
7961
 */
7962
static LY_ERR
7963
eval_name_test_try_compile_predicates(const struct lyxp_expr *exp, uint32_t *tok_idx, const struct lysc_node *ctx_scnode,
7964
        const struct lyxp_set *set, struct ly_path_predicate **predicates)
7965
0
{
7966
0
    LY_ERR rc = LY_SUCCESS;
7967
0
    uint32_t e_idx, val_start_idx, pred_idx = 0, *prev_lo, temp_lo = 0, pred_len = 0, nested_pred;
7968
0
    const struct lysc_node *key;
7969
0
    char *pred = NULL;
7970
0
    struct lyxp_expr *exp2 = NULL;
7971
7972
0
    assert(ctx_scnode->nodetype & (LYS_LIST | LYS_LEAFLIST));
7973
7974
    /* turn logging off */
7975
0
    prev_lo = ly_temp_log_options(&temp_lo);
7976
7977
0
    if (ctx_scnode->nodetype == LYS_LIST) {
7978
        /* check for predicates "[key1=...][key2=...]..." */
7979
7980
        /* get key count */
7981
0
        if (ctx_scnode->flags & LYS_KEYLESS) {
7982
0
            rc = LY_ENOT;
7983
0
            goto cleanup;
7984
0
        }
7985
7986
        /* learn where the predicates end */
7987
0
        e_idx = *tok_idx;
7988
0
        for (key = lysc_node_child(ctx_scnode); key && (key->flags & LYS_KEY); key = key->next) {
7989
            /* '[' */
7990
0
            if (lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_BRACK1)) {
7991
0
                rc = LY_ENOT;
7992
0
                goto cleanup;
7993
0
            }
7994
0
            ++e_idx;
7995
7996
0
            if (lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_NAMETEST)) {
7997
                /* not a key */
7998
0
                rc = LY_ENOT;
7999
0
                goto cleanup;
8000
0
            }
8001
8002
            /* check key */
8003
0
            LY_CHECK_GOTO(rc = eval_name_test_try_compile_predicate_key(exp->expr + exp->tok_pos[e_idx],
8004
0
                    exp->tok_len[e_idx], ctx_scnode, set, key), cleanup);
8005
8006
0
            ++e_idx;
8007
8008
0
            if (lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_OPER_EQUAL)) {
8009
                /* not '=' */
8010
0
                rc = LY_ENOT;
8011
0
                goto cleanup;
8012
0
            }
8013
0
            ++e_idx;
8014
8015
            /* value start */
8016
0
            val_start_idx = e_idx;
8017
8018
            /* ']' */
8019
0
            nested_pred = 1;
8020
0
            do {
8021
0
                ++e_idx;
8022
8023
0
                if ((nested_pred == 1) && !lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_OPER_LOG)) {
8024
                    /* higher priority than '=' */
8025
0
                    rc = LY_ENOT;
8026
0
                    goto cleanup;
8027
0
                } else if (!lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_BRACK1)) {
8028
                    /* nested predicate */
8029
0
                    ++nested_pred;
8030
0
                } else if (!lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_BRACK2)) {
8031
                    /* predicate end */
8032
0
                    --nested_pred;
8033
0
                }
8034
0
            } while (nested_pred);
8035
8036
            /* try to evaluate the value */
8037
0
            LY_CHECK_GOTO(rc = eval_name_test_try_compile_predicate_append(exp, val_start_idx, e_idx - 1, ctx_scnode,
8038
0
                    set, key, &pred, &pred_len), cleanup);
8039
8040
0
            ++e_idx;
8041
0
        }
8042
0
    } else {
8043
        /* check for predicate "[.=...]" */
8044
8045
        /* learn just where this single predicate ends */
8046
0
        e_idx = *tok_idx;
8047
8048
        /* '[' */
8049
0
        if (lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_BRACK1)) {
8050
0
            rc = LY_ENOT;
8051
0
            goto cleanup;
8052
0
        }
8053
0
        ++e_idx;
8054
8055
0
        if (lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_DOT)) {
8056
            /* not the node value */
8057
0
            rc = LY_ENOT;
8058
0
            goto cleanup;
8059
0
        }
8060
0
        ++e_idx;
8061
8062
0
        if (lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_OPER_EQUAL)) {
8063
            /* not '=' */
8064
0
            rc = LY_ENOT;
8065
0
            goto cleanup;
8066
0
        }
8067
0
        ++e_idx;
8068
8069
        /* value start */
8070
0
        val_start_idx = e_idx;
8071
8072
        /* ']' */
8073
0
        nested_pred = 1;
8074
0
        do {
8075
0
            ++e_idx;
8076
8077
0
            if ((nested_pred == 1) && !lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_OPER_LOG)) {
8078
                /* higher priority than '=' */
8079
0
                rc = LY_ENOT;
8080
0
                goto cleanup;
8081
0
            } else if (!lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_BRACK1)) {
8082
                /* nested predicate */
8083
0
                ++nested_pred;
8084
0
            } else if (!lyxp_check_token(NULL, exp, e_idx, LYXP_TOKEN_BRACK2)) {
8085
                /* predicate end */
8086
0
                --nested_pred;
8087
0
            }
8088
0
        } while (nested_pred);
8089
8090
        /* try to evaluate the value */
8091
0
        LY_CHECK_GOTO(rc = eval_name_test_try_compile_predicate_append(exp, val_start_idx, e_idx - 1, ctx_scnode, set,
8092
0
                ctx_scnode, &pred, &pred_len), cleanup);
8093
8094
0
        ++e_idx;
8095
0
    }
8096
8097
    /* parse the predicate(s) */
8098
0
    LY_CHECK_GOTO(rc = ly_path_parse_predicate(set->ctx, ctx_scnode, pred, pred_len, LY_PATH_PREFIX_OPTIONAL,
8099
0
            LY_PATH_PRED_SIMPLE, &exp2), cleanup);
8100
8101
    /* compile */
8102
0
    rc = ly_path_compile_predicate(set->ctx, set->cur_node ? set->cur_node->schema : NULL, ctx_scnode, exp2, &pred_idx,
8103
0
            LY_VALUE_JSON, NULL, predicates);
8104
0
    LY_CHECK_GOTO(rc, cleanup);
8105
8106
    /* success, the predicate must include all the needed information for hash-based search */
8107
0
    *tok_idx = e_idx;
8108
8109
0
cleanup:
8110
0
    ly_temp_log_options(prev_lo);
8111
0
    lyxp_expr_free(exp2);
8112
0
    free(pred);
8113
0
    return rc;
8114
0
}
8115
8116
/**
8117
 * @brief Find a specific child schema node. ::lys_find_child() is not used to avoid searching in extension instances.
8118
 *
8119
 * No need to find ext instance data nodes using hashes and may cause some recursive callback calls (schema-mount).
8120
 *
8121
 * @param[in] parent Parent node, if any.
8122
 * @param[in] mod Node module.
8123
 * @param[in] name Name of the node.
8124
 * @param[in] name_len Length of @p name.
8125
 * @param[in] options Getnext options.
8126
 * @return Found schema node;
8127
 * @return NULL if no node found.
8128
 */
8129
static const struct lysc_node *
8130
eval_name_test_with_predicate_find_scnode(const struct lysc_node *parent, const struct lys_module *mod,
8131
        const char *name, uint32_t name_len, uint32_t options)
8132
0
{
8133
0
    const struct lysc_node *node = NULL;
8134
8135
0
    assert(mod && mod->implemented);
8136
8137
0
    while ((node = lys_getnext(node, parent, mod->compiled, options))) {
8138
        /* check module */
8139
0
        if (node->module != mod) {
8140
0
            continue;
8141
0
        }
8142
8143
        /* check name */
8144
0
        if (!ly_strncmp(node->name, name, name_len)) {
8145
0
            return node;
8146
0
        }
8147
0
    }
8148
8149
0
    return NULL;
8150
0
}
8151
8152
/**
8153
 * @brief Search for/check the next schema node that could be the only matching schema node meaning the
8154
 * data node(s) could be found using a single hash-based search.
8155
 *
8156
 * @param[in] ctx libyang context.
8157
 * @param[in] node Next context node to check.
8158
 * @param[in] name Expected node name.
8159
 * @param[in] name_len Length of @p name.
8160
 * @param[in] moveto_mod Expected node module, can be NULL for JSON format with no prefix.
8161
 * @param[in] root_type XPath root type.
8162
 * @param[in] format Prefix format.
8163
 * @param[in,out] found Previously found node, is updated.
8164
 * @return LY_SUCCESS on success,
8165
 * @return LY_ENOT if the whole check failed and hashes cannot be used.
8166
 */
8167
static LY_ERR
8168
eval_name_test_with_predicate_get_scnode(const struct ly_ctx *ctx, const struct lyd_node *node, const char *name,
8169
        uint32_t name_len, const struct lys_module *moveto_mod, enum lyxp_node_type root_type, LY_VALUE_FORMAT format,
8170
        const struct lysc_node **found)
8171
0
{
8172
0
    const struct lysc_node *scnode, *scnode2;
8173
0
    const struct lys_module *mod;
8174
0
    uint32_t idx = 0;
8175
8176
0
    assert((format == LY_VALUE_JSON) || moveto_mod);
8177
8178
0
continue_search:
8179
0
    scnode = NULL;
8180
0
    if (!node) {
8181
0
        if ((format == LY_VALUE_JSON) && !moveto_mod) {
8182
            /* search all modules for a single match */
8183
0
            while ((mod = ly_ctx_get_module_iter(ctx, &idx))) {
8184
0
                if (!mod->implemented) {
8185
0
                    continue;
8186
0
                }
8187
8188
0
                scnode = eval_name_test_with_predicate_find_scnode(NULL, mod, name, name_len, 0);
8189
0
                if (scnode) {
8190
                    /* we have found a match */
8191
0
                    break;
8192
0
                }
8193
0
            }
8194
8195
0
            if (!scnode) {
8196
                /* all modules searched */
8197
0
                idx = 0;
8198
0
            }
8199
0
        } else {
8200
            /* search in top-level */
8201
0
            scnode = eval_name_test_with_predicate_find_scnode(NULL, moveto_mod, name, name_len, 0);
8202
0
        }
8203
0
    } else if (node->schema && (!*found || (lysc_data_parent(*found) != node->schema))) {
8204
0
        if ((format == LY_VALUE_JSON) && !moveto_mod) {
8205
            /* we must adjust the module to inherit the one from the context node */
8206
0
            moveto_mod = node->schema->module;
8207
0
        }
8208
8209
        /* search in children, do not repeat the same search */
8210
0
        if (node->schema->nodetype & (LYS_RPC | LYS_ACTION)) {
8211
            /* make sure the node is unique, whether in input or output */
8212
0
            scnode = eval_name_test_with_predicate_find_scnode(node->schema, moveto_mod, name, name_len, 0);
8213
0
            scnode2 = eval_name_test_with_predicate_find_scnode(node->schema, moveto_mod, name, name_len,
8214
0
                    LYS_GETNEXT_OUTPUT);
8215
0
            if (scnode && scnode2) {
8216
                /* conflict, do not use hashes */
8217
0
                scnode = NULL;
8218
0
            } else if (scnode2) {
8219
0
                scnode = scnode2;
8220
0
            }
8221
0
        } else {
8222
0
            scnode = eval_name_test_with_predicate_find_scnode(node->schema, moveto_mod, name, name_len, 0);
8223
0
        }
8224
0
    } /* else skip redundant search */
8225
8226
    /* additional context check */
8227
0
    if (scnode && (root_type == LYXP_NODE_ROOT_CONFIG) && (scnode->flags & LYS_CONFIG_R)) {
8228
0
        scnode = NULL;
8229
0
    }
8230
8231
0
    if (scnode) {
8232
0
        if (*found) {
8233
            /* we found a schema node with the same name but at different level, give up, too complicated
8234
             * (more hash-based searches would be required, not supported) */
8235
0
            return LY_ENOT;
8236
0
        } else {
8237
            /* remember the found schema node and continue to make sure it can be used */
8238
0
            *found = scnode;
8239
0
        }
8240
0
    }
8241
8242
0
    if (idx) {
8243
        /* continue searching all the following modules */
8244
0
        goto continue_search;
8245
0
    }
8246
8247
0
    return LY_SUCCESS;
8248
0
}
8249
8250
/**
8251
 * @brief Generate message when no matching schema nodes were found for a path segment.
8252
 *
8253
 * @param[in] set XPath set.
8254
 * @param[in] scparent Previous schema parent in the context, if only one.
8255
 * @param[in] ncname XPath NCName being evaluated.
8256
 * @param[in] ncname_len Length of @p ncname.
8257
 * @param[in] expr Whole XPath expression.
8258
 * @param[in] options XPath options.
8259
 */
8260
static void
8261
eval_name_test_scnode_no_match_msg(struct lyxp_set *set, const struct lyxp_set_scnode *scparent, const char *ncname,
8262
        uint32_t ncname_len, const char *expr, uint32_t options)
8263
0
{
8264
0
    const char *format;
8265
0
    char *path = NULL, *ppath = NULL;
8266
8267
0
    path = lysc_path(set->cur_scnode, LYSC_PATH_LOG, NULL, 0);
8268
0
    if (scparent) {
8269
        /* generate path for the parent */
8270
0
        if (scparent->type == LYXP_NODE_ELEM) {
8271
0
            ppath = lysc_path(scparent->scnode, LYSC_PATH_LOG, NULL, 0);
8272
0
        } else if (scparent->type == LYXP_NODE_ROOT) {
8273
0
            ppath = strdup("<root>");
8274
0
        } else if (scparent->type == LYXP_NODE_ROOT_CONFIG) {
8275
0
            ppath = strdup("<config-root>");
8276
0
        }
8277
0
    }
8278
0
    if (ppath) {
8279
0
        format = "Schema node \"%.*s\" for parent \"%s\" not found; in expr \"%.*s\" with context node \"%s\".";
8280
0
        if (options & LYXP_SCNODE_ERROR) {
8281
0
            LOGERR(set->ctx, LY_ENOTFOUND, format, ncname_len, ncname, ppath, (ncname - expr) + ncname_len, expr, path);
8282
0
        } else {
8283
0
            LOGWRN(set->ctx, format, ncname_len, ncname, ppath, (ncname - expr) + ncname_len, expr, path);
8284
0
        }
8285
0
    } else {
8286
0
        format = "Schema node \"%.*s\" not found; in expr \"%.*s\" with context node \"%s\".";
8287
0
        if (options & LYXP_SCNODE_ERROR) {
8288
0
            LOGERR(set->ctx, LY_ENOTFOUND, format, ncname_len, ncname, (ncname - expr) + ncname_len, expr, path);
8289
0
        } else {
8290
0
            LOGWRN(set->ctx, format, ncname_len, ncname, (ncname - expr) + ncname_len, expr, path);
8291
0
        }
8292
0
    }
8293
0
    free(path);
8294
0
    free(ppath);
8295
0
}
8296
8297
/**
8298
 * @brief Evaluate NameTest and any following Predicates. Logs directly on error.
8299
 *
8300
 * [5] Step ::= '@'? NodeTest Predicate* | '.' | '..'
8301
 * [6] NodeTest ::= NameTest | NodeType '(' ')'
8302
 * [7] NameTest ::= '*' | NCName ':' '*' | QName
8303
 *
8304
 * @param[in] exp Parsed XPath expression.
8305
 * @param[in] tok_idx Position in the expression @p exp.
8306
 * @param[in] axis What axis to search on.
8307
 * @param[in] all_desc Whether to search all the descendants or children only.
8308
 * @param[in,out] set Context and result set.
8309
 * @param[in] options XPath options.
8310
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when, LY_ENOT for not found schema node)
8311
 */
8312
static LY_ERR
8313
eval_name_test_with_predicate(const struct lyxp_expr *exp, uint32_t *tok_idx, enum lyxp_axis axis, ly_bool all_desc,
8314
        struct lyxp_set *set, uint32_t options)
8315
0
{
8316
0
    LY_ERR rc = LY_SUCCESS, r;
8317
0
    const char *ncname = NULL;
8318
0
    uint32_t i, ncname_len;
8319
0
    const struct lys_module *moveto_mod = NULL, *moveto_m;
8320
0
    const struct lysc_node *scnode = NULL;
8321
0
    struct ly_path_predicate *predicates = NULL;
8322
0
    int scnode_skip_pred = 0;
8323
8324
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8325
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8326
0
    ++(*tok_idx);
8327
8328
0
    if (options & LYXP_SKIP_EXPR) {
8329
0
        goto moveto;
8330
0
    }
8331
8332
0
    ncname = &exp->expr[exp->tok_pos[*tok_idx - 1]];
8333
0
    ncname_len = exp->tok_len[*tok_idx - 1];
8334
8335
0
    if ((ncname[0] == '*') && (ncname_len == 1)) {
8336
        /* all nodes will match */
8337
0
        goto moveto;
8338
0
    }
8339
8340
    /* parse (and skip) module name */
8341
0
    rc = moveto_resolve_module(&ncname, &ncname_len, set, NULL, &moveto_mod);
8342
0
    LY_CHECK_GOTO(rc, cleanup);
8343
8344
0
    if ((ncname[0] == '*') && (ncname_len == 1)) {
8345
        /* all nodes from the module will match */
8346
0
        goto moveto;
8347
0
    }
8348
8349
0
    if (((set->format == LY_VALUE_JSON) || moveto_mod) && (axis == LYXP_AXIS_CHILD) && !all_desc &&
8350
0
            (set->type == LYXP_SET_NODE_SET)) {
8351
        /* find the matching schema node in some parent in the context */
8352
0
        for (i = 0; i < set->used; ++i) {
8353
0
            if (moveto_mod && (set->val.nodes[i].type == LYXP_NODE_ELEM) &&
8354
0
                    (moveto_mod->ctx != LYD_CTX(set->val.nodes[i].node))) {
8355
                /* extension data, use the correct module */
8356
0
                moveto_m = ly_ctx_get_module_implemented(LYD_CTX(set->val.nodes[i].node), moveto_mod->name);
8357
0
            } else {
8358
0
                moveto_m = moveto_mod;
8359
0
            }
8360
0
            if (eval_name_test_with_predicate_get_scnode(set->ctx, set->val.nodes[i].node, ncname, ncname_len,
8361
0
                    moveto_m, set->root_type, set->format, &scnode)) {
8362
                /* check failed */
8363
0
                scnode = NULL;
8364
0
                break;
8365
0
            }
8366
0
        }
8367
8368
0
        if (scnode && (scnode->nodetype & (LYS_LIST | LYS_LEAFLIST))) {
8369
            /* try to create the predicates */
8370
0
            if (eval_name_test_try_compile_predicates(exp, tok_idx, scnode, set, &predicates)) {
8371
                /* hashes cannot be used */
8372
0
                scnode = NULL;
8373
0
            }
8374
0
        }
8375
0
    }
8376
8377
0
moveto:
8378
0
    if (scnode || (ncname && (ncname[0] == '*') && (ncname_len == 1))) {
8379
        /* match based on scnode, not based on ncname */
8380
0
        ncname = NULL;
8381
0
        ncname_len = 0;
8382
0
    }
8383
8384
    /* move to the attribute(s), data node(s), or schema node(s) */
8385
0
    if (axis == LYXP_AXIS_ATTRIBUTE) {
8386
0
        if (!(options & LYXP_SKIP_EXPR) && (options & LYXP_SCNODE_ALL)) {
8387
0
            set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
8388
0
        } else {
8389
0
            if (all_desc) {
8390
0
                rc = moveto_attr_alldesc(set, moveto_mod, ncname, ncname_len, options);
8391
0
            } else {
8392
0
                rc = moveto_attr(set, moveto_mod, ncname, ncname_len, options);
8393
0
            }
8394
0
            LY_CHECK_GOTO(rc, cleanup);
8395
0
        }
8396
0
    } else {
8397
0
        if (!(options & LYXP_SKIP_EXPR) && (options & LYXP_SCNODE_ALL)) {
8398
0
            const struct lyxp_set_scnode *scparent = NULL;
8399
0
            ly_bool found = 0;
8400
8401
            /* remember parent if there is only one, to print in the warning */
8402
0
            for (i = 0; i < set->used; ++i) {
8403
0
                if (set->val.scnodes[i].in_ctx == LYXP_SET_SCNODE_ATOM_CTX) {
8404
0
                    if (!scparent) {
8405
                        /* remember the context node */
8406
0
                        scparent = &set->val.scnodes[i];
8407
0
                    } else {
8408
                        /* several context nodes, no reasonable error possible */
8409
0
                        scparent = NULL;
8410
0
                        break;
8411
0
                    }
8412
0
                }
8413
0
            }
8414
8415
0
            if (all_desc && (axis == LYXP_AXIS_CHILD)) {
8416
                /* efficient evaluation that does not add all the descendants into the set */
8417
0
                rc = moveto_scnode_alldesc_child(set, moveto_mod, ncname, ncname_len, options);
8418
0
            } else {
8419
0
                if (all_desc) {
8420
                    /* "//" == "/descendant-or-self::node()/" */
8421
0
                    rc = xpath_pi_node(set, LYXP_AXIS_DESCENDANT_OR_SELF, options);
8422
0
                    LY_CHECK_GOTO(rc, cleanup);
8423
0
                }
8424
0
                rc = moveto_scnode(set, moveto_mod, ncname, ncname_len, axis, options);
8425
0
            }
8426
0
            LY_CHECK_GOTO(rc, cleanup);
8427
8428
0
            if (set->used) {
8429
0
                i = set->used;
8430
0
                assert(i);
8431
0
                do {
8432
0
                    --i;
8433
0
                    if (set->val.scnodes[i].in_ctx > LYXP_SET_SCNODE_ATOM_NODE) {
8434
0
                        found = 1;
8435
0
                        break;
8436
0
                    }
8437
0
                } while (i);
8438
0
            }
8439
0
            if (!found) {
8440
                /* generate message */
8441
0
                eval_name_test_scnode_no_match_msg(set, scparent, ncname, ncname_len, exp->expr, options);
8442
8443
0
                if (options & LYXP_SCNODE_ERROR) {
8444
                    /* error */
8445
0
                    set->not_found = 1;
8446
0
                }
8447
8448
                /* skip the predicates and the rest of this path to not generate invalid warnings */
8449
0
                rc = LY_ENOT;
8450
0
                scnode_skip_pred = 1;
8451
0
            }
8452
0
        } else {
8453
0
            if (all_desc && (axis == LYXP_AXIS_CHILD)) {
8454
                /* efficient evaluation */
8455
0
                rc = moveto_node_alldesc_child(set, moveto_mod, ncname, ncname_len, options);
8456
0
            } else if (scnode && (axis == LYXP_AXIS_CHILD)) {
8457
                /* we can find the child nodes using hashes */
8458
0
                rc = moveto_node_hash_child(set, scnode, predicates, options);
8459
0
            } else {
8460
0
                if (all_desc) {
8461
                    /* "//" == "/descendant-or-self::node()/" */
8462
0
                    rc = xpath_pi_node(set, LYXP_AXIS_DESCENDANT_OR_SELF, options);
8463
0
                    LY_CHECK_GOTO(rc, cleanup);
8464
0
                }
8465
0
                rc = moveto_node(set, moveto_mod, ncname, ncname_len, axis, options);
8466
0
            }
8467
0
            LY_CHECK_GOTO(rc, cleanup);
8468
0
        }
8469
0
    }
8470
8471
0
    if (scnode_skip_pred) {
8472
        /* skip predicates */
8473
0
        options |= LYXP_SKIP_EXPR;
8474
0
    }
8475
8476
    /* Predicate* */
8477
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_BRACK1)) {
8478
0
        r = eval_predicate(exp, tok_idx, set, options, axis);
8479
0
        LY_CHECK_ERR_GOTO(r, rc = r, cleanup);
8480
0
    }
8481
8482
0
cleanup:
8483
0
    if (scnode_skip_pred) {
8484
        /* restore options */
8485
0
        options &= ~LYXP_SKIP_EXPR;
8486
0
    }
8487
0
    if (predicates) {
8488
0
        ly_path_predicates_free(scnode->module->ctx, predicates);
8489
0
    }
8490
0
    return rc;
8491
0
}
8492
8493
/**
8494
 * @brief Evaluate NodeType and any following Predicates. Logs directly on error.
8495
 *
8496
 * [5] Step ::= '@'? NodeTest Predicate* | '.' | '..'
8497
 * [6] NodeTest ::= NameTest | NodeType '(' ')'
8498
 * [8] NodeType ::= 'text' | 'node'
8499
 *
8500
 * @param[in] exp Parsed XPath expression.
8501
 * @param[in] tok_idx Position in the expression @p exp.
8502
 * @param[in] axis Axis to search on.
8503
 * @param[in] all_desc Whether to search all the descendants or axis only.
8504
 * @param[in,out] set Context and result set.
8505
 * @param[in] options XPath options.
8506
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
8507
 */
8508
static LY_ERR
8509
eval_node_type_with_predicate(const struct lyxp_expr *exp, uint32_t *tok_idx, enum lyxp_axis axis, ly_bool all_desc,
8510
        struct lyxp_set *set, uint32_t options)
8511
0
{
8512
0
    LY_ERR rc;
8513
8514
0
    (void)all_desc;
8515
8516
0
    if (!(options & LYXP_SKIP_EXPR)) {
8517
0
        assert(exp->tok_len[*tok_idx] == 4);
8518
0
        if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "node", 4)) {
8519
0
            rc = xpath_pi_node(set, axis, options);
8520
0
        } else {
8521
0
            assert(!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "text", 4));
8522
0
            rc = xpath_pi_text(set, axis, options);
8523
0
        }
8524
0
        LY_CHECK_RET(rc);
8525
0
    }
8526
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8527
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8528
0
    ++(*tok_idx);
8529
8530
    /* '(' */
8531
0
    assert(exp->tokens[*tok_idx] == LYXP_TOKEN_PAR1);
8532
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8533
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8534
0
    ++(*tok_idx);
8535
8536
    /* ')' */
8537
0
    assert(exp->tokens[*tok_idx] == LYXP_TOKEN_PAR2);
8538
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8539
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8540
0
    ++(*tok_idx);
8541
8542
    /* Predicate* */
8543
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_BRACK1)) {
8544
0
        rc = eval_predicate(exp, tok_idx, set, options, axis);
8545
0
        LY_CHECK_RET(rc);
8546
0
    }
8547
8548
0
    return LY_SUCCESS;
8549
0
}
8550
8551
/**
8552
 * @brief Evaluate RelativeLocationPath. Logs directly on error.
8553
 *
8554
 * [4] RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step
8555
 * [5] Step ::= '@'? NodeTest Predicate* | '.' | '..'
8556
 * [6] NodeTest ::= NameTest | NodeType '(' ')'
8557
 *
8558
 * @param[in] exp Parsed XPath expression.
8559
 * @param[in] tok_idx Position in the expression @p exp.
8560
 * @param[in] all_desc Whether to search all the descendants or children only.
8561
 * @param[in,out] set Context and result set.
8562
 * @param[in] options XPath options.
8563
 * @return LY_ERR (YL_EINCOMPLETE on unresolved when)
8564
 */
8565
static LY_ERR
8566
eval_relative_location_path(const struct lyxp_expr *exp, uint32_t *tok_idx, ly_bool all_desc, struct lyxp_set *set,
8567
        uint32_t options)
8568
0
{
8569
0
    LY_ERR rc = LY_SUCCESS;
8570
0
    enum lyxp_axis axis;
8571
0
    int scnode_skip_path = 0;
8572
8573
0
    goto step;
8574
0
    do {
8575
        /* evaluate '/' or '//' */
8576
0
        if (exp->tok_len[*tok_idx] == 1) {
8577
0
            all_desc = 0;
8578
0
        } else {
8579
0
            assert(exp->tok_len[*tok_idx] == 2);
8580
0
            all_desc = 1;
8581
0
        }
8582
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8583
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8584
0
        ++(*tok_idx);
8585
8586
0
step:
8587
        /* AxisSpecifier */
8588
0
        if (exp->tokens[*tok_idx] == LYXP_TOKEN_AXISNAME) {
8589
0
            axis = str2axis(exp->expr + exp->tok_pos[*tok_idx], exp->tok_len[*tok_idx]);
8590
8591
0
            LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8592
0
                    lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8593
0
            ++(*tok_idx);
8594
8595
0
            assert(exp->tokens[*tok_idx] == LYXP_TOKEN_DCOLON);
8596
0
            LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8597
0
                    lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8598
0
            ++(*tok_idx);
8599
0
        } else if (exp->tokens[*tok_idx] == LYXP_TOKEN_AT) {
8600
0
            axis = LYXP_AXIS_ATTRIBUTE;
8601
8602
0
            LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8603
0
                    lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8604
0
            ++(*tok_idx);
8605
0
        } else {
8606
            /* default */
8607
0
            axis = LYXP_AXIS_CHILD;
8608
0
        }
8609
8610
        /* NodeTest Predicate* */
8611
0
        switch (exp->tokens[*tok_idx]) {
8612
0
        case LYXP_TOKEN_DOT:
8613
            /* evaluate '.' */
8614
0
            if (!(options & LYXP_SKIP_EXPR)) {
8615
0
                if (((options & LYXP_SCNODE_ALL) && (set->type != LYXP_SET_SCNODE_SET)) ||
8616
0
                        (!(options & LYXP_SCNODE_ALL) && (set->type != LYXP_SET_NODE_SET))) {
8617
0
                    LOGVAL_XPATH(set, options, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
8618
0
                    rc = LY_EVALID;
8619
0
                    goto cleanup;
8620
0
                }
8621
8622
0
                if (all_desc) {
8623
0
                    rc = xpath_pi_node(set, LYXP_AXIS_DESCENDANT_OR_SELF, options);
8624
0
                    LY_CHECK_GOTO(rc, cleanup);
8625
0
                }
8626
0
                rc = xpath_pi_node(set, LYXP_AXIS_SELF, options);
8627
0
                LY_CHECK_GOTO(rc, cleanup);
8628
0
            }
8629
0
            LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
8630
0
                    lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8631
0
            ++(*tok_idx);
8632
0
            break;
8633
8634
0
        case LYXP_TOKEN_DDOT:
8635
            /* evaluate '..' */
8636
0
            if (!(options & LYXP_SKIP_EXPR)) {
8637
0
                if (((options & LYXP_SCNODE_ALL) && (set->type != LYXP_SET_SCNODE_SET)) ||
8638
0
                        (!(options & LYXP_SCNODE_ALL) && (set->type != LYXP_SET_NODE_SET))) {
8639
0
                    LOGVAL_XPATH(set, options, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
8640
0
                    rc = LY_EVALID;
8641
0
                    goto cleanup;
8642
0
                }
8643
8644
0
                if (all_desc) {
8645
0
                    rc = xpath_pi_node(set, LYXP_AXIS_DESCENDANT_OR_SELF, options);
8646
0
                    LY_CHECK_GOTO(rc, cleanup);
8647
0
                }
8648
0
                rc = xpath_pi_node(set, LYXP_AXIS_PARENT, options);
8649
0
                LY_CHECK_GOTO(rc, cleanup);
8650
0
            }
8651
0
            LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8652
0
                    lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8653
0
            ++(*tok_idx);
8654
0
            break;
8655
8656
0
        case LYXP_TOKEN_NAMETEST:
8657
            /* evaluate NameTest Predicate* */
8658
0
            rc = eval_name_test_with_predicate(exp, tok_idx, axis, all_desc, set, options);
8659
0
            if (rc == LY_ENOT) {
8660
0
                assert(options & LYXP_SCNODE_ALL);
8661
0
                rc = LY_SUCCESS;
8662
8663
                /* skip the rest of this path */
8664
0
                scnode_skip_path = 1;
8665
0
                options |= LYXP_SKIP_EXPR;
8666
0
            }
8667
0
            LY_CHECK_GOTO(rc, cleanup);
8668
0
            break;
8669
8670
0
        case LYXP_TOKEN_NODETYPE:
8671
            /* evaluate NodeType Predicate* */
8672
0
            rc = eval_node_type_with_predicate(exp, tok_idx, axis, all_desc, set, options);
8673
0
            LY_CHECK_GOTO(rc, cleanup);
8674
0
            break;
8675
8676
0
        default:
8677
0
            LOGINT(set->ctx);
8678
0
            rc = LY_EINT;
8679
0
            goto cleanup;
8680
0
        }
8681
0
    } while (!exp_check_token2(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_PATH, LYXP_TOKEN_OPER_RPATH));
8682
8683
0
cleanup:
8684
0
    if (scnode_skip_path) {
8685
0
        options &= ~LYXP_SKIP_EXPR;
8686
0
    }
8687
0
    return rc;
8688
0
}
8689
8690
/**
8691
 * @brief Evaluate AbsoluteLocationPath. Logs directly on error.
8692
 *
8693
 * [3] AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath
8694
 *
8695
 * @param[in] exp Parsed XPath expression.
8696
 * @param[in] tok_idx Position in the expression @p exp.
8697
 * @param[in,out] set Context and result set.
8698
 * @param[in] options XPath options.
8699
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
8700
 */
8701
static LY_ERR
8702
eval_absolute_location_path(const struct lyxp_expr *exp, uint32_t *tok_idx, struct lyxp_set *set, uint32_t options)
8703
0
{
8704
0
    ly_bool all_desc;
8705
8706
0
    if (!(options & LYXP_SKIP_EXPR)) {
8707
        /* no matter what tokens follow, we need to be at the root */
8708
0
        LY_CHECK_RET(moveto_root(set, options));
8709
0
    }
8710
8711
    /* '/' RelativeLocationPath? */
8712
0
    if (exp->tok_len[*tok_idx] == 1) {
8713
        /* evaluate '/' - deferred */
8714
0
        all_desc = 0;
8715
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8716
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8717
0
        ++(*tok_idx);
8718
8719
0
        if (lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_NONE)) {
8720
0
            return LY_SUCCESS;
8721
0
        }
8722
0
        switch (exp->tokens[*tok_idx]) {
8723
0
        case LYXP_TOKEN_DOT:
8724
0
        case LYXP_TOKEN_DDOT:
8725
0
        case LYXP_TOKEN_AXISNAME:
8726
0
        case LYXP_TOKEN_AT:
8727
0
        case LYXP_TOKEN_NAMETEST:
8728
0
        case LYXP_TOKEN_NODETYPE:
8729
0
            LY_CHECK_RET(eval_relative_location_path(exp, tok_idx, all_desc, set, options));
8730
0
            break;
8731
0
        default:
8732
0
            break;
8733
0
        }
8734
8735
0
    } else {
8736
        /* '//' RelativeLocationPath */
8737
        /* evaluate '//' - deferred so as not to waste memory by remembering all the nodes */
8738
0
        all_desc = 1;
8739
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8740
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8741
0
        ++(*tok_idx);
8742
8743
0
        LY_CHECK_RET(eval_relative_location_path(exp, tok_idx, all_desc, set, options));
8744
0
    }
8745
8746
0
    return LY_SUCCESS;
8747
0
}
8748
8749
/**
8750
 * @brief Evaluate FunctionCall. Logs directly on error.
8751
 *
8752
 * [11] FunctionCall ::= FunctionName '(' ( Expr ( ',' Expr )* )? ')'
8753
 *
8754
 * @param[in] exp Parsed XPath expression.
8755
 * @param[in] tok_idx Position in the expression @p exp.
8756
 * @param[in,out] set Context and result set.
8757
 * @param[in] options XPath options.
8758
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
8759
 */
8760
static LY_ERR
8761
eval_function_call(const struct lyxp_expr *exp, uint32_t *tok_idx, struct lyxp_set *set, uint32_t options)
8762
0
{
8763
0
    LY_ERR rc;
8764
8765
0
    LY_ERR (*xpath_func)(struct lyxp_set **, uint32_t, struct lyxp_set *, uint32_t) = NULL;
8766
0
    uint32_t arg_count = 0, i;
8767
0
    struct lyxp_set **args = NULL, **args_aux;
8768
8769
0
    if (!(options & LYXP_SKIP_EXPR)) {
8770
        /* FunctionName */
8771
0
        switch (exp->tok_len[*tok_idx]) {
8772
0
        case 3:
8773
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "not", 3)) {
8774
0
                xpath_func = &xpath_not;
8775
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "sum", 3)) {
8776
0
                xpath_func = &xpath_sum;
8777
0
            }
8778
0
            break;
8779
0
        case 4:
8780
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "lang", 4)) {
8781
0
                xpath_func = &xpath_lang;
8782
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "last", 4)) {
8783
0
                xpath_func = &xpath_last;
8784
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "name", 4)) {
8785
0
                xpath_func = &xpath_name;
8786
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "true", 4)) {
8787
0
                xpath_func = &xpath_true;
8788
0
            }
8789
0
            break;
8790
0
        case 5:
8791
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "count", 5)) {
8792
0
                xpath_func = &xpath_count;
8793
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "false", 5)) {
8794
0
                xpath_func = &xpath_false;
8795
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "floor", 5)) {
8796
0
                xpath_func = &xpath_floor;
8797
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "round", 5)) {
8798
0
                xpath_func = &xpath_round;
8799
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "deref", 5)) {
8800
0
                xpath_func = &xpath_deref;
8801
0
            }
8802
0
            break;
8803
0
        case 6:
8804
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "concat", 6)) {
8805
0
                xpath_func = &xpath_concat;
8806
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "number", 6)) {
8807
0
                xpath_func = &xpath_number;
8808
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "string", 6)) {
8809
0
                xpath_func = &xpath_string;
8810
0
            }
8811
0
            break;
8812
0
        case 7:
8813
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "boolean", 7)) {
8814
0
                xpath_func = &xpath_boolean;
8815
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "ceiling", 7)) {
8816
0
                xpath_func = &xpath_ceiling;
8817
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "current", 7)) {
8818
0
                xpath_func = &xpath_current;
8819
0
            }
8820
0
            break;
8821
0
        case 8:
8822
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "contains", 8)) {
8823
0
                xpath_func = &xpath_contains;
8824
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "position", 8)) {
8825
0
                xpath_func = &xpath_position;
8826
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "re-match", 8)) {
8827
0
                xpath_func = &xpath_re_match;
8828
0
            }
8829
0
            break;
8830
0
        case 9:
8831
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "substring", 9)) {
8832
0
                xpath_func = &xpath_substring;
8833
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "translate", 9)) {
8834
0
                xpath_func = &xpath_translate;
8835
0
            }
8836
0
            break;
8837
0
        case 10:
8838
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "local-name", 10)) {
8839
0
                xpath_func = &xpath_local_name;
8840
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "enum-value", 10)) {
8841
0
                xpath_func = &xpath_enum_value;
8842
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "bit-is-set", 10)) {
8843
0
                xpath_func = &xpath_bit_is_set;
8844
0
            }
8845
0
            break;
8846
0
        case 11:
8847
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "starts-with", 11)) {
8848
0
                xpath_func = &xpath_starts_with;
8849
0
            }
8850
0
            break;
8851
0
        case 12:
8852
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "derived-from", 12)) {
8853
0
                xpath_func = &xpath_derived_from;
8854
0
            }
8855
0
            break;
8856
0
        case 13:
8857
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "namespace-uri", 13)) {
8858
0
                xpath_func = &xpath_namespace_uri;
8859
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "string-length", 13)) {
8860
0
                xpath_func = &xpath_string_length;
8861
0
            }
8862
0
            break;
8863
0
        case 15:
8864
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "normalize-space", 15)) {
8865
0
                xpath_func = &xpath_normalize_space;
8866
0
            } else if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "substring-after", 15)) {
8867
0
                xpath_func = &xpath_substring_after;
8868
0
            }
8869
0
            break;
8870
0
        case 16:
8871
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "substring-before", 16)) {
8872
0
                xpath_func = &xpath_substring_before;
8873
0
            }
8874
0
            break;
8875
0
        case 20:
8876
0
            if (!strncmp(&exp->expr[exp->tok_pos[*tok_idx]], "derived-from-or-self", 20)) {
8877
0
                xpath_func = &xpath_derived_from_or_self;
8878
0
            }
8879
0
            break;
8880
0
        }
8881
8882
0
        if (!xpath_func) {
8883
0
            LOGVAL_XPATH(set, options, LY_VCODE_XP_INFUNC, (int)exp->tok_len[*tok_idx], &exp->expr[exp->tok_pos[*tok_idx]]);
8884
0
            return LY_EVALID;
8885
0
        }
8886
0
    }
8887
8888
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8889
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8890
0
    ++(*tok_idx);
8891
8892
    /* '(' */
8893
0
    assert(exp->tokens[*tok_idx] == LYXP_TOKEN_PAR1);
8894
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8895
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8896
0
    ++(*tok_idx);
8897
8898
    /* ( Expr ( ',' Expr )* )? */
8899
0
    if (exp->tokens[*tok_idx] != LYXP_TOKEN_PAR2) {
8900
0
        if (!(options & LYXP_SKIP_EXPR)) {
8901
0
            args = malloc(sizeof *args);
8902
0
            LY_CHECK_ERR_GOTO(!args, LOGMEM(set->ctx); rc = LY_EMEM, cleanup);
8903
0
            arg_count = 1;
8904
0
            args[0] = set_copy(set);
8905
0
            if (!args[0]) {
8906
0
                rc = LY_EMEM;
8907
0
                goto cleanup;
8908
0
            }
8909
8910
0
            rc = eval_expr_select(exp, tok_idx, 0, args[0], options);
8911
0
            LY_CHECK_GOTO(rc, cleanup);
8912
0
            set->not_found = args[0]->not_found;
8913
0
        } else {
8914
0
            rc = eval_expr_select(exp, tok_idx, 0, set, options);
8915
0
            LY_CHECK_GOTO(rc, cleanup);
8916
0
        }
8917
0
    }
8918
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_COMMA)) {
8919
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8920
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8921
0
        ++(*tok_idx);
8922
8923
0
        if (!(options & LYXP_SKIP_EXPR)) {
8924
0
            ++arg_count;
8925
0
            args_aux = realloc(args, arg_count * sizeof *args);
8926
0
            LY_CHECK_ERR_GOTO(!args_aux, arg_count--; LOGMEM(set->ctx); rc = LY_EMEM, cleanup);
8927
0
            args = args_aux;
8928
0
            args[arg_count - 1] = set_copy(set);
8929
0
            if (!args[arg_count - 1]) {
8930
0
                rc = LY_EMEM;
8931
0
                goto cleanup;
8932
0
            }
8933
8934
0
            rc = eval_expr_select(exp, tok_idx, 0, args[arg_count - 1], options);
8935
0
            LY_CHECK_GOTO(rc, cleanup);
8936
0
            if (args[arg_count - 1]->not_found) {
8937
0
                set->not_found = 1;
8938
0
            }
8939
0
        } else {
8940
0
            rc = eval_expr_select(exp, tok_idx, 0, set, options);
8941
0
            LY_CHECK_GOTO(rc, cleanup);
8942
0
        }
8943
0
    }
8944
8945
    /* ')' */
8946
0
    assert(exp->tokens[*tok_idx] == LYXP_TOKEN_PAR2);
8947
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
8948
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
8949
0
    ++(*tok_idx);
8950
8951
0
    if (!(options & LYXP_SKIP_EXPR)) {
8952
        /* evaluate function */
8953
0
        rc = xpath_func(args, arg_count, set, options);
8954
8955
0
        if (options & LYXP_SCNODE_ALL) {
8956
            /* merge all nodes from arg evaluations */
8957
0
            for (i = 0; i < arg_count; ++i) {
8958
0
                set_scnode_clear_ctx(args[i], LYXP_SET_SCNODE_ATOM_NODE);
8959
0
                lyxp_set_scnode_merge(set, args[i]);
8960
0
            }
8961
0
        }
8962
0
    } else {
8963
0
        rc = LY_SUCCESS;
8964
0
    }
8965
8966
0
cleanup:
8967
0
    for (i = 0; i < arg_count; ++i) {
8968
0
        lyxp_set_free(args[i]);
8969
0
    }
8970
0
    free(args);
8971
0
    return rc;
8972
0
}
8973
8974
/**
8975
 * @brief Evaluate Number. Logs directly on error.
8976
 *
8977
 * @param[in] exp Parsed XPath expression.
8978
 * @param[in] tok_idx Position in the expression @p exp.
8979
 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8980
 * @param[in] options XPath options.
8981
 * @return LY_ERR
8982
 */
8983
static LY_ERR
8984
eval_number(const struct lyxp_expr *exp, uint32_t *tok_idx, struct lyxp_set *set, uint32_t options)
8985
0
{
8986
0
    long double num;
8987
0
    char *endptr;
8988
8989
0
    if (!(options & LYXP_SKIP_EXPR)) {
8990
0
        errno = 0;
8991
0
        num = strtold(&exp->expr[exp->tok_pos[*tok_idx]], &endptr);
8992
0
        if (errno) {
8993
0
            LOGVAL_XPATH(set, options, LY_VCODE_XP_INTOK, "Unknown", &exp->expr[exp->tok_pos[*tok_idx]]);
8994
0
            LOGVAL_XPATH(set, options, LYVE_XPATH, "Failed to convert \"%.*s\" into a long double (%s).",
8995
0
                    (int)exp->tok_len[*tok_idx], &exp->expr[exp->tok_pos[*tok_idx]], strerror(errno));
8996
0
            return LY_EVALID;
8997
0
        } else if ((uint32_t)(endptr - &exp->expr[exp->tok_pos[*tok_idx]]) != exp->tok_len[*tok_idx]) {
8998
0
            LOGVAL_XPATH(set, options, LY_VCODE_XP_INTOK, "Unknown", &exp->expr[exp->tok_pos[*tok_idx]]);
8999
0
            LOGVAL_XPATH(set, options, LYVE_XPATH, "Failed to convert \"%.*s\" into a long double.",
9000
0
                    (int)exp->tok_len[*tok_idx], &exp->expr[exp->tok_pos[*tok_idx]]);
9001
0
            return LY_EVALID;
9002
0
        }
9003
9004
0
        set_fill_number(set, num);
9005
0
    }
9006
9007
0
    LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
9008
0
            lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9009
0
    ++(*tok_idx);
9010
0
    return LY_SUCCESS;
9011
0
}
9012
9013
LY_ERR
9014
lyxp_vars_find(const struct ly_ctx *ctx, const struct lyxp_var *vars, const char *name, size_t name_len,
9015
        struct lyxp_var **var)
9016
0
{
9017
0
    LY_ARRAY_COUNT_TYPE u;
9018
9019
0
    assert(name);
9020
9021
0
    if (!name_len) {
9022
0
        name_len = strlen(name);
9023
0
    }
9024
9025
0
    LY_ARRAY_FOR(vars, u) {
9026
0
        if (!strncmp(vars[u].name, name, name_len)) {
9027
0
            if (var) {
9028
0
                *var = (struct lyxp_var *)&vars[u];
9029
0
            }
9030
0
            return LY_SUCCESS;
9031
0
        }
9032
0
    }
9033
9034
0
    if (ctx) {
9035
0
        LOGERR(ctx, LY_ENOTFOUND, "Variable \"%.*s\" not defined.", (int)name_len, name);
9036
0
    }
9037
0
    return LY_ENOTFOUND;
9038
0
}
9039
9040
/**
9041
 * @brief Evaluate VariableReference.
9042
 *
9043
 * @param[in] exp Parsed XPath expression.
9044
 * @param[in] tok_idx Position in the expression @p exp.
9045
 * @param[in] vars [Sized array](@ref sizedarrays) of XPath variables.
9046
 * @param[in,out] set Context and result set.
9047
 * @param[in] options XPath options.
9048
 * @return LY_ERR value.
9049
 */
9050
static LY_ERR
9051
eval_variable_reference(const struct lyxp_expr *exp, uint32_t *tok_idx, struct lyxp_set *set, uint32_t options)
9052
0
{
9053
0
    LY_ERR ret;
9054
0
    const char *name;
9055
0
    struct lyxp_var *var;
9056
0
    struct lyxp_expr *tokens = NULL;
9057
0
    uint32_t token_index, name_len;
9058
9059
    /* find out the name and value of the variable */
9060
0
    name = &exp->expr[exp->tok_pos[*tok_idx]];
9061
0
    name_len = exp->tok_len[*tok_idx];
9062
0
    ret = lyxp_vars_find(set->ctx, set->vars, name, name_len, &var);
9063
0
    LY_CHECK_RET(ret);
9064
9065
    /* parse value */
9066
0
    ret = lyxp_expr_parse(set->ctx, !(options & LYXP_SCNODE_ALL) ? set->cur_node : NULL, var->value, 0, 1, &tokens);
9067
0
    LY_CHECK_GOTO(ret, cleanup);
9068
9069
    /* evaluate value */
9070
0
    token_index = 0;
9071
0
    ret = eval_expr_select(tokens, &token_index, 0, set, options);
9072
0
    LY_CHECK_GOTO(ret, cleanup);
9073
9074
0
cleanup:
9075
0
    lyxp_expr_free(tokens);
9076
9077
0
    return ret;
9078
0
}
9079
9080
/**
9081
 * @brief Evaluate PathExpr. Logs directly on error.
9082
 *
9083
 * [12] PathExpr ::= LocationPath | PrimaryExpr Predicate*
9084
 *                 | PrimaryExpr Predicate* '/' RelativeLocationPath
9085
 *                 | PrimaryExpr Predicate* '//' RelativeLocationPath
9086
 * [2] LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
9087
 * [10] PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall
9088
 *
9089
 * @param[in] exp Parsed XPath expression.
9090
 * @param[in] tok_idx Position in the expression @p exp.
9091
 * @param[in,out] set Context and result set.
9092
 * @param[in] options XPath options.
9093
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9094
 */
9095
static LY_ERR
9096
eval_path_expr(const struct lyxp_expr *exp, uint32_t *tok_idx, struct lyxp_set *set, uint32_t options)
9097
0
{
9098
0
    ly_bool all_desc;
9099
0
    LY_ERR rc;
9100
9101
0
    switch (exp->tokens[*tok_idx]) {
9102
0
    case LYXP_TOKEN_PAR1:
9103
        /* '(' Expr ')' */
9104
9105
        /* '(' */
9106
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
9107
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9108
0
        ++(*tok_idx);
9109
9110
        /* Expr */
9111
0
        rc = eval_expr_select(exp, tok_idx, 0, set, options);
9112
0
        LY_CHECK_RET(rc);
9113
9114
        /* ')' */
9115
0
        assert(exp->tokens[*tok_idx] == LYXP_TOKEN_PAR2);
9116
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
9117
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9118
0
        ++(*tok_idx);
9119
9120
0
        goto predicate;
9121
9122
0
    case LYXP_TOKEN_DOT:
9123
0
    case LYXP_TOKEN_DDOT:
9124
0
    case LYXP_TOKEN_AXISNAME:
9125
0
    case LYXP_TOKEN_AT:
9126
0
    case LYXP_TOKEN_NAMETEST:
9127
0
    case LYXP_TOKEN_NODETYPE:
9128
        /* RelativeLocationPath */
9129
0
        rc = eval_relative_location_path(exp, tok_idx, 0, set, options);
9130
0
        LY_CHECK_RET(rc);
9131
0
        break;
9132
9133
0
    case LYXP_TOKEN_VARREF:
9134
        /* VariableReference */
9135
0
        rc = eval_variable_reference(exp, tok_idx, set, options);
9136
0
        LY_CHECK_RET(rc);
9137
0
        ++(*tok_idx);
9138
9139
0
        goto predicate;
9140
9141
0
    case LYXP_TOKEN_FUNCNAME:
9142
        /* FunctionCall */
9143
0
        rc = eval_function_call(exp, tok_idx, set, options);
9144
0
        LY_CHECK_RET(rc);
9145
9146
0
        goto predicate;
9147
9148
0
    case LYXP_TOKEN_OPER_PATH:
9149
0
    case LYXP_TOKEN_OPER_RPATH:
9150
        /* AbsoluteLocationPath */
9151
0
        rc = eval_absolute_location_path(exp, tok_idx, set, options);
9152
0
        LY_CHECK_RET(rc);
9153
0
        break;
9154
9155
0
    case LYXP_TOKEN_LITERAL:
9156
        /* Literal */
9157
0
        if ((options & LYXP_SKIP_EXPR) || (options & LYXP_SCNODE_ALL)) {
9158
0
            if (!(options & LYXP_SKIP_EXPR)) {
9159
0
                set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
9160
0
            }
9161
0
            eval_literal(exp, tok_idx, NULL);
9162
0
        } else {
9163
0
            eval_literal(exp, tok_idx, set);
9164
0
        }
9165
9166
0
        goto predicate;
9167
9168
0
    case LYXP_TOKEN_NUMBER:
9169
        /* Number */
9170
0
        if ((options & LYXP_SKIP_EXPR) || (options & LYXP_SCNODE_ALL)) {
9171
0
            if (!(options & LYXP_SKIP_EXPR)) {
9172
0
                set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
9173
0
            }
9174
0
            rc = eval_number(exp, tok_idx, set, options | LYXP_SKIP_EXPR);
9175
0
        } else {
9176
0
            rc = eval_number(exp, tok_idx, set, options);
9177
0
        }
9178
0
        LY_CHECK_RET(rc);
9179
9180
0
        goto predicate;
9181
9182
0
    default:
9183
0
        LOGVAL_XPATH(set, options, LY_VCODE_XP_INTOK, lyxp_token2str(exp->tokens[*tok_idx]), &exp->expr[exp->tok_pos[*tok_idx]]);
9184
0
        return LY_EVALID;
9185
0
    }
9186
9187
0
    return LY_SUCCESS;
9188
9189
0
predicate:
9190
    /* Predicate* */
9191
0
    while (!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_BRACK1)) {
9192
0
        rc = eval_predicate(exp, tok_idx, set, options, LYXP_AXIS_CHILD);
9193
0
        LY_CHECK_RET(rc);
9194
0
    }
9195
9196
    /* ('/' or '//') RelativeLocationPath */
9197
0
    if (!exp_check_token2(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_PATH, LYXP_TOKEN_OPER_RPATH)) {
9198
9199
        /* evaluate '/' or '//' */
9200
0
        if (exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_PATH) {
9201
0
            all_desc = 0;
9202
0
        } else {
9203
0
            all_desc = 1;
9204
0
        }
9205
9206
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
9207
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9208
0
        ++(*tok_idx);
9209
9210
0
        rc = eval_relative_location_path(exp, tok_idx, all_desc, set, options);
9211
0
        LY_CHECK_RET(rc);
9212
0
    }
9213
9214
0
    return LY_SUCCESS;
9215
0
}
9216
9217
/**
9218
 * @brief Evaluate UnionExpr. Logs directly on error.
9219
 *
9220
 * [20] UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
9221
 *
9222
 * @param[in] exp Parsed XPath expression.
9223
 * @param[in] tok_idx Position in the expression @p exp.
9224
 * @param[in] repeat How many times this expression is repeated.
9225
 * @param[in,out] set Context and result set.
9226
 * @param[in] options XPath options.
9227
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9228
 */
9229
static LY_ERR
9230
eval_union_expr(const struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t repeat, struct lyxp_set *set, uint32_t options)
9231
0
{
9232
0
    LY_ERR rc = LY_SUCCESS;
9233
0
    uint32_t i;
9234
0
    struct lyxp_set orig_set, set2;
9235
0
    ly_bool found = 0;
9236
9237
0
    assert(repeat);
9238
9239
0
    set_init(&orig_set, set);
9240
0
    set_init(&set2, set);
9241
9242
0
    set_fill_set(&orig_set, set);
9243
9244
0
    rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_UNION, set, options);
9245
0
    LY_CHECK_GOTO(rc, cleanup);
9246
0
    if (set->not_found) {
9247
0
        set->not_found = 0;
9248
0
    } else {
9249
0
        found = 1;
9250
0
    }
9251
9252
    /* ('|' PathExpr)* */
9253
0
    for (i = 0; i < repeat; ++i) {
9254
0
        assert(exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_UNI);
9255
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
9256
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9257
0
        ++(*tok_idx);
9258
9259
0
        if (options & LYXP_SKIP_EXPR) {
9260
0
            rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_UNION, set, options);
9261
0
            LY_CHECK_GOTO(rc, cleanup);
9262
0
            continue;
9263
0
        }
9264
9265
0
        set_fill_set(&set2, &orig_set);
9266
0
        rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_UNION, &set2, options);
9267
0
        LY_CHECK_GOTO(rc, cleanup);
9268
0
        if (!set2.not_found) {
9269
0
            found = 1;
9270
0
        }
9271
9272
        /* eval */
9273
0
        if (options & LYXP_SCNODE_ALL) {
9274
0
            lyxp_set_scnode_merge(set, &set2);
9275
0
        } else {
9276
0
            rc = moveto_union(set, &set2);
9277
0
            LY_CHECK_GOTO(rc, cleanup);
9278
0
        }
9279
0
    }
9280
9281
0
cleanup:
9282
0
    lyxp_set_free_content(&orig_set);
9283
0
    lyxp_set_free_content(&set2);
9284
0
    if (!found) {
9285
0
        set->not_found = 1;
9286
0
    }
9287
0
    return rc;
9288
0
}
9289
9290
/**
9291
 * @brief Evaluate UnaryExpr. Logs directly on error.
9292
 *
9293
 * [19] UnaryExpr ::= UnionExpr | '-' UnaryExpr
9294
 *
9295
 * @param[in] exp Parsed XPath expression.
9296
 * @param[in] tok_idx Position in the expression @p exp.
9297
 * @param[in] repeat How many times this expression is repeated.
9298
 * @param[in,out] set Context and result set.
9299
 * @param[in] options XPath options.
9300
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9301
 */
9302
static LY_ERR
9303
eval_unary_expr(const struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t repeat, struct lyxp_set *set, uint32_t options)
9304
0
{
9305
0
    LY_ERR rc;
9306
0
    uint32_t this_op, i;
9307
9308
0
    assert(repeat);
9309
9310
    /* ('-')+ */
9311
0
    this_op = *tok_idx;
9312
0
    for (i = 0; i < repeat; ++i) {
9313
0
        assert(!lyxp_check_token(NULL, exp, *tok_idx, LYXP_TOKEN_OPER_MATH) && (exp->expr[exp->tok_pos[*tok_idx]] == '-'));
9314
9315
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
9316
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9317
0
        ++(*tok_idx);
9318
0
    }
9319
9320
0
    rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_UNARY, set, options);
9321
0
    LY_CHECK_RET(rc);
9322
9323
0
    if (!(options & LYXP_SKIP_EXPR) && (repeat % 2)) {
9324
0
        if (options & LYXP_SCNODE_ALL) {
9325
0
            warn_operands(set->ctx, set, NULL, 1, exp->expr, exp->tok_pos[this_op]);
9326
0
        } else {
9327
0
            rc = moveto_op_math(set, NULL, &exp->expr[exp->tok_pos[this_op]]);
9328
0
            LY_CHECK_RET(rc);
9329
0
        }
9330
0
    }
9331
9332
0
    return LY_SUCCESS;
9333
0
}
9334
9335
/**
9336
 * @brief Evaluate MultiplicativeExpr. Logs directly on error.
9337
 *
9338
 * [18] MultiplicativeExpr ::= UnaryExpr
9339
 *                     | MultiplicativeExpr '*' UnaryExpr
9340
 *                     | MultiplicativeExpr 'div' UnaryExpr
9341
 *                     | MultiplicativeExpr 'mod' UnaryExpr
9342
 *
9343
 * @param[in] exp Parsed XPath expression.
9344
 * @param[in] tok_idx Position in the expression @p exp.
9345
 * @param[in] repeat How many times this expression is repeated.
9346
 * @param[in,out] set Context and result set.
9347
 * @param[in] options XPath options.
9348
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9349
 */
9350
static LY_ERR
9351
eval_multiplicative_expr(const struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t repeat, struct lyxp_set *set,
9352
        uint32_t options)
9353
0
{
9354
0
    LY_ERR rc = LY_SUCCESS;
9355
0
    uint32_t i, this_op;
9356
0
    struct lyxp_set orig_set, set2;
9357
9358
0
    assert(repeat);
9359
9360
0
    set_init(&orig_set, set);
9361
0
    set_init(&set2, set);
9362
9363
0
    set_fill_set(&orig_set, set);
9364
9365
0
    rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_MULTIPLICATIVE, set, options);
9366
0
    LY_CHECK_GOTO(rc, cleanup);
9367
9368
    /* ('*' / 'div' / 'mod' UnaryExpr)* */
9369
0
    for (i = 0; i < repeat; ++i) {
9370
0
        this_op = *tok_idx;
9371
9372
0
        assert(exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_MATH);
9373
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
9374
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9375
0
        ++(*tok_idx);
9376
9377
0
        if (options & LYXP_SKIP_EXPR) {
9378
0
            rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_MULTIPLICATIVE, set, options);
9379
0
            LY_CHECK_GOTO(rc, cleanup);
9380
0
            continue;
9381
0
        }
9382
9383
0
        set_fill_set(&set2, &orig_set);
9384
0
        rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_MULTIPLICATIVE, &set2, options);
9385
0
        LY_CHECK_GOTO(rc, cleanup);
9386
0
        if (set2.not_found) {
9387
0
            set->not_found = 1;
9388
0
        }
9389
9390
        /* eval */
9391
0
        if (options & LYXP_SCNODE_ALL) {
9392
0
            warn_operands(set->ctx, set, &set2, 1, exp->expr, exp->tok_pos[this_op - 1]);
9393
0
            lyxp_set_scnode_merge(set, &set2);
9394
0
            set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
9395
0
        } else {
9396
0
            rc = moveto_op_math(set, &set2, &exp->expr[exp->tok_pos[this_op]]);
9397
0
            LY_CHECK_GOTO(rc, cleanup);
9398
0
        }
9399
0
    }
9400
9401
0
cleanup:
9402
0
    lyxp_set_free_content(&orig_set);
9403
0
    lyxp_set_free_content(&set2);
9404
0
    return rc;
9405
0
}
9406
9407
/**
9408
 * @brief Evaluate AdditiveExpr. Logs directly on error.
9409
 *
9410
 * [17] AdditiveExpr ::= MultiplicativeExpr
9411
 *                     | AdditiveExpr '+' MultiplicativeExpr
9412
 *                     | AdditiveExpr '-' MultiplicativeExpr
9413
 *
9414
 * @param[in] exp Parsed XPath expression.
9415
 * @param[in] tok_idx Position in the expression @p exp.
9416
 * @param[in] repeat How many times this expression is repeated.
9417
 * @param[in,out] set Context and result set.
9418
 * @param[in] options XPath options.
9419
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9420
 */
9421
static LY_ERR
9422
eval_additive_expr(const struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t repeat, struct lyxp_set *set, uint32_t options)
9423
0
{
9424
0
    LY_ERR rc = LY_SUCCESS;
9425
0
    uint32_t i, this_op;
9426
0
    struct lyxp_set orig_set, set2;
9427
9428
0
    assert(repeat);
9429
9430
0
    set_init(&orig_set, set);
9431
0
    set_init(&set2, set);
9432
9433
0
    set_fill_set(&orig_set, set);
9434
9435
0
    rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_ADDITIVE, set, options);
9436
0
    LY_CHECK_GOTO(rc, cleanup);
9437
9438
    /* ('+' / '-' MultiplicativeExpr)* */
9439
0
    for (i = 0; i < repeat; ++i) {
9440
0
        this_op = *tok_idx;
9441
9442
0
        assert(exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_MATH);
9443
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
9444
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9445
0
        ++(*tok_idx);
9446
9447
0
        if (options & LYXP_SKIP_EXPR) {
9448
0
            rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_ADDITIVE, set, options);
9449
0
            LY_CHECK_GOTO(rc, cleanup);
9450
0
            continue;
9451
0
        }
9452
9453
0
        set_fill_set(&set2, &orig_set);
9454
0
        rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_ADDITIVE, &set2, options);
9455
0
        LY_CHECK_GOTO(rc, cleanup);
9456
0
        if (set2.not_found) {
9457
0
            set->not_found = 1;
9458
0
        }
9459
9460
        /* eval */
9461
0
        if (options & LYXP_SCNODE_ALL) {
9462
0
            warn_operands(set->ctx, set, &set2, 1, exp->expr, exp->tok_pos[this_op - 1]);
9463
0
            lyxp_set_scnode_merge(set, &set2);
9464
0
            set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
9465
0
        } else {
9466
0
            rc = moveto_op_math(set, &set2, &exp->expr[exp->tok_pos[this_op]]);
9467
0
            LY_CHECK_GOTO(rc, cleanup);
9468
0
        }
9469
0
    }
9470
9471
0
cleanup:
9472
0
    lyxp_set_free_content(&orig_set);
9473
0
    lyxp_set_free_content(&set2);
9474
0
    return rc;
9475
0
}
9476
9477
/**
9478
 * @brief Evaluate RelationalExpr. Logs directly on error.
9479
 *
9480
 * [16] RelationalExpr ::= AdditiveExpr
9481
 *                       | RelationalExpr '<' AdditiveExpr
9482
 *                       | RelationalExpr '>' AdditiveExpr
9483
 *                       | RelationalExpr '<=' AdditiveExpr
9484
 *                       | RelationalExpr '>=' AdditiveExpr
9485
 *
9486
 * @param[in] exp Parsed XPath expression.
9487
 * @param[in] tok_idx Position in the expression @p exp.
9488
 * @param[in] repeat How many times this expression is repeated.
9489
 * @param[in,out] set Context and result set.
9490
 * @param[in] options XPath options.
9491
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9492
 */
9493
static LY_ERR
9494
eval_relational_expr(const struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t repeat, struct lyxp_set *set, uint32_t options)
9495
0
{
9496
0
    LY_ERR rc = LY_SUCCESS;
9497
0
    uint32_t i, this_op;
9498
0
    struct lyxp_set orig_set, set2;
9499
9500
0
    assert(repeat);
9501
9502
0
    set_init(&orig_set, set);
9503
0
    set_init(&set2, set);
9504
9505
0
    set_fill_set(&orig_set, set);
9506
9507
0
    rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_RELATIONAL, set, options);
9508
0
    LY_CHECK_GOTO(rc, cleanup);
9509
9510
    /* ('<' / '>' / '<=' / '>=' AdditiveExpr)* */
9511
0
    for (i = 0; i < repeat; ++i) {
9512
0
        this_op = *tok_idx;
9513
9514
0
        assert(exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_COMP);
9515
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
9516
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9517
0
        ++(*tok_idx);
9518
9519
0
        if (options & LYXP_SKIP_EXPR) {
9520
0
            rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_RELATIONAL, set, options);
9521
0
            LY_CHECK_GOTO(rc, cleanup);
9522
0
            continue;
9523
0
        }
9524
9525
0
        set_fill_set(&set2, &orig_set);
9526
0
        rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_RELATIONAL, &set2, options);
9527
0
        LY_CHECK_GOTO(rc, cleanup);
9528
0
        if (set2.not_found) {
9529
0
            set->not_found = 1;
9530
0
        }
9531
9532
        /* eval */
9533
0
        if (options & LYXP_SCNODE_ALL) {
9534
0
            warn_operands(set->ctx, set, &set2, 1, exp->expr, exp->tok_pos[this_op - 1]);
9535
0
            lyxp_set_scnode_merge(set, &set2);
9536
0
            set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
9537
0
        } else {
9538
0
            ly_bool result;
9539
9540
0
            rc = moveto_op_comp(set, &set2, &exp->expr[exp->tok_pos[this_op]], &result);
9541
0
            LY_CHECK_GOTO(rc, cleanup);
9542
0
            set_fill_boolean(set, result);
9543
0
        }
9544
0
    }
9545
9546
0
cleanup:
9547
0
    lyxp_set_free_content(&orig_set);
9548
0
    lyxp_set_free_content(&set2);
9549
0
    return rc;
9550
0
}
9551
9552
/**
9553
 * @brief Evaluate EqualityExpr. Logs directly on error.
9554
 *
9555
 * [15] EqualityExpr ::= RelationalExpr | EqualityExpr '=' RelationalExpr
9556
 *                     | EqualityExpr '!=' RelationalExpr
9557
 *
9558
 * @param[in] exp Parsed XPath expression.
9559
 * @param[in] tok_idx Position in the expression @p exp.
9560
 * @param[in] repeat How many times this expression is repeated.
9561
 * @param[in,out] set Context and result set.
9562
 * @param[in] options XPath options.
9563
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9564
 */
9565
static LY_ERR
9566
eval_equality_expr(const struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t repeat, struct lyxp_set *set, uint32_t options)
9567
0
{
9568
0
    LY_ERR rc = LY_SUCCESS;
9569
0
    uint32_t i, this_op;
9570
0
    struct lyxp_set orig_set, set2;
9571
9572
0
    assert(repeat);
9573
9574
0
    set_init(&orig_set, set);
9575
0
    set_init(&set2, set);
9576
9577
0
    set_fill_set(&orig_set, set);
9578
9579
0
    rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_EQUALITY, set, options);
9580
0
    LY_CHECK_GOTO(rc, cleanup);
9581
9582
    /* ('=' / '!=' RelationalExpr)* */
9583
0
    for (i = 0; i < repeat; ++i) {
9584
0
        this_op = *tok_idx;
9585
9586
0
        assert((exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_EQUAL) || (exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_NEQUAL));
9587
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (options & LYXP_SKIP_EXPR ? "skipped" : "parsed"),
9588
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9589
0
        ++(*tok_idx);
9590
9591
0
        if (options & LYXP_SKIP_EXPR) {
9592
0
            rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_EQUALITY, set, options);
9593
0
            LY_CHECK_GOTO(rc, cleanup);
9594
0
            continue;
9595
0
        }
9596
9597
0
        set_fill_set(&set2, &orig_set);
9598
0
        rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_EQUALITY, &set2, options);
9599
0
        LY_CHECK_GOTO(rc, cleanup);
9600
0
        if (set2.not_found) {
9601
0
            set->not_found = 1;
9602
0
        }
9603
9604
        /* eval */
9605
0
        if (options & LYXP_SCNODE_ALL) {
9606
0
            warn_operands(set->ctx, set, &set2, 0, exp->expr, exp->tok_pos[this_op - 1]);
9607
0
            warn_equality_value(exp, set, *tok_idx - 1, this_op - 1, *tok_idx - 1);
9608
0
            warn_equality_value(exp, &set2, this_op - 1, this_op - 1, *tok_idx - 1);
9609
0
            lyxp_set_scnode_merge(set, &set2);
9610
0
            set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_VAL);
9611
0
        } else {
9612
0
            ly_bool result;
9613
9614
0
            rc = moveto_op_comp(set, &set2, &exp->expr[exp->tok_pos[this_op]], &result);
9615
0
            LY_CHECK_GOTO(rc, cleanup);
9616
0
            set_fill_boolean(set, result);
9617
0
        }
9618
0
    }
9619
9620
0
cleanup:
9621
0
    lyxp_set_free_content(&orig_set);
9622
0
    lyxp_set_free_content(&set2);
9623
0
    return rc;
9624
0
}
9625
9626
/**
9627
 * @brief Evaluate AndExpr. Logs directly on error.
9628
 *
9629
 * [14] AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
9630
 *
9631
 * @param[in] exp Parsed XPath expression.
9632
 * @param[in] tok_idx Position in the expression @p exp.
9633
 * @param[in] repeat How many times this expression is repeated.
9634
 * @param[in,out] set Context and result set.
9635
 * @param[in] options XPath options.
9636
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9637
 */
9638
static LY_ERR
9639
eval_and_expr(const struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t repeat, struct lyxp_set *set, uint32_t options)
9640
0
{
9641
0
    LY_ERR rc = LY_SUCCESS;
9642
0
    struct lyxp_set orig_set, set2;
9643
0
    uint32_t i;
9644
9645
0
    assert(repeat);
9646
9647
0
    set_init(&orig_set, set);
9648
0
    set_init(&set2, set);
9649
9650
0
    set_fill_set(&orig_set, set);
9651
9652
0
    rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_AND, set, options);
9653
0
    LY_CHECK_GOTO(rc, cleanup);
9654
9655
0
    if (!(options & LYXP_SKIP_EXPR)) {
9656
0
        if (options & LYXP_SCNODE_ALL) {
9657
0
            set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
9658
0
        } else {
9659
            /* cast to boolean, we know that will be the final result */
9660
0
            lyxp_set_cast(set, LYXP_SET_BOOLEAN);
9661
0
        }
9662
0
    }
9663
9664
    /* ('and' EqualityExpr)* */
9665
0
    for (i = 0; i < repeat; ++i) {
9666
0
        assert(exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_LOG);
9667
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, ((options & LYXP_SKIP_EXPR) || !set->val.bln ? "skipped" : "parsed"),
9668
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9669
0
        ++(*tok_idx);
9670
9671
        /* lazy evaluation */
9672
0
        if ((options & LYXP_SKIP_EXPR) || ((set->type == LYXP_SET_BOOLEAN) && !set->val.bln)) {
9673
0
            rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_AND, set, options | LYXP_SKIP_EXPR);
9674
0
            LY_CHECK_GOTO(rc, cleanup);
9675
0
            continue;
9676
0
        }
9677
9678
0
        set_fill_set(&set2, &orig_set);
9679
0
        rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_AND, &set2, options);
9680
0
        LY_CHECK_GOTO(rc, cleanup);
9681
0
        if (set2.not_found) {
9682
0
            set->not_found = 1;
9683
0
        }
9684
9685
        /* eval - just get boolean value actually */
9686
0
        if (set->type == LYXP_SET_SCNODE_SET) {
9687
0
            set_scnode_clear_ctx(&set2, LYXP_SET_SCNODE_ATOM_NODE);
9688
0
            lyxp_set_scnode_merge(set, &set2);
9689
0
        } else {
9690
0
            lyxp_set_cast(&set2, LYXP_SET_BOOLEAN);
9691
0
            set_fill_set(set, &set2);
9692
0
        }
9693
0
    }
9694
9695
0
cleanup:
9696
0
    lyxp_set_free_content(&orig_set);
9697
0
    lyxp_set_free_content(&set2);
9698
0
    return rc;
9699
0
}
9700
9701
/**
9702
 * @brief Evaluate OrExpr. Logs directly on error.
9703
 *
9704
 * [13] OrExpr ::= AndExpr | OrExpr 'or' AndExpr
9705
 *
9706
 * @param[in] exp Parsed XPath expression.
9707
 * @param[in] tok_idx Position in the expression @p exp.
9708
 * @param[in] repeat How many times this expression is repeated.
9709
 * @param[in,out] set Context and result set.
9710
 * @param[in] options XPath options.
9711
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9712
 */
9713
static LY_ERR
9714
eval_or_expr(const struct lyxp_expr *exp, uint32_t *tok_idx, uint32_t repeat, struct lyxp_set *set, uint32_t options)
9715
0
{
9716
0
    LY_ERR rc = LY_SUCCESS;
9717
0
    struct lyxp_set orig_set, set2;
9718
0
    uint32_t i;
9719
9720
0
    assert(repeat);
9721
9722
0
    set_init(&orig_set, set);
9723
0
    set_init(&set2, set);
9724
9725
0
    set_fill_set(&orig_set, set);
9726
9727
0
    rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_OR, set, options);
9728
0
    LY_CHECK_GOTO(rc, cleanup);
9729
9730
0
    if (!(options & LYXP_SKIP_EXPR)) {
9731
0
        if (options & LYXP_SCNODE_ALL) {
9732
0
            set_scnode_clear_ctx(set, LYXP_SET_SCNODE_ATOM_NODE);
9733
0
        } else {
9734
            /* cast to boolean, we know that will be the final result */
9735
0
            lyxp_set_cast(set, LYXP_SET_BOOLEAN);
9736
0
        }
9737
0
    }
9738
9739
    /* ('or' AndExpr)* */
9740
0
    for (i = 0; i < repeat; ++i) {
9741
0
        assert(exp->tokens[*tok_idx] == LYXP_TOKEN_OPER_LOG);
9742
0
        LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, ((options & LYXP_SKIP_EXPR) || set->val.bln ? "skipped" : "parsed"),
9743
0
                lyxp_token2str(exp->tokens[*tok_idx]), exp->tok_pos[*tok_idx]);
9744
0
        ++(*tok_idx);
9745
9746
        /* lazy evaluation */
9747
0
        if ((options & LYXP_SKIP_EXPR) || ((set->type == LYXP_SET_BOOLEAN) && set->val.bln)) {
9748
0
            rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_OR, set, options | LYXP_SKIP_EXPR);
9749
0
            LY_CHECK_GOTO(rc, cleanup);
9750
0
            continue;
9751
0
        }
9752
9753
0
        set_fill_set(&set2, &orig_set);
9754
        /* expr_type cound have been LYXP_EXPR_NONE in all these later calls (except for the first one),
9755
         * but it does not matter */
9756
0
        rc = eval_expr_select(exp, tok_idx, LYXP_EXPR_OR, &set2, options);
9757
0
        LY_CHECK_GOTO(rc, cleanup);
9758
0
        if (set2.not_found) {
9759
0
            set->not_found = 1;
9760
0
        }
9761
9762
        /* eval - just get boolean value actually */
9763
0
        if (set->type == LYXP_SET_SCNODE_SET) {
9764
0
            set_scnode_clear_ctx(&set2, LYXP_SET_SCNODE_ATOM_NODE);
9765
0
            lyxp_set_scnode_merge(set, &set2);
9766
0
        } else {
9767
0
            lyxp_set_cast(&set2, LYXP_SET_BOOLEAN);
9768
0
            set_fill_set(set, &set2);
9769
0
        }
9770
0
    }
9771
9772
0
cleanup:
9773
0
    lyxp_set_free_content(&orig_set);
9774
0
    lyxp_set_free_content(&set2);
9775
0
    return rc;
9776
0
}
9777
9778
/**
9779
 * @brief Decide what expression is at the pointer @p tok_idx and evaluate it accordingly.
9780
 *
9781
 * @param[in] exp Parsed XPath expression.
9782
 * @param[in] tok_idx Position in the expression @p exp.
9783
 * @param[in] etype Expression type to evaluate.
9784
 * @param[in,out] set Context and result set.
9785
 * @param[in] options XPath options.
9786
 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
9787
 */
9788
static LY_ERR
9789
eval_expr_select(const struct lyxp_expr *exp, uint32_t *tok_idx, enum lyxp_expr_type etype, struct lyxp_set *set,
9790
        uint32_t options)
9791
0
{
9792
0
    uint32_t i, count;
9793
0
    enum lyxp_expr_type next_etype;
9794
0
    LY_ERR rc;
9795
9796
    /* process operator repeats */
9797
0
    if (!exp->repeat[*tok_idx]) {
9798
0
        next_etype = LYXP_EXPR_NONE;
9799
0
    } else {
9800
        /* find etype repeat */
9801
0
        for (i = 0; exp->repeat[*tok_idx][i] > etype; ++i) {}
9802
9803
        /* select one-priority lower because etype expression called us */
9804
0
        if (i) {
9805
0
            next_etype = exp->repeat[*tok_idx][i - 1];
9806
            /* count repeats for that expression */
9807
0
            for (count = 0; i && exp->repeat[*tok_idx][i - 1] == next_etype; ++count, --i) {}
9808
0
        } else {
9809
0
            next_etype = LYXP_EXPR_NONE;
9810
0
        }
9811
0
    }
9812
9813
    /* decide what expression are we parsing based on the repeat */
9814
0
    switch (next_etype) {
9815
0
    case LYXP_EXPR_OR:
9816
0
        rc = eval_or_expr(exp, tok_idx, count, set, options);
9817
0
        break;
9818
0
    case LYXP_EXPR_AND:
9819
0
        rc = eval_and_expr(exp, tok_idx, count, set, options);
9820
0
        break;
9821
0
    case LYXP_EXPR_EQUALITY:
9822
0
        rc = eval_equality_expr(exp, tok_idx, count, set, options);
9823
0
        break;
9824
0
    case LYXP_EXPR_RELATIONAL:
9825
0
        rc = eval_relational_expr(exp, tok_idx, count, set, options);
9826
0
        break;
9827
0
    case LYXP_EXPR_ADDITIVE:
9828
0
        rc = eval_additive_expr(exp, tok_idx, count, set, options);
9829
0
        break;
9830
0
    case LYXP_EXPR_MULTIPLICATIVE:
9831
0
        rc = eval_multiplicative_expr(exp, tok_idx, count, set, options);
9832
0
        break;
9833
0
    case LYXP_EXPR_UNARY:
9834
0
        rc = eval_unary_expr(exp, tok_idx, count, set, options);
9835
0
        break;
9836
0
    case LYXP_EXPR_UNION:
9837
0
        rc = eval_union_expr(exp, tok_idx, count, set, options);
9838
0
        break;
9839
0
    case LYXP_EXPR_NONE:
9840
0
        rc = eval_path_expr(exp, tok_idx, set, options);
9841
0
        break;
9842
0
    default:
9843
0
        LOGINT_RET(set->ctx);
9844
0
    }
9845
9846
0
    return rc;
9847
0
}
9848
9849
/**
9850
 * @brief Get root type.
9851
 *
9852
 * @param[in] ctx_node Context node.
9853
 * @param[in] ctx_scnode Schema context node.
9854
 * @param[in] options XPath options.
9855
 * @return Root type.
9856
 */
9857
static enum lyxp_node_type
9858
lyxp_get_root_type(const struct lyd_node *ctx_node, const struct lysc_node *ctx_scnode, uint32_t options)
9859
0
{
9860
0
    const struct lysc_node *op;
9861
9862
    /* explicit */
9863
0
    if (options & LYXP_ACCESS_TREE_ALL) {
9864
0
        return LYXP_NODE_ROOT;
9865
0
    } else if (options & LYXP_ACCESS_TREE_CONFIG) {
9866
0
        return LYXP_NODE_ROOT_CONFIG;
9867
0
    }
9868
9869
0
    if (options & LYXP_SCNODE_ALL) {
9870
        /* schema */
9871
0
        for (op = ctx_scnode; op && !(op->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF)); op = op->parent) {}
9872
9873
0
        if (op || !(options & LYXP_SCNODE_SCHEMA)) {
9874
            /* general root that can access everything */
9875
0
            return LYXP_NODE_ROOT;
9876
0
        } else if (!ctx_scnode || (ctx_scnode->flags & LYS_CONFIG_W)) {
9877
            /* root context node can access only config data (because we said so, it is unspecified) */
9878
0
            return LYXP_NODE_ROOT_CONFIG;
9879
0
        }
9880
0
        return LYXP_NODE_ROOT;
9881
0
    }
9882
9883
    /* data */
9884
0
    op = ctx_node ? ctx_node->schema : NULL;
9885
0
    for ( ; op && !(op->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF)); op = op->parent) {}
9886
9887
0
    if (op || !(options & LYXP_SCHEMA)) {
9888
        /* general root that can access everything */
9889
0
        return LYXP_NODE_ROOT;
9890
0
    } else if (!ctx_node || !ctx_node->schema || (ctx_node->schema->flags & LYS_CONFIG_W)) {
9891
        /* root context node can access only config data (because we said so, it is unspecified) */
9892
0
        return LYXP_NODE_ROOT_CONFIG;
9893
0
    }
9894
0
    return LYXP_NODE_ROOT;
9895
0
}
9896
9897
LY_ERR
9898
lyxp_eval(const struct ly_ctx *ctx, const struct lyxp_expr *exp, const struct lys_module *cur_mod,
9899
        LY_VALUE_FORMAT format, void *prefix_data, const struct lyd_node *cur_node, const struct lyd_node *ctx_node,
9900
        const struct lyd_node *tree, const struct lyxp_var *vars, struct lyxp_set *set, uint32_t options)
9901
0
{
9902
0
    uint32_t tok_idx = 0;
9903
0
    LY_ERR rc;
9904
9905
0
    LY_CHECK_ARG_RET(ctx, ctx, exp, set, LY_EINVAL);
9906
0
    if (!cur_mod && ((format == LY_VALUE_SCHEMA) || (format == LY_VALUE_SCHEMA_RESOLVED))) {
9907
0
        LOGERR(ctx, LY_EINVAL, "Current module must be set if schema format is used.");
9908
0
        return LY_EINVAL;
9909
0
    }
9910
9911
0
    if (tree) {
9912
        /* adjust the pointer to be the first top-level sibling */
9913
0
        while (tree->parent) {
9914
0
            tree = tree->parent;
9915
0
        }
9916
0
        tree = lyd_first_sibling(tree);
9917
9918
0
        if (lysc_data_parent(tree->schema)) {
9919
            /* unable to evaluate absolute paths */
9920
0
            LOGERR(ctx, LY_EINVAL, "Data node \"%s\" has no parent but is not instance of a top-level schema node.",
9921
0
                    LYD_NAME(tree));
9922
0
            return LY_EINVAL;
9923
0
        }
9924
0
    }
9925
9926
    /* prepare set for evaluation */
9927
0
    memset(set, 0, sizeof *set);
9928
0
    set->type = LYXP_SET_NODE_SET;
9929
0
    set->root_type = lyxp_get_root_type(ctx_node, NULL, options);
9930
0
    set_insert_node(set, (struct lyd_node *)ctx_node, 0, ctx_node ? LYXP_NODE_ELEM : set->root_type, 0);
9931
9932
0
    set->ctx = (struct ly_ctx *)ctx;
9933
0
    set->cur_node = cur_node;
9934
0
    for (set->context_op = cur_node ? cur_node->schema : NULL;
9935
0
            set->context_op && !(set->context_op->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF));
9936
0
            set->context_op = set->context_op->parent) {}
9937
0
    set->tree = tree;
9938
0
    set->cur_mod = cur_mod;
9939
0
    set->format = format;
9940
0
    set->prefix_data = prefix_data;
9941
0
    set->vars = vars;
9942
9943
    /* evaluate */
9944
0
    rc = eval_expr_select(exp, &tok_idx, 0, set, options);
9945
0
    if (!rc && set->not_found) {
9946
0
        rc = LY_ENOTFOUND;
9947
0
    }
9948
0
    if (rc) {
9949
0
        lyxp_set_free_content(set);
9950
0
    }
9951
9952
0
    return rc;
9953
0
}
9954
9955
#if 0
9956
9957
/* full xml printing of set elements, not used currently */
9958
9959
void
9960
lyxp_set_print_xml(FILE *f, struct lyxp_set *set)
9961
{
9962
    uint32_t i;
9963
    char *str_num;
9964
    struct lyout out;
9965
9966
    memset(&out, 0, sizeof out);
9967
9968
    out.type = LYOUT_STREAM;
9969
    out.method.f = f;
9970
9971
    switch (set->type) {
9972
    case LYXP_SET_EMPTY:
9973
        ly_print_(&out, "Empty XPath set\n\n");
9974
        break;
9975
    case LYXP_SET_BOOLEAN:
9976
        ly_print_(&out, "Boolean XPath set:\n");
9977
        ly_print_(&out, "%s\n\n", set->value.bool ? "true" : "false");
9978
        break;
9979
    case LYXP_SET_STRING:
9980
        ly_print_(&out, "String XPath set:\n");
9981
        ly_print_(&out, "\"%s\"\n\n", set->value.str);
9982
        break;
9983
    case LYXP_SET_NUMBER:
9984
        ly_print_(&out, "Number XPath set:\n");
9985
9986
        if (isnan(set->value.num)) {
9987
            str_num = strdup("NaN");
9988
        } else if ((set->value.num == 0) || (set->value.num == -0.0f)) {
9989
            str_num = strdup("0");
9990
        } else if (isinf(set->value.num) && !signbit(set->value.num)) {
9991
            str_num = strdup("Infinity");
9992
        } else if (isinf(set->value.num) && signbit(set->value.num)) {
9993
            str_num = strdup("-Infinity");
9994
        } else if ((long long)set->value.num == set->value.num) {
9995
            if (asprintf(&str_num, "%lld", (long long)set->value.num) == -1) {
9996
                str_num = NULL;
9997
            }
9998
        } else {
9999
            if (asprintf(&str_num, "%03.1Lf", set->value.num) == -1) {
10000
                str_num = NULL;
10001
            }
10002
        }
10003
        if (!str_num) {
10004
            LOGMEM;
10005
            return;
10006
        }
10007
        ly_print_(&out, "%s\n\n", str_num);
10008
        free(str_num);
10009
        break;
10010
    case LYXP_SET_NODE_SET:
10011
        ly_print_(&out, "Node XPath set:\n");
10012
10013
        for (i = 0; i < set->used; ++i) {
10014
            ly_print_(&out, "%d. ", i + 1);
10015
            switch (set->node_type[i]) {
10016
            case LYXP_NODE_ROOT_ALL:
10017
                ly_print_(&out, "ROOT all\n\n");
10018
                break;
10019
            case LYXP_NODE_ROOT_CONFIG:
10020
                ly_print_(&out, "ROOT config\n\n");
10021
                break;
10022
            case LYXP_NODE_ROOT_STATE:
10023
                ly_print_(&out, "ROOT state\n\n");
10024
                break;
10025
            case LYXP_NODE_ROOT_NOTIF:
10026
                ly_print_(&out, "ROOT notification \"%s\"\n\n", set->value.nodes[i]->schema->name);
10027
                break;
10028
            case LYXP_NODE_ROOT_RPC:
10029
                ly_print_(&out, "ROOT rpc \"%s\"\n\n", set->value.nodes[i]->schema->name);
10030
                break;
10031
            case LYXP_NODE_ROOT_OUTPUT:
10032
                ly_print_(&out, "ROOT output \"%s\"\n\n", set->value.nodes[i]->schema->name);
10033
                break;
10034
            case LYXP_NODE_ELEM:
10035
                ly_print_(&out, "ELEM \"%s\"\n", set->value.nodes[i]->schema->name);
10036
                xml_print_node(&out, 1, set->value.nodes[i], 1, LYP_FORMAT);
10037
                ly_print_(&out, "\n");
10038
                break;
10039
            case LYXP_NODE_TEXT:
10040
                ly_print_(&out, "TEXT \"%s\"\n\n", ((struct lyd_node_leaf_list *)set->value.nodes[i])->value_str);
10041
                break;
10042
            case LYXP_NODE_ATTR:
10043
                ly_print_(&out, "ATTR \"%s\" = \"%s\"\n\n", set->value.attrs[i]->name, set->value.attrs[i]->value);
10044
                break;
10045
            }
10046
        }
10047
        break;
10048
    }
10049
}
10050
10051
#endif
10052
10053
LY_ERR
10054
lyxp_set_cast(struct lyxp_set *set, enum lyxp_set_type target)
10055
0
{
10056
0
    long double num;
10057
0
    char *str;
10058
0
    LY_ERR rc;
10059
10060
0
    if (!set || (set->type == target)) {
10061
0
        return LY_SUCCESS;
10062
0
    }
10063
10064
    /* it's not possible to convert anything into a node set */
10065
0
    assert(target != LYXP_SET_NODE_SET);
10066
10067
0
    if (set->type == LYXP_SET_SCNODE_SET) {
10068
0
        lyxp_set_free_content(set);
10069
0
        return LY_EINVAL;
10070
0
    }
10071
10072
    /* to STRING */
10073
0
    if ((target == LYXP_SET_STRING) || ((target == LYXP_SET_NUMBER) && (set->type == LYXP_SET_NODE_SET))) {
10074
0
        switch (set->type) {
10075
0
        case LYXP_SET_NUMBER:
10076
0
            if (isnan(set->val.num)) {
10077
0
                set->val.str = strdup("NaN");
10078
0
                LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), -1);
10079
0
            } else if ((set->val.num == 0) || (set->val.num == -0.0f)) {
10080
0
                set->val.str = strdup("0");
10081
0
                LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), -1);
10082
0
            } else if (isinf(set->val.num) && !signbit(set->val.num)) {
10083
0
                set->val.str = strdup("Infinity");
10084
0
                LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), -1);
10085
0
            } else if (isinf(set->val.num) && signbit(set->val.num)) {
10086
0
                set->val.str = strdup("-Infinity");
10087
0
                LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), -1);
10088
0
            } else if ((long long)set->val.num == set->val.num) {
10089
0
                if (asprintf(&str, "%lld", (long long)set->val.num) == -1) {
10090
0
                    LOGMEM_RET(set->ctx);
10091
0
                }
10092
0
                set->val.str = str;
10093
0
            } else {
10094
0
                if (asprintf(&str, "%03.1Lf", set->val.num) == -1) {
10095
0
                    LOGMEM_RET(set->ctx);
10096
0
                }
10097
0
                set->val.str = str;
10098
0
            }
10099
0
            break;
10100
0
        case LYXP_SET_BOOLEAN:
10101
0
            if (set->val.bln) {
10102
0
                set->val.str = strdup("true");
10103
0
            } else {
10104
0
                set->val.str = strdup("false");
10105
0
            }
10106
0
            LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), LY_EMEM);
10107
0
            break;
10108
0
        case LYXP_SET_NODE_SET:
10109
            /* we need the set sorted, it affects the result */
10110
0
            assert(!set_sort(set));
10111
10112
0
            rc = cast_node_set_to_string(set, &str);
10113
0
            LY_CHECK_RET(rc);
10114
0
            lyxp_set_free_content(set);
10115
0
            set->val.str = str;
10116
0
            break;
10117
0
        default:
10118
0
            LOGINT_RET(set->ctx);
10119
0
        }
10120
0
        set->type = LYXP_SET_STRING;
10121
0
    }
10122
10123
    /* to NUMBER */
10124
0
    if (target == LYXP_SET_NUMBER) {
10125
0
        switch (set->type) {
10126
0
        case LYXP_SET_STRING:
10127
0
            num = cast_string_to_number(set->val.str);
10128
0
            lyxp_set_free_content(set);
10129
0
            set->val.num = num;
10130
0
            break;
10131
0
        case LYXP_SET_BOOLEAN:
10132
0
            if (set->val.bln) {
10133
0
                set->val.num = 1;
10134
0
            } else {
10135
0
                set->val.num = 0;
10136
0
            }
10137
0
            break;
10138
0
        default:
10139
0
            LOGINT_RET(set->ctx);
10140
0
        }
10141
0
        set->type = LYXP_SET_NUMBER;
10142
0
    }
10143
10144
    /* to BOOLEAN */
10145
0
    if (target == LYXP_SET_BOOLEAN) {
10146
0
        switch (set->type) {
10147
0
        case LYXP_SET_NUMBER:
10148
0
            if ((set->val.num == 0) || (set->val.num == -0.0f) || isnan(set->val.num)) {
10149
0
                set->val.bln = 0;
10150
0
            } else {
10151
0
                set->val.bln = 1;
10152
0
            }
10153
0
            break;
10154
0
        case LYXP_SET_STRING:
10155
0
            if (set->val.str[0]) {
10156
0
                lyxp_set_free_content(set);
10157
0
                set->val.bln = 1;
10158
0
            } else {
10159
0
                lyxp_set_free_content(set);
10160
0
                set->val.bln = 0;
10161
0
            }
10162
0
            break;
10163
0
        case LYXP_SET_NODE_SET:
10164
0
            if (set->used) {
10165
0
                lyxp_set_free_content(set);
10166
0
                set->val.bln = 1;
10167
0
            } else {
10168
0
                lyxp_set_free_content(set);
10169
0
                set->val.bln = 0;
10170
0
            }
10171
0
            break;
10172
0
        default:
10173
0
            LOGINT_RET(set->ctx);
10174
0
        }
10175
0
        set->type = LYXP_SET_BOOLEAN;
10176
0
    }
10177
10178
0
    return LY_SUCCESS;
10179
0
}
10180
10181
LY_ERR
10182
lyxp_atomize(const struct ly_ctx *ctx, const struct lyxp_expr *exp, const struct lys_module *cur_mod,
10183
        LY_VALUE_FORMAT format, void *prefix_data, const struct lysc_node *cur_scnode,
10184
        const struct lysc_node *ctx_scnode, struct lyxp_set *set, uint32_t options)
10185
0
{
10186
0
    LY_ERR rc;
10187
0
    uint32_t tok_idx = 0;
10188
10189
0
    LY_CHECK_ARG_RET(ctx, ctx, exp, set, LY_EINVAL);
10190
0
    if (!cur_mod && ((format == LY_VALUE_SCHEMA) || (format == LY_VALUE_SCHEMA_RESOLVED))) {
10191
0
        LOGARG(NULL, "Current module must be set if schema format is used.");
10192
0
        return LY_EINVAL;
10193
0
    }
10194
10195
    /* prepare set for evaluation */
10196
0
    memset(set, 0, sizeof *set);
10197
0
    set->type = LYXP_SET_SCNODE_SET;
10198
0
    set->root_type = lyxp_get_root_type(NULL, ctx_scnode, options);
10199
0
    LY_CHECK_RET(lyxp_set_scnode_insert_node(set, ctx_scnode, ctx_scnode ? LYXP_NODE_ELEM : set->root_type, LYXP_AXIS_SELF, NULL));
10200
0
    set->val.scnodes[0].in_ctx = LYXP_SET_SCNODE_START;
10201
10202
0
    set->ctx = (struct ly_ctx *)ctx;
10203
0
    set->cur_scnode = cur_scnode;
10204
0
    for (set->context_op = cur_scnode;
10205
0
            set->context_op && !(set->context_op->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF));
10206
0
            set->context_op = set->context_op->parent) {}
10207
0
    set->cur_mod = cur_mod;
10208
0
    set->format = format;
10209
0
    set->prefix_data = prefix_data;
10210
10211
    /* evaluate */
10212
0
    rc = eval_expr_select(exp, &tok_idx, 0, set, options);
10213
0
    if (!rc && set->not_found) {
10214
0
        rc = LY_ENOTFOUND;
10215
0
    }
10216
10217
0
    return rc;
10218
0
}
10219
10220
LIBYANG_API_DEF const char *
10221
lyxp_get_expr(const struct lyxp_expr *path)
10222
0
{
10223
0
    if (!path) {
10224
0
        return NULL;
10225
0
    }
10226
10227
0
    return path->expr;
10228
0
}