Coverage Report

Created: 2026-01-13 06:56

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