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