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