blob: d1e7bfb7b1a10bad4661af3fae7dd93fe2007370 [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;
Michal Vaskobe2e3562019-10-15 15:35:35 +02002081 max_arg_count = INT_MAX;
Michal Vasko03ff5a72019-09-11 13:49:33 +02002082 } 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{
Michal Vaskoae9e4cb2019-09-25 08:43:05 +02003534 struct lysc_ctx cctx;
Michal Vasko03ff5a72019-09-11 13:49:33 +02003535 struct lyd_node_term *leaf;
3536 struct lysc_node_leaf *sleaf;
Michal Vaskoae9e4cb2019-09-25 08:43:05 +02003537 const struct lysc_node *target;
Michal Vasko03ff5a72019-09-11 13:49:33 +02003538 const struct lyd_node *node;
3539 char *errmsg = NULL;
3540 const char *val;
3541 int dynamic;
3542 LY_ERR rc = LY_SUCCESS;
3543
3544 if (options & LYXP_SCNODE_ALL) {
3545 if ((args[0]->type != LYXP_SET_SCNODE_SET) || !(sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
3546 LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3547 rc = LY_EINVAL;
3548 } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3549 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
3550 rc = LY_EINVAL;
3551 } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_LEAFREF) && !warn_is_specific_type(sleaf->type, LY_TYPE_INST)) {
3552 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"leafref\" nor \"instance-identifier\".",
3553 __func__, sleaf->name);
3554 rc = LY_EINVAL;
3555 }
3556 set_scnode_clear_ctx(set);
Michal Vaskoae9e4cb2019-09-25 08:43:05 +02003557 if ((rc == LY_SUCCESS) && (sleaf->type->basetype == LY_TYPE_LEAFREF)) {
3558 cctx.ctx = set->ctx;
3559 rc = lys_compile_leafref_validate(&cctx, (struct lysc_node *)sleaf, (struct lysc_type_leafref *)sleaf->type, &target);
3560 /* it was already validated, it must succeed */
3561 if (rc == LY_SUCCESS) {
3562 set_scnode_insert_node(set, target, LYXP_NODE_ELEM);
3563 }
3564 }
3565
Michal Vasko03ff5a72019-09-11 13:49:33 +02003566 return rc;
3567 }
3568
3569 if ((args[0]->type != LYXP_SET_NODE_SET) && (args[0]->type != LYXP_SET_EMPTY)) {
3570 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "deref(node-set)");
3571 return LY_EVALID;
3572 }
3573
3574 lyxp_set_cast(set, LYXP_SET_EMPTY, options);
3575 if (args[0]->type != LYXP_SET_EMPTY) {
3576 leaf = (struct lyd_node_term *)args[0]->val.nodes[0].node;
3577 sleaf = (struct lysc_node_leaf *)leaf->schema;
3578 if (sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
3579 if (sleaf->type->basetype == LY_TYPE_LEAFREF) {
3580 /* find leafref target */
3581 val = lyd_value2str(leaf, &dynamic);
3582 node = ly_type_find_leafref(set->ctx, sleaf->type, val, strlen(val), (struct lyd_node *)leaf,
3583 set->trees, &leaf->value, &errmsg);
3584 if (dynamic) {
3585 free((char *)val);
3586 }
3587 if (!node) {
3588 LOGERR(set->ctx, LY_EINVAL, errmsg);
3589 free(errmsg);
3590 return LY_EINVAL;
3591 }
3592
3593 /* insert it */
3594 set_insert_node(set, node, 0, LYXP_NODE_ELEM, 0);
3595 } else {
3596 assert(sleaf->type->basetype == LY_TYPE_INST);
3597 node = (struct lyd_node *)lyd_target(leaf->value.target, set->trees);
3598 if (!node) {
3599 val = lyd_value2str(leaf, &dynamic);
3600 LOGERR(set->ctx, LY_EVALID, "Invalid instance-identifier \"%s\" value - required instance not found.", val);
3601 if (dynamic) {
3602 free((char *)val);
3603 }
3604 return LY_EVALID;
3605 }
3606 }
3607 }
3608 }
3609
3610 return LY_SUCCESS;
3611}
3612
3613/**
3614 * @brief Execute the YANG 1.1 derived-from(node-set, string) function. Returns LYXP_SET_BOOLEAN depending
3615 * on whether the first argument nodes contain a node of an identity derived from the second
3616 * argument identity.
3617 *
3618 * @param[in] args Array of arguments.
3619 * @param[in] arg_count Count of elements in @p args.
3620 * @param[in,out] set Context and result set at the same time.
3621 * @param[in] options XPath options.
3622 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
3623 */
3624static LY_ERR
3625xpath_derived_from(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
3626{
3627 uint16_t i;
3628 struct lyd_node_term *leaf;
3629 struct lysc_node_leaf *sleaf;
3630 struct lyd_value data = {0};
3631 struct ly_err_item *err = NULL;
3632 LY_ERR rc = LY_SUCCESS;
3633 int found;
3634
3635 if (options & LYXP_SCNODE_ALL) {
3636 if ((args[0]->type != LYXP_SET_SCNODE_SET) || !(sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
3637 LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3638 rc = LY_EINVAL;
3639 } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3640 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
3641 rc = LY_EINVAL;
3642 } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_IDENT)) {
3643 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"identityref\".", __func__, sleaf->name);
3644 rc = LY_EINVAL;
3645 }
3646
3647 if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
3648 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3649 LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
3650 rc = LY_EINVAL;
3651 } else if (!warn_is_string_type(sleaf->type)) {
3652 LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3653 rc = LY_EINVAL;
3654 }
3655 }
3656 set_scnode_clear_ctx(set);
3657 return rc;
3658 }
3659
3660 if ((args[0]->type != LYXP_SET_NODE_SET) && (args[0]->type != LYXP_SET_EMPTY)) {
3661 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "derived-from(node-set, string)");
3662 return LY_EVALID;
3663 }
3664 rc = lyxp_set_cast(args[1], LYXP_SET_STRING, options);
3665 LY_CHECK_RET(rc);
3666
3667 set_fill_boolean(set, 0);
3668 if (args[0]->type != LYXP_SET_EMPTY) {
3669 found = 0;
3670 for (i = 0; i < args[0]->used; ++i) {
3671 leaf = (struct lyd_node_term *)args[0]->val.nodes[i].node;
3672 sleaf = (struct lysc_node_leaf *)leaf->schema;
3673 if ((sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST)) && (sleaf->type->basetype == LY_TYPE_IDENT)) {
3674 /* store args[1] into ident */
3675 rc = sleaf->type->plugin->store(set->ctx, sleaf->type, args[1]->val.str, strlen(args[1]->val.str),
3676 LY_TYPE_OPTS_STORE, lys_resolve_prefix, (void *)sleaf->dflt_mod, set->format,
3677 (struct lyd_node *)leaf, set->trees, &data, NULL, &err);
3678 if (err) {
3679 ly_err_print(err);
3680 ly_err_free(err);
3681 }
3682 LY_CHECK_RET(rc);
3683
3684 LY_ARRAY_FOR(data.ident->derived, i) {
3685 if (data.ident->derived[i] == leaf->value.ident) {
3686 set_fill_boolean(set, 1);
3687 found = 1;
3688 break;
3689 }
3690 }
3691 if (found) {
3692 break;
3693 }
3694 }
3695 }
3696 }
3697
3698 return LY_SUCCESS;
3699}
3700
3701/**
3702 * @brief Execute the YANG 1.1 derived-from-or-self(node-set, string) function. Returns LYXP_SET_BOOLEAN depending
3703 * on whether the first argument nodes contain a node of an identity that either is or is derived from
3704 * the second argument identity.
3705 *
3706 * @param[in] args Array of arguments.
3707 * @param[in] arg_count Count of elements in @p args.
3708 * @param[in,out] set Context and result set at the same time.
3709 * @param[in] options XPath options.
3710 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
3711 */
3712static LY_ERR
3713xpath_derived_from_or_self(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
3714{
3715 uint16_t i;
3716 struct lyd_node_term *leaf;
3717 struct lysc_node_leaf *sleaf;
3718 struct lyd_value data = {0};
3719 struct ly_err_item *err = NULL;
3720 LY_ERR rc = LY_SUCCESS;
3721 int found;
3722
3723 if (options & LYXP_SCNODE_ALL) {
3724 if ((args[0]->type != LYXP_SET_SCNODE_SET) || !(sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
3725 LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3726 rc = LY_EINVAL;
3727 } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3728 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
3729 rc = LY_EINVAL;
3730 } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_IDENT)) {
3731 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"identityref\".", __func__, sleaf->name);
3732 rc = LY_EINVAL;
3733 }
3734
3735 if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
3736 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3737 LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
3738 rc = LY_EINVAL;
3739 } else if (!warn_is_string_type(sleaf->type)) {
3740 LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3741 rc = LY_EINVAL;
3742 }
3743 }
3744 set_scnode_clear_ctx(set);
3745 return rc;
3746 }
3747
3748 if ((args[0]->type != LYXP_SET_NODE_SET) && (args[0]->type != LYXP_SET_EMPTY)) {
3749 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)");
3750 return LY_EVALID;
3751 }
3752 rc = lyxp_set_cast(args[1], LYXP_SET_STRING, options);
3753 LY_CHECK_RET(rc);
3754
3755 set_fill_boolean(set, 0);
3756 if (args[0]->type != LYXP_SET_EMPTY) {
3757 found = 0;
3758 for (i = 0; i < args[0]->used; ++i) {
3759 leaf = (struct lyd_node_term *)args[0]->val.nodes[i].node;
3760 sleaf = (struct lysc_node_leaf *)leaf->schema;
3761 if ((sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST)) && (sleaf->type->basetype == LY_TYPE_IDENT)) {
3762 /* store args[1] into ident */
3763 rc = sleaf->type->plugin->store(set->ctx, sleaf->type, args[1]->val.str, strlen(args[1]->val.str),
3764 LY_TYPE_OPTS_STORE, lys_resolve_prefix, (void *)sleaf->dflt_mod, set->format,
3765 (struct lyd_node *)leaf, set->trees, &data, NULL, &err);
3766 if (err) {
3767 ly_err_print(err);
3768 ly_err_free(err);
3769 }
3770 LY_CHECK_RET(rc);
3771
3772 if (data.ident == leaf->value.ident) {
3773 set_fill_boolean(set, 1);
3774 break;
3775 }
3776 LY_ARRAY_FOR(data.ident->derived, i) {
3777 if (data.ident->derived[i] == leaf->value.ident) {
3778 set_fill_boolean(set, 1);
3779 found = 1;
3780 break;
3781 }
3782 }
3783 if (found) {
3784 break;
3785 }
3786 }
3787 }
3788 }
3789
3790 return LY_SUCCESS;
3791}
3792
3793/**
3794 * @brief Execute the YANG 1.1 enum-value(node-set) function. Returns LYXP_SET_NUMBER
3795 * with the integer value of the first node's enum value, otherwise NaN.
3796 *
3797 * @param[in] args Array of arguments.
3798 * @param[in] arg_count Count of elements in @p args.
3799 * @param[in,out] set Context and result set at the same time.
3800 * @param[in] options XPath options.
3801 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
3802 */
3803static LY_ERR
3804xpath_enum_value(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
3805{
3806 struct lyd_node_term *leaf;
3807 struct lysc_node_leaf *sleaf;
3808 LY_ERR rc = LY_SUCCESS;
3809
3810 if (options & LYXP_SCNODE_ALL) {
3811 if ((args[0]->type != LYXP_SET_SCNODE_SET) || !(sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
3812 LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
3813 rc = LY_EINVAL;
3814 } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3815 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
3816 rc = LY_EINVAL;
3817 } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_ENUM)) {
3818 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"enumeration\".", __func__, sleaf->name);
3819 rc = LY_EINVAL;
3820 }
3821 set_scnode_clear_ctx(set);
3822 return rc;
3823 }
3824
3825 if ((args[0]->type != LYXP_SET_NODE_SET) && (args[0]->type != LYXP_SET_EMPTY)) {
3826 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "enum-value(node-set)");
3827 return LY_EVALID;
3828 }
3829
3830 set_fill_number(set, NAN);
3831 if (args[0]->type == LYXP_SET_NODE_SET) {
3832 leaf = (struct lyd_node_term *)args[0]->val.nodes[0].node;
3833 sleaf = (struct lysc_node_leaf *)leaf->schema;
3834 if ((sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST)) && (sleaf->type->basetype == LY_TYPE_ENUM)) {
3835 set_fill_number(set, leaf->value.enum_item->value);
3836 }
3837 }
3838
3839 return LY_SUCCESS;
3840}
3841
3842/**
3843 * @brief Execute the XPath false() function. Returns LYXP_SET_BOOLEAN
3844 * with false value.
3845 *
3846 * @param[in] args Array of arguments.
3847 * @param[in] arg_count Count of elements in @p args.
3848 * @param[in,out] set Context and result set at the same time.
3849 * @param[in] options XPath options.
3850 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
3851 */
3852static LY_ERR
3853xpath_false(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
3854{
3855 if (options & LYXP_SCNODE_ALL) {
3856 set_scnode_clear_ctx(set);
3857 return LY_SUCCESS;
3858 }
3859
3860 set_fill_boolean(set, 0);
3861 return LY_SUCCESS;
3862}
3863
3864/**
3865 * @brief Execute the XPath floor(number) function. Returns LYXP_SET_NUMBER
3866 * with the first argument floored (truncated).
3867 *
3868 * @param[in] args Array of arguments.
3869 * @param[in] arg_count Count of elements in @p args.
3870 * @param[in,out] set Context and result set at the same time.
3871 * @param[in] options XPath options.
3872 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
3873 */
3874static LY_ERR
3875xpath_floor(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
3876{
3877 LY_ERR rc;
3878
3879 rc = lyxp_set_cast(args[0], LYXP_SET_NUMBER, options);
3880 LY_CHECK_RET(rc);
3881 if (isfinite(args[0]->val.num)) {
3882 set_fill_number(set, (long long)args[0]->val.num);
3883 }
3884
3885 return LY_SUCCESS;
3886}
3887
3888/**
3889 * @brief Execute the XPath lang(string) function. Returns LYXP_SET_BOOLEAN
3890 * whether the language of the text matches the one from the argument.
3891 *
3892 * @param[in] args Array of arguments.
3893 * @param[in] arg_count Count of elements in @p args.
3894 * @param[in,out] set Context and result set at the same time.
3895 * @param[in] options XPath options.
3896 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
3897 */
3898static LY_ERR
3899xpath_lang(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
3900{
3901 const struct lyd_node *node;
3902 struct lysc_node_leaf *sleaf;
3903 struct lyd_attr *attr = NULL;
3904 const char *val;
3905 int i, dynamic;
3906 LY_ERR rc = LY_SUCCESS;
3907
3908 if (options & LYXP_SCNODE_ALL) {
3909 if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
3910 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
3911 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
3912 rc = LY_EINVAL;
3913 } else if (!warn_is_string_type(sleaf->type)) {
3914 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
3915 rc = LY_EINVAL;
3916 }
3917 }
3918 set_scnode_clear_ctx(set);
3919 return rc;
3920 }
3921
3922 rc = lyxp_set_cast(args[0], LYXP_SET_STRING, options);
3923 LY_CHECK_RET(rc);
3924
3925 if (set->type == LYXP_SET_EMPTY) {
3926 set_fill_boolean(set, 0);
3927 return LY_SUCCESS;
3928 }
3929 if (set->type != LYXP_SET_NODE_SET) {
3930 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INCTX, print_set_type(set), "lang(string)");
3931 return LY_EVALID;
3932 }
3933
3934 switch (set->val.nodes[0].type) {
3935 case LYXP_NODE_ELEM:
3936 case LYXP_NODE_TEXT:
3937 node = set->val.nodes[0].node;
3938 break;
3939 case LYXP_NODE_ATTR:
3940 node = set->val.attrs[0].attr->parent;
3941 break;
3942 default:
3943 /* nothing to do with roots */
3944 set_fill_boolean(set, 0);
3945 return LY_SUCCESS;
3946 }
3947
3948 /* find lang attribute */
3949 for (; node; node = (struct lyd_node *)node->parent) {
3950 for (attr = node->attr; attr; attr = attr->next) {
3951 /* annotations */
3952 if (attr->name && !strcmp(attr->name, "lang") && !strcmp(attr->annotation->module->name, "xml")) {
3953 break;
3954 }
3955 }
3956
3957 if (attr) {
3958 break;
3959 }
3960 }
3961
3962 /* compare languages */
3963 if (!attr) {
3964 set_fill_boolean(set, 0);
3965 } else {
3966 val = lyd_attr2str(attr, &dynamic);
3967 for (i = 0; args[0]->val.str[i]; ++i) {
3968 if (tolower(args[0]->val.str[i]) != tolower(val[i])) {
3969 set_fill_boolean(set, 0);
3970 break;
3971 }
3972 }
3973 if (!args[0]->val.str[i]) {
3974 if (!val[i] || (val[i] == '-')) {
3975 set_fill_boolean(set, 1);
3976 } else {
3977 set_fill_boolean(set, 0);
3978 }
3979 }
3980 if (dynamic) {
3981 free((char *)val);
3982 }
3983 }
3984
3985 return LY_SUCCESS;
3986}
3987
3988/**
3989 * @brief Execute the XPath last() function. Returns LYXP_SET_NUMBER
3990 * with the context size.
3991 *
3992 * @param[in] args Array of arguments.
3993 * @param[in] arg_count Count of elements in @p args.
3994 * @param[in,out] set Context and result set at the same time.
3995 * @param[in] options XPath options.
3996 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
3997 */
3998static LY_ERR
3999xpath_last(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4000{
4001 if (options & LYXP_SCNODE_ALL) {
4002 set_scnode_clear_ctx(set);
4003 return LY_SUCCESS;
4004 }
4005
4006 if (set->type == LYXP_SET_EMPTY) {
4007 set_fill_number(set, 0);
4008 return LY_SUCCESS;
4009 }
4010 if (set->type != LYXP_SET_NODE_SET) {
4011 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INCTX, print_set_type(set), "last()");
4012 return LY_EVALID;
4013 }
4014
4015 set_fill_number(set, set->ctx_size);
4016 return LY_SUCCESS;
4017}
4018
4019/**
4020 * @brief Execute the XPath local-name(node-set?) function. Returns LYXP_SET_STRING
4021 * with the node name without namespace from the argument or the context.
4022 *
4023 * @param[in] args Array of arguments.
4024 * @param[in] arg_count Count of elements in @p args.
4025 * @param[in,out] set Context and result set at the same time.
4026 * @param[in] options XPath options.
4027 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4028 */
4029static LY_ERR
4030xpath_local_name(struct lyxp_set **args, uint16_t arg_count, struct lyxp_set *set, int options)
4031{
4032 struct lyxp_set_node *item;
4033 /* suppress unused variable warning */
4034 (void)options;
4035
4036 if (options & LYXP_SCNODE_ALL) {
4037 set_scnode_clear_ctx(set);
4038 return LY_SUCCESS;
4039 }
4040
4041 if (arg_count) {
4042 if (args[0]->type == LYXP_SET_EMPTY) {
4043 set_fill_string(set, "", 0);
4044 return LY_SUCCESS;
4045 }
4046 if (args[0]->type != LYXP_SET_NODE_SET) {
4047 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "local-name(node-set?)");
4048 return LY_EVALID;
4049 }
4050
4051 /* we need the set sorted, it affects the result */
4052 assert(!set_sort(args[0], options));
4053
4054 item = &args[0]->val.nodes[0];
4055 } else {
4056 if (set->type == LYXP_SET_EMPTY) {
4057 set_fill_string(set, "", 0);
4058 return LY_SUCCESS;
4059 }
4060 if (set->type != LYXP_SET_NODE_SET) {
4061 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INCTX, print_set_type(set), "local-name(node-set?)");
4062 return LY_EVALID;
4063 }
4064
4065 /* we need the set sorted, it affects the result */
4066 assert(!set_sort(set, options));
4067
4068 item = &set->val.nodes[0];
4069 }
4070
4071 switch (item->type) {
4072 case LYXP_NODE_ROOT:
4073 case LYXP_NODE_ROOT_CONFIG:
4074 case LYXP_NODE_TEXT:
4075 set_fill_string(set, "", 0);
4076 break;
4077 case LYXP_NODE_ELEM:
4078 set_fill_string(set, item->node->schema->name, strlen(item->node->schema->name));
4079 break;
4080 case LYXP_NODE_ATTR:
4081 set_fill_string(set, ((struct lyd_attr *)item->node)->name, strlen(((struct lyd_attr *)item->node)->name));
4082 break;
4083 }
4084
4085 return LY_SUCCESS;
4086}
4087
4088/**
4089 * @brief Execute the XPath name(node-set?) function. Returns LYXP_SET_STRING
4090 * with the node name fully qualified (with namespace) from the argument or the context.
4091 *
4092 * @param[in] args Array of arguments.
4093 * @param[in] arg_count Count of elements in @p args.
4094 * @param[in,out] set Context and result set at the same time.
4095 * @param[in] options XPath options.
4096 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4097 */
4098static LY_ERR
4099xpath_name(struct lyxp_set **args, uint16_t arg_count, struct lyxp_set *set, int options)
4100{
4101 struct lyxp_set_node *item;
4102 struct lys_module *mod;
4103 char *str;
4104 const char *name;
4105 int rc;
4106
4107 if (options & LYXP_SCNODE_ALL) {
4108 set_scnode_clear_ctx(set);
4109 return LY_SUCCESS;
4110 }
4111
4112 if (arg_count) {
4113 if (args[0]->type == LYXP_SET_EMPTY) {
4114 set_fill_string(set, "", 0);
4115 return LY_SUCCESS;
4116 }
4117 if (args[0]->type != LYXP_SET_NODE_SET) {
4118 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "name(node-set?)");
4119 return LY_EVALID;
4120 }
4121
4122 /* we need the set sorted, it affects the result */
4123 assert(!set_sort(args[0], options));
4124
4125 item = &args[0]->val.nodes[0];
4126 } else {
4127 if (set->type == LYXP_SET_EMPTY) {
4128 set_fill_string(set, "", 0);
4129 return LY_SUCCESS;
4130 }
4131 if (set->type != LYXP_SET_NODE_SET) {
4132 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INCTX, print_set_type(set), "name(node-set?)");
4133 return LY_EVALID;
4134 }
4135
4136 /* we need the set sorted, it affects the result */
4137 assert(!set_sort(set, options));
4138
4139 item = &set->val.nodes[0];
4140 }
4141
4142 switch (item->type) {
4143 case LYXP_NODE_ROOT:
4144 case LYXP_NODE_ROOT_CONFIG:
4145 case LYXP_NODE_TEXT:
4146 mod = NULL;
4147 name = NULL;
4148 break;
4149 case LYXP_NODE_ELEM:
4150 mod = item->node->schema->module;
4151 name = item->node->schema->name;
4152 break;
4153 case LYXP_NODE_ATTR:
4154 mod = ((struct lyd_attr *)item->node)->annotation->module;
4155 name = ((struct lyd_attr *)item->node)->name;
4156 break;
4157 }
4158
4159 if (mod && name) {
4160 switch (set->format) {
4161 case LYD_UNKNOWN:
4162 rc = asprintf(&str, "%s:%s", lys_prefix_find_module(set->local_mod, mod), name);
4163 break;
4164 case LYD_JSON:
4165 rc = asprintf(&str, "%s:%s", mod->name, name);
4166 break;
Michal Vasko9409ef62019-09-12 11:47:17 +02004167 default:
4168 LOGINT_RET(set->ctx);
Michal Vasko03ff5a72019-09-11 13:49:33 +02004169 }
4170 LY_CHECK_ERR_RET(rc == -1, LOGMEM(set->ctx), LY_EMEM);
4171 set_fill_string(set, str, strlen(str));
4172 free(str);
4173 } else {
4174 set_fill_string(set, "", 0);
4175 }
4176
4177 return LY_SUCCESS;
4178}
4179
4180/**
4181 * @brief Execute the XPath namespace-uri(node-set?) function. Returns LYXP_SET_STRING
4182 * with the namespace of the node from the argument or the context.
4183 *
4184 * @param[in] args Array of arguments.
4185 * @param[in] arg_count Count of elements in @p args.
4186 * @param[in,out] set Context and result set at the same time.
4187 * @param[in] options XPath options.
4188 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4189 */
4190static LY_ERR
4191xpath_namespace_uri(struct lyxp_set **args, uint16_t arg_count, struct lyxp_set *set, int options)
4192{
4193 struct lyxp_set_node *item;
4194 struct lys_module *mod;
4195 /* suppress unused variable warning */
4196 (void)options;
4197
4198 if (options & LYXP_SCNODE_ALL) {
4199 set_scnode_clear_ctx(set);
4200 return LY_SUCCESS;
4201 }
4202
4203 if (arg_count) {
4204 if (args[0]->type == LYXP_SET_EMPTY) {
4205 set_fill_string(set, "", 0);
4206 return LY_SUCCESS;
4207 }
4208 if (args[0]->type != LYXP_SET_NODE_SET) {
4209 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "namespace-uri(node-set?)");
4210 return LY_EVALID;
4211 }
4212
4213 /* we need the set sorted, it affects the result */
4214 assert(!set_sort(args[0], options));
4215
4216 item = &args[0]->val.nodes[0];
4217 } else {
4218 if (set->type == LYXP_SET_EMPTY) {
4219 set_fill_string(set, "", 0);
4220 return LY_SUCCESS;
4221 }
4222 if (set->type != LYXP_SET_NODE_SET) {
4223 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INCTX, print_set_type(set), "namespace-uri(node-set?)");
4224 return LY_EVALID;
4225 }
4226
4227 /* we need the set sorted, it affects the result */
4228 assert(!set_sort(set, options));
4229
4230 item = &set->val.nodes[0];
4231 }
4232
4233 switch (item->type) {
4234 case LYXP_NODE_ROOT:
4235 case LYXP_NODE_ROOT_CONFIG:
4236 case LYXP_NODE_TEXT:
4237 set_fill_string(set, "", 0);
4238 break;
4239 case LYXP_NODE_ELEM:
4240 case LYXP_NODE_ATTR:
4241 if (item->type == LYXP_NODE_ELEM) {
4242 mod = item->node->schema->module;
4243 } else { /* LYXP_NODE_ATTR */
4244 /* annotations */
4245 mod = ((struct lyd_attr *)item->node)->annotation->module;
4246 }
4247
4248 set_fill_string(set, mod->ns, strlen(mod->ns));
4249 break;
4250 }
4251
4252 return LY_SUCCESS;
4253}
4254
4255/**
4256 * @brief Execute the XPath node() function (node type). Returns LYXP_SET_NODE_SET
4257 * with only nodes from the context. In practice it either leaves the context
4258 * as it is or returns an empty node set.
4259 *
4260 * @param[in] args Array of arguments.
4261 * @param[in] arg_count Count of elements in @p args.
4262 * @param[in,out] set Context and result set at the same time.
4263 * @param[in] options XPath options.
4264 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4265 */
4266static LY_ERR
4267xpath_node(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4268{
4269 if (options & LYXP_SCNODE_ALL) {
4270 set_scnode_clear_ctx(set);
4271 return LY_SUCCESS;
4272 }
4273
4274 if (set->type != LYXP_SET_NODE_SET) {
4275 lyxp_set_cast(set, LYXP_SET_EMPTY, options);
4276 }
4277 return LY_SUCCESS;
4278}
4279
4280/**
4281 * @brief Execute the XPath normalize-space(string?) function. Returns LYXP_SET_STRING
4282 * with normalized value (no leading, trailing, double white spaces) of the node
4283 * from the argument or the context.
4284 *
4285 * @param[in] args Array of arguments.
4286 * @param[in] arg_count Count of elements in @p args.
4287 * @param[in,out] set Context and result set at the same time.
4288 * @param[in] options XPath options.
4289 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4290 */
4291static LY_ERR
4292xpath_normalize_space(struct lyxp_set **args, uint16_t arg_count, struct lyxp_set *set, int options)
4293{
4294 uint16_t i, new_used;
4295 char *new;
4296 int have_spaces = 0, space_before = 0;
4297 struct lysc_node_leaf *sleaf;
4298 LY_ERR rc = LY_SUCCESS;
4299
4300 if (options & LYXP_SCNODE_ALL) {
4301 if (arg_count && (args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4302 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4303 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4304 rc = LY_EINVAL;
4305 } else if (!warn_is_string_type(sleaf->type)) {
4306 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4307 rc = LY_EINVAL;
4308 }
4309 }
4310 set_scnode_clear_ctx(set);
4311 return rc;
4312 }
4313
4314 if (arg_count) {
4315 set_fill_set(set, args[0]);
4316 }
4317 rc = lyxp_set_cast(set, LYXP_SET_STRING, options);
4318 LY_CHECK_RET(rc);
4319
4320 /* is there any normalization necessary? */
4321 for (i = 0; set->val.str[i]; ++i) {
4322 if (is_xmlws(set->val.str[i])) {
4323 if ((i == 0) || space_before || (!set->val.str[i + 1])) {
4324 have_spaces = 1;
4325 break;
4326 }
4327 space_before = 1;
4328 } else {
4329 space_before = 0;
4330 }
4331 }
4332
4333 /* yep, there is */
4334 if (have_spaces) {
4335 /* it's enough, at least one character will go, makes space for ending '\0' */
4336 new = malloc(strlen(set->val.str) * sizeof(char));
4337 LY_CHECK_ERR_RET(!new, LOGMEM(set->ctx), LY_EMEM);
4338 new_used = 0;
4339
4340 space_before = 0;
4341 for (i = 0; set->val.str[i]; ++i) {
4342 if (is_xmlws(set->val.str[i])) {
4343 if ((i == 0) || space_before) {
4344 space_before = 1;
4345 continue;
4346 } else {
4347 space_before = 1;
4348 }
4349 } else {
4350 space_before = 0;
4351 }
4352
4353 new[new_used] = (space_before ? ' ' : set->val.str[i]);
4354 ++new_used;
4355 }
4356
4357 /* at worst there is one trailing space now */
4358 if (new_used && is_xmlws(new[new_used - 1])) {
4359 --new_used;
4360 }
4361
4362 new = ly_realloc(new, (new_used + 1) * sizeof(char));
4363 LY_CHECK_ERR_RET(!new, LOGMEM(set->ctx), LY_EMEM);
4364 new[new_used] = '\0';
4365
4366 free(set->val.str);
4367 set->val.str = new;
4368 }
4369
4370 return LY_SUCCESS;
4371}
4372
4373/**
4374 * @brief Execute the XPath not(boolean) function. Returns LYXP_SET_BOOLEAN
4375 * with the argument converted to boolean and logically inverted.
4376 *
4377 * @param[in] args Array of arguments.
4378 * @param[in] arg_count Count of elements in @p args.
4379 * @param[in,out] set Context and result set at the same time.
4380 * @param[in] options XPath options.
4381 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4382 */
4383static LY_ERR
4384xpath_not(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4385{
4386 if (options & LYXP_SCNODE_ALL) {
4387 set_scnode_clear_ctx(set);
4388 return LY_SUCCESS;
4389 }
4390
4391 lyxp_set_cast(args[0], LYXP_SET_BOOLEAN, options);
4392 if (args[0]->val.bool) {
4393 set_fill_boolean(set, 0);
4394 } else {
4395 set_fill_boolean(set, 1);
4396 }
4397
4398 return LY_SUCCESS;
4399}
4400
4401/**
4402 * @brief Execute the XPath number(object?) function. Returns LYXP_SET_NUMBER
4403 * with the number representation of either the argument or the context.
4404 *
4405 * @param[in] args Array of arguments.
4406 * @param[in] arg_count Count of elements in @p args.
4407 * @param[in,out] set Context and result set at the same time.
4408 * @param[in] options XPath options.
4409 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4410 */
4411static LY_ERR
4412xpath_number(struct lyxp_set **args, uint16_t arg_count, struct lyxp_set *set, int options)
4413{
4414 LY_ERR rc;
4415
4416 if (options & LYXP_SCNODE_ALL) {
4417 set_scnode_clear_ctx(set);
4418 return LY_SUCCESS;
4419 }
4420
4421 if (arg_count) {
4422 rc = lyxp_set_cast(args[0], LYXP_SET_NUMBER, options);
4423 LY_CHECK_RET(rc);
4424 set_fill_set(set, args[0]);
4425 } else {
4426 rc = lyxp_set_cast(set, LYXP_SET_NUMBER, options);
4427 LY_CHECK_RET(rc);
4428 }
4429
4430 return LY_SUCCESS;
4431}
4432
4433/**
4434 * @brief Execute the XPath position() function. Returns LYXP_SET_NUMBER
4435 * with the context position.
4436 *
4437 * @param[in] args Array of arguments.
4438 * @param[in] arg_count Count of elements in @p args.
4439 * @param[in,out] set Context and result set at the same time.
4440 * @param[in] options XPath options.
4441 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4442 */
4443static LY_ERR
4444xpath_position(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4445{
4446 if (options & LYXP_SCNODE_ALL) {
4447 set_scnode_clear_ctx(set);
4448 return LY_SUCCESS;
4449 }
4450
4451 if (set->type == LYXP_SET_EMPTY) {
4452 set_fill_number(set, 0);
4453 return LY_SUCCESS;
4454 }
4455 if (set->type != LYXP_SET_NODE_SET) {
4456 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INCTX, print_set_type(set), "position()");
4457 return LY_EVALID;
4458 }
4459
4460 set_fill_number(set, set->ctx_pos);
4461
4462 /* UNUSED in 'Release' build type */
4463 (void)options;
4464 return LY_SUCCESS;
4465}
4466
4467/**
4468 * @brief Execute the YANG 1.1 re-match(string, string) function. Returns LYXP_SET_BOOLEAN
4469 * depending on whether the second argument regex matches the first argument string. For details refer to
4470 * YANG 1.1 RFC section 10.2.1.
4471 *
4472 * @param[in] args Array of arguments.
4473 * @param[in] arg_count Count of elements in @p args.
4474 * @param[in,out] set Context and result set at the same time.
4475 * @param[in] options XPath options.
4476 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4477 */
4478static LY_ERR
4479xpath_re_match(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4480{
4481 struct lysc_pattern **patterns = NULL, **pattern;
4482 struct lysc_node_leaf *sleaf;
4483 char *path;
4484 LY_ERR rc = LY_SUCCESS;
4485 struct ly_err_item *err;
4486
4487 if (options & LYXP_SCNODE_ALL) {
4488 if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4489 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4490 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4491 rc = LY_EINVAL;
4492 } else if (!warn_is_string_type(sleaf->type)) {
4493 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4494 rc = LY_EINVAL;
4495 }
4496 }
4497
4498 if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
4499 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4500 LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4501 rc = LY_EINVAL;
4502 } else if (!warn_is_string_type(sleaf->type)) {
4503 LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4504 rc = LY_EINVAL;
4505 }
4506 }
4507 set_scnode_clear_ctx(set);
4508 return rc;
4509 }
4510
4511 rc = lyxp_set_cast(args[0], LYXP_SET_STRING, options);
4512 LY_CHECK_RET(rc);
4513 rc = lyxp_set_cast(args[1], LYXP_SET_STRING, options);
4514 LY_CHECK_RET(rc);
4515
4516 LY_ARRAY_NEW_RET(set->ctx, patterns, pattern, LY_EMEM);
4517 *pattern = malloc(sizeof **pattern);
4518 path = lyd_path(set->ctx_node, LYD_PATH_LOG, NULL, 0);
4519 rc = lys_compile_type_pattern_check(set->ctx, path, args[1]->val.str, &(*pattern)->code);
4520 free(path);
4521 if (rc != LY_SUCCESS) {
4522 LY_ARRAY_FREE(patterns);
4523 return rc;
4524 }
4525
4526 rc = ly_type_validate_patterns(patterns, args[0]->val.str, strlen(args[0]->val.str), &err);
4527 pcre2_code_free((*pattern)->code);
4528 free(*pattern);
4529 LY_ARRAY_FREE(patterns);
4530 if (rc && (rc != LY_EVALID)) {
4531 ly_err_print(err);
4532 ly_err_free(err);
4533 return rc;
4534 }
4535
4536 if (rc == LY_EVALID) {
4537 ly_err_free(err);
4538 set_fill_boolean(set, 0);
4539 } else {
4540 set_fill_boolean(set, 1);
4541 }
4542
4543 return LY_SUCCESS;
4544}
4545
4546/**
4547 * @brief Execute the XPath round(number) function. Returns LYXP_SET_NUMBER
4548 * with the rounded first argument. For details refer to
4549 * http://www.w3.org/TR/1999/REC-xpath-19991116/#function-round.
4550 *
4551 * @param[in] args Array of arguments.
4552 * @param[in] arg_count Count of elements in @p args.
4553 * @param[in,out] set Context and result set at the same time.
4554 * @param[in] options XPath options.
4555 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4556 */
4557static LY_ERR
4558xpath_round(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4559{
4560 struct lysc_node_leaf *sleaf;
4561 LY_ERR rc = LY_SUCCESS;
4562
4563 if (options & LYXP_SCNODE_ALL) {
4564 if ((args[0]->type != LYXP_SET_SCNODE_SET) || !(sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4565 LOGWRN(set->ctx, "Argument #1 of %s not a node-set as expected.", __func__);
4566 rc = LY_EINVAL;
4567 } else if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4568 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4569 rc = LY_EINVAL;
4570 } else if (!warn_is_specific_type(sleaf->type, LY_TYPE_DEC64)) {
4571 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of type \"decimal64\".", __func__, sleaf->name);
4572 rc = LY_EINVAL;
4573 }
4574 set_scnode_clear_ctx(set);
4575 return rc;
4576 }
4577
4578 rc = lyxp_set_cast(args[0], LYXP_SET_NUMBER, options);
4579 LY_CHECK_RET(rc);
4580
4581 /* cover only the cases where floor can't be used */
4582 if ((args[0]->val.num == -0.0f) || ((args[0]->val.num < 0) && (args[0]->val.num >= -0.5))) {
4583 set_fill_number(set, -0.0f);
4584 } else {
4585 args[0]->val.num += 0.5;
4586 rc = xpath_floor(args, 1, args[0], options);
4587 LY_CHECK_RET(rc);
4588 set_fill_number(set, args[0]->val.num);
4589 }
4590
4591 return LY_SUCCESS;
4592}
4593
4594/**
4595 * @brief Execute the XPath starts-with(string, string) function.
4596 * Returns LYXP_SET_BOOLEAN whether the second argument is
4597 * the prefix of the first or not.
4598 *
4599 * @param[in] args Array of arguments.
4600 * @param[in] arg_count Count of elements in @p args.
4601 * @param[in,out] set Context and result set at the same time.
4602 * @param[in] options XPath options.
4603 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4604 */
4605static LY_ERR
4606xpath_starts_with(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4607{
4608 struct lysc_node_leaf *sleaf;
4609 LY_ERR rc = LY_SUCCESS;
4610
4611 if (options & LYXP_SCNODE_ALL) {
4612 if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4613 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4614 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4615 rc = LY_EINVAL;
4616 } else if (!warn_is_string_type(sleaf->type)) {
4617 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4618 rc = LY_EINVAL;
4619 }
4620 }
4621
4622 if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
4623 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4624 LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4625 rc = LY_EINVAL;
4626 } else if (!warn_is_string_type(sleaf->type)) {
4627 LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4628 rc = LY_EINVAL;
4629 }
4630 }
4631 set_scnode_clear_ctx(set);
4632 return rc;
4633 }
4634
4635 rc = lyxp_set_cast(args[0], LYXP_SET_STRING, options);
4636 LY_CHECK_RET(rc);
4637 rc = lyxp_set_cast(args[1], LYXP_SET_STRING, options);
4638 LY_CHECK_RET(rc);
4639
4640 if (strncmp(args[0]->val.str, args[1]->val.str, strlen(args[1]->val.str))) {
4641 set_fill_boolean(set, 0);
4642 } else {
4643 set_fill_boolean(set, 1);
4644 }
4645
4646 return LY_SUCCESS;
4647}
4648
4649/**
4650 * @brief Execute the XPath string(object?) function. Returns LYXP_SET_STRING
4651 * with the string representation of either the argument or the context.
4652 *
4653 * @param[in] args Array of arguments.
4654 * @param[in] arg_count Count of elements in @p args.
4655 * @param[in,out] set Context and result set at the same time.
4656 * @param[in] options XPath options.
4657 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4658 */
4659static LY_ERR
4660xpath_string(struct lyxp_set **args, uint16_t arg_count, struct lyxp_set *set, int options)
4661{
4662 LY_ERR rc;
4663
4664 if (options & LYXP_SCNODE_ALL) {
4665 set_scnode_clear_ctx(set);
4666 return LY_SUCCESS;
4667 }
4668
4669 if (arg_count) {
4670 rc = lyxp_set_cast(args[0], LYXP_SET_STRING, options);
4671 LY_CHECK_RET(rc);
4672 set_fill_set(set, args[0]);
4673 } else {
4674 rc = lyxp_set_cast(set, LYXP_SET_STRING, options);
4675 LY_CHECK_RET(rc);
4676 }
4677
4678 return LY_SUCCESS;
4679}
4680
4681/**
4682 * @brief Execute the XPath string-length(string?) function. Returns LYXP_SET_NUMBER
4683 * with the length of the string in either the argument or the context.
4684 *
4685 * @param[in] args Array of arguments.
4686 * @param[in] arg_count Count of elements in @p args.
4687 * @param[in,out] set Context and result set at the same time.
4688 * @param[in] options XPath options.
4689 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4690 */
4691static LY_ERR
4692xpath_string_length(struct lyxp_set **args, uint16_t arg_count, struct lyxp_set *set, int options)
4693{
4694 struct lysc_node_leaf *sleaf;
4695 LY_ERR rc = LY_SUCCESS;
4696
4697 if (options & LYXP_SCNODE_ALL) {
4698 if (arg_count && (args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4699 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4700 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4701 rc = LY_EINVAL;
4702 } else if (!warn_is_string_type(sleaf->type)) {
4703 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4704 rc = LY_EINVAL;
4705 }
4706 }
4707 if (!arg_count && (set->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(set))) {
4708 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4709 LOGWRN(set->ctx, "Argument #0 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4710 rc = LY_EINVAL;
4711 } else if (!warn_is_string_type(sleaf->type)) {
4712 LOGWRN(set->ctx, "Argument #0 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4713 rc = LY_EINVAL;
4714 }
4715 }
4716 set_scnode_clear_ctx(set);
4717 return rc;
4718 }
4719
4720 if (arg_count) {
4721 rc = lyxp_set_cast(args[0], LYXP_SET_STRING, options);
4722 LY_CHECK_RET(rc);
4723 set_fill_number(set, strlen(args[0]->val.str));
4724 } else {
4725 rc = lyxp_set_cast(set, LYXP_SET_STRING, options);
4726 LY_CHECK_RET(rc);
4727 set_fill_number(set, strlen(set->val.str));
4728 }
4729
4730 return LY_SUCCESS;
4731}
4732
4733/**
4734 * @brief Execute the XPath substring(string, number, number?) function.
4735 * Returns LYXP_SET_STRING substring of the first argument starting
4736 * on the second argument index ending on the third argument index,
4737 * indexed from 1. For exact definition refer to
4738 * http://www.w3.org/TR/1999/REC-xpath-19991116/#function-substring.
4739 *
4740 * @param[in] args Array of arguments.
4741 * @param[in] arg_count Count of elements in @p args.
4742 * @param[in,out] set Context and result set at the same time.
4743 * @param[in] options XPath options.
4744 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4745 */
4746static LY_ERR
4747xpath_substring(struct lyxp_set **args, uint16_t arg_count, struct lyxp_set *set, int options)
4748{
4749 int start, len;
4750 uint16_t str_start, str_len, pos;
4751 struct lysc_node_leaf *sleaf;
4752 LY_ERR rc = LY_SUCCESS;
4753
4754 if (options & LYXP_SCNODE_ALL) {
4755 if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4756 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4757 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4758 rc = LY_EINVAL;
4759 } else if (!warn_is_string_type(sleaf->type)) {
4760 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4761 rc = LY_EINVAL;
4762 }
4763 }
4764
4765 if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
4766 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4767 LOGWRN(set->ctx, "Argument #2 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 #2 of %s is node \"%s\", not of numeric type.", __func__, sleaf->name);
4771 rc = LY_EINVAL;
4772 }
4773 }
4774
4775 if ((arg_count == 3) && (args[2]->type == LYXP_SET_SCNODE_SET)
4776 && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[2]))) {
4777 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4778 LOGWRN(set->ctx, "Argument #3 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4779 rc = LY_EINVAL;
4780 } else if (!warn_is_numeric_type(sleaf->type)) {
4781 LOGWRN(set->ctx, "Argument #3 of %s is node \"%s\", not of numeric type.", __func__, sleaf->name);
4782 rc = LY_EINVAL;
4783 }
4784 }
4785 set_scnode_clear_ctx(set);
4786 return rc;
4787 }
4788
4789 rc = lyxp_set_cast(args[0], LYXP_SET_STRING, options);
4790 LY_CHECK_RET(rc);
4791
4792 /* start */
4793 if (xpath_round(&args[1], 1, args[1], options)) {
4794 return -1;
4795 }
4796 if (isfinite(args[1]->val.num)) {
4797 start = args[1]->val.num - 1;
4798 } else if (isinf(args[1]->val.num) && signbit(args[1]->val.num)) {
4799 start = INT_MIN;
4800 } else {
4801 start = INT_MAX;
4802 }
4803
4804 /* len */
4805 if (arg_count == 3) {
4806 rc = xpath_round(&args[2], 1, args[2], options);
4807 LY_CHECK_RET(rc);
4808 if (isfinite(args[2]->val.num)) {
4809 len = args[2]->val.num;
4810 } else if (isnan(args[2]->val.num) || signbit(args[2]->val.num)) {
4811 len = 0;
4812 } else {
4813 len = INT_MAX;
4814 }
4815 } else {
4816 len = INT_MAX;
4817 }
4818
4819 /* find matching character positions */
4820 str_start = 0;
4821 str_len = 0;
4822 for (pos = 0; args[0]->val.str[pos]; ++pos) {
4823 if (pos < start) {
4824 ++str_start;
4825 } else if (pos < start + len) {
4826 ++str_len;
4827 } else {
4828 break;
4829 }
4830 }
4831
4832 set_fill_string(set, args[0]->val.str + str_start, str_len);
4833 return LY_SUCCESS;
4834}
4835
4836/**
4837 * @brief Execute the XPath substring-after(string, string) function.
4838 * Returns LYXP_SET_STRING with the string succeeding the occurance
4839 * of the second argument in the first or an empty string.
4840 *
4841 * @param[in] args Array of arguments.
4842 * @param[in] arg_count Count of elements in @p args.
4843 * @param[in,out] set Context and result set at the same time.
4844 * @param[in] options XPath options.
4845 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4846 */
4847static LY_ERR
4848xpath_substring_after(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4849{
4850 char *ptr;
4851 struct lysc_node_leaf *sleaf;
4852 LY_ERR rc = LY_SUCCESS;
4853
4854 if (options & LYXP_SCNODE_ALL) {
4855 if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4856 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4857 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4858 rc = LY_EINVAL;
4859 } else if (!warn_is_string_type(sleaf->type)) {
4860 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4861 rc = LY_EINVAL;
4862 }
4863 }
4864
4865 if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
4866 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4867 LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4868 rc = LY_EINVAL;
4869 } else if (!warn_is_string_type(sleaf->type)) {
4870 LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4871 rc = LY_EINVAL;
4872 }
4873 }
4874 set_scnode_clear_ctx(set);
4875 return rc;
4876 }
4877
4878 rc = lyxp_set_cast(args[0], LYXP_SET_STRING, options);
4879 LY_CHECK_RET(rc);
4880 rc = lyxp_set_cast(args[1], LYXP_SET_STRING, options);
4881 LY_CHECK_RET(rc);
4882
4883 ptr = strstr(args[0]->val.str, args[1]->val.str);
4884 if (ptr) {
4885 set_fill_string(set, ptr + strlen(args[1]->val.str), strlen(ptr + strlen(args[1]->val.str)));
4886 } else {
4887 set_fill_string(set, "", 0);
4888 }
4889
4890 return LY_SUCCESS;
4891}
4892
4893/**
4894 * @brief Execute the XPath substring-before(string, string) function.
4895 * Returns LYXP_SET_STRING with the string preceding the occurance
4896 * of the second argument in the first or an empty string.
4897 *
4898 * @param[in] args Array of arguments.
4899 * @param[in] arg_count Count of elements in @p args.
4900 * @param[in,out] set Context and result set at the same time.
4901 * @param[in] options XPath options.
4902 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4903 */
4904static LY_ERR
4905xpath_substring_before(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4906{
4907 char *ptr;
4908 struct lysc_node_leaf *sleaf;
4909 LY_ERR rc = LY_SUCCESS;
4910
4911 if (options & LYXP_SCNODE_ALL) {
4912 if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
4913 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4914 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4915 rc = LY_EINVAL;
4916 } else if (!warn_is_string_type(sleaf->type)) {
4917 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4918 rc = LY_EINVAL;
4919 }
4920 }
4921
4922 if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
4923 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4924 LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
4925 rc = LY_EINVAL;
4926 } else if (!warn_is_string_type(sleaf->type)) {
4927 LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
4928 rc = LY_EINVAL;
4929 }
4930 }
4931 set_scnode_clear_ctx(set);
4932 return rc;
4933 }
4934
4935 rc = lyxp_set_cast(args[0], LYXP_SET_STRING, options);
4936 LY_CHECK_RET(rc);
4937 rc = lyxp_set_cast(args[1], LYXP_SET_STRING, options);
4938 LY_CHECK_RET(rc);
4939
4940 ptr = strstr(args[0]->val.str, args[1]->val.str);
4941 if (ptr) {
4942 set_fill_string(set, args[0]->val.str, ptr - args[0]->val.str);
4943 } else {
4944 set_fill_string(set, "", 0);
4945 }
4946
4947 return LY_SUCCESS;
4948}
4949
4950/**
4951 * @brief Execute the XPath sum(node-set) function. Returns LYXP_SET_NUMBER
4952 * with the sum of all the nodes in the context.
4953 *
4954 * @param[in] args Array of arguments.
4955 * @param[in] arg_count Count of elements in @p args.
4956 * @param[in,out] set Context and result set at the same time.
4957 * @param[in] options XPath options.
4958 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
4959 */
4960static LY_ERR
4961xpath_sum(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
4962{
4963 long double num;
4964 char *str;
4965 uint16_t i;
4966 struct lyxp_set set_item;
4967 struct lysc_node_leaf *sleaf;
4968 LY_ERR rc = LY_SUCCESS;
4969
4970 if (options & LYXP_SCNODE_ALL) {
4971 if (args[0]->type == LYXP_SET_SCNODE_SET) {
4972 for (i = 0; i < args[0]->used; ++i) {
4973 if (args[0]->val.scnodes[i].in_ctx == 1) {
4974 sleaf = (struct lysc_node_leaf *)args[0]->val.scnodes[i].scnode;
4975 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
4976 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__,
4977 lys_nodetype2str(sleaf->nodetype), sleaf->name);
4978 rc = LY_EINVAL;
4979 } else if (!warn_is_numeric_type(sleaf->type)) {
4980 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of numeric type.", __func__, sleaf->name);
4981 rc = LY_EINVAL;
4982 }
4983 }
4984 }
4985 }
4986 set_scnode_clear_ctx(set);
4987 return rc;
4988 }
4989
4990 set_fill_number(set, 0);
4991 if (args[0]->type == LYXP_SET_EMPTY) {
4992 return LY_SUCCESS;
4993 }
4994
4995 if (args[0]->type != LYXP_SET_NODE_SET) {
4996 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INARGTYPE, 1, print_set_type(args[0]), "sum(node-set)");
4997 return LY_EVALID;
4998 }
4999
5000 set_item.type = LYXP_SET_NODE_SET;
5001 set_item.val.nodes = malloc(sizeof *set_item.val.nodes);
5002 LY_CHECK_ERR_RET(!set_item.val.nodes, LOGMEM(set->ctx), LY_EMEM);
5003
5004 set_item.used = 1;
5005 set_item.size = 1;
5006
5007 for (i = 0; i < args[0]->used; ++i) {
5008 set_item.val.nodes[0] = args[0]->val.nodes[i];
5009
5010 rc = cast_node_set_to_string(&set_item, options, &str);
5011 LY_CHECK_RET(rc);
5012 num = cast_string_to_number(str);
5013 free(str);
5014 set->val.num += num;
5015 }
5016
5017 free(set_item.val.nodes);
5018
5019 return LY_SUCCESS;
5020}
5021
5022/**
5023 * @brief Execute the XPath text() function (node type). Returns LYXP_SET_NODE_SET
5024 * with the text content of the nodes in the context.
5025 *
5026 * @param[in] args Array of arguments.
5027 * @param[in] arg_count Count of elements in @p args.
5028 * @param[in,out] set Context and result set at the same time.
5029 * @param[in] options XPath options.
5030 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
5031 */
5032static LY_ERR
5033xpath_text(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
5034{
5035 uint32_t i;
5036
5037 if (options & LYXP_SCNODE_ALL) {
5038 set_scnode_clear_ctx(set);
5039 return LY_SUCCESS;
5040 }
5041
5042 if (set->type == LYXP_SET_EMPTY) {
5043 return LY_SUCCESS;
5044 }
5045 if (set->type != LYXP_SET_NODE_SET) {
5046 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INCTX, print_set_type(set), "text()");
5047 return LY_EVALID;
5048 }
5049
5050 for (i = 0; i < set->used;) {
5051 switch (set->val.nodes[i].type) {
5052 case LYXP_NODE_ELEM:
5053 if (set->val.nodes[i].node->flags & LYD_DUMMY) {
5054 LOGVAL(set->ctx, LY_VLOG_LYD, set->val.nodes[i].node, LY_VCODE_XP_DUMMY, set->val.nodes[i].node->schema->name);
5055 return LY_EVALID;
5056 }
5057 if (set->val.nodes[i].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
5058 set->val.nodes[i].type = LYXP_NODE_TEXT;
5059 ++i;
5060 break;
5061 }
5062 /* fall through */
5063 case LYXP_NODE_ROOT:
5064 case LYXP_NODE_ROOT_CONFIG:
5065 case LYXP_NODE_TEXT:
5066 case LYXP_NODE_ATTR:
5067 set_remove_node(set, i);
5068 break;
5069 }
5070 }
5071
5072 return LY_SUCCESS;
5073}
5074
5075/**
5076 * @brief Execute the XPath translate(string, string, string) function.
5077 * Returns LYXP_SET_STRING with the first argument with the characters
5078 * from the second argument replaced by those on the corresponding
5079 * positions in the third argument.
5080 *
5081 * @param[in] args Array of arguments.
5082 * @param[in] arg_count Count of elements in @p args.
5083 * @param[in,out] set Context and result set at the same time.
5084 * @param[in] options XPath options.
5085 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
5086 */
5087static LY_ERR
5088xpath_translate(struct lyxp_set **args, uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
5089{
5090 uint16_t i, j, new_used;
5091 char *new;
5092 int found, have_removed;
5093 struct lysc_node_leaf *sleaf;
5094 LY_ERR rc = LY_SUCCESS;
5095
5096 if (options & LYXP_SCNODE_ALL) {
5097 if ((args[0]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[0]))) {
5098 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5099 LOGWRN(set->ctx, "Argument #1 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5100 rc = LY_EINVAL;
5101 } else if (!warn_is_string_type(sleaf->type)) {
5102 LOGWRN(set->ctx, "Argument #1 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5103 rc = LY_EINVAL;
5104 }
5105 }
5106
5107 if ((args[1]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[1]))) {
5108 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5109 LOGWRN(set->ctx, "Argument #2 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5110 rc = LY_EINVAL;
5111 } else if (!warn_is_string_type(sleaf->type)) {
5112 LOGWRN(set->ctx, "Argument #2 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5113 rc = LY_EINVAL;
5114 }
5115 }
5116
5117 if ((args[2]->type == LYXP_SET_SCNODE_SET) && (sleaf = (struct lysc_node_leaf *)warn_get_scnode_in_ctx(args[2]))) {
5118 if (!(sleaf->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
5119 LOGWRN(set->ctx, "Argument #3 of %s is a %s node \"%s\".", __func__, lys_nodetype2str(sleaf->nodetype), sleaf->name);
5120 rc = LY_EINVAL;
5121 } else if (!warn_is_string_type(sleaf->type)) {
5122 LOGWRN(set->ctx, "Argument #3 of %s is node \"%s\", not of string-type.", __func__, sleaf->name);
5123 rc = LY_EINVAL;
5124 }
5125 }
5126 set_scnode_clear_ctx(set);
5127 return rc;
5128 }
5129
5130 rc = lyxp_set_cast(args[0], LYXP_SET_STRING, options);
5131 LY_CHECK_RET(rc);
5132 rc = lyxp_set_cast(args[1], LYXP_SET_STRING, options);
5133 LY_CHECK_RET(rc);
5134 rc = lyxp_set_cast(args[2], LYXP_SET_STRING, options);
5135 LY_CHECK_RET(rc);
5136
5137 new = malloc((strlen(args[0]->val.str) + 1) * sizeof(char));
5138 LY_CHECK_ERR_RET(!new, LOGMEM(set->ctx), LY_EMEM);
5139 new_used = 0;
5140
5141 have_removed = 0;
5142 for (i = 0; args[0]->val.str[i]; ++i) {
5143 found = 0;
5144
5145 for (j = 0; args[1]->val.str[j]; ++j) {
5146 if (args[0]->val.str[i] == args[1]->val.str[j]) {
5147 /* removing this char */
5148 if (j >= strlen(args[2]->val.str)) {
5149 have_removed = 1;
5150 found = 1;
5151 break;
5152 }
5153 /* replacing this char */
5154 new[new_used] = args[2]->val.str[j];
5155 ++new_used;
5156 found = 1;
5157 break;
5158 }
5159 }
5160
5161 /* copying this char */
5162 if (!found) {
5163 new[new_used] = args[0]->val.str[i];
5164 ++new_used;
5165 }
5166 }
5167
5168 if (have_removed) {
5169 new = ly_realloc(new, (new_used + 1) * sizeof(char));
5170 LY_CHECK_ERR_RET(!new, LOGMEM(set->ctx), LY_EMEM);
5171 }
5172 new[new_used] = '\0';
5173
5174 lyxp_set_cast(set, LYXP_SET_EMPTY, options);
5175 set->type = LYXP_SET_STRING;
5176 set->val.str = new;
5177
5178 return LY_SUCCESS;
5179}
5180
5181/**
5182 * @brief Execute the XPath true() function. Returns LYXP_SET_BOOLEAN
5183 * with true value.
5184 *
5185 * @param[in] args Array of arguments.
5186 * @param[in] arg_count Count of elements in @p args.
5187 * @param[in,out] set Context and result set at the same time.
5188 * @param[in] options XPath options.
5189 * @return LY_ERR (LY_EINVAL for wrong arguments on schema)
5190 */
5191static LY_ERR
5192xpath_true(struct lyxp_set **UNUSED(args), uint16_t UNUSED(arg_count), struct lyxp_set *set, int options)
5193{
5194 if (options & LYXP_SCNODE_ALL) {
5195 set_scnode_clear_ctx(set);
5196 return LY_SUCCESS;
5197 }
5198
5199 set_fill_boolean(set, 1);
5200 return LY_SUCCESS;
5201}
5202
5203/*
5204 * moveto functions
5205 *
5206 * They and only they actually change the context (set).
5207 */
5208
5209/**
Michal Vasko6346ece2019-09-24 13:12:53 +02005210 * @brief Skip prefix and return corresponding model if there is a prefix. Logs directly.
Michal Vasko03ff5a72019-09-11 13:49:33 +02005211 *
Michal Vasko6346ece2019-09-24 13:12:53 +02005212 * @param[in,out] qname Qualified node name. If includes prefix, it is skipped.
5213 * @param[in,out] qname_len Length of @p qname, is updated accordingly.
5214 * @param[in] set Set with XPath context.
5215 * @param[out] moveto_mod Expected module of a matching node.
5216 * @return LY_ERR
Michal Vasko03ff5a72019-09-11 13:49:33 +02005217 */
Michal Vasko6346ece2019-09-24 13:12:53 +02005218static LY_ERR
5219moveto_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 +02005220{
Michal Vasko6346ece2019-09-24 13:12:53 +02005221 const struct lys_module *mod;
5222 const char *ptr;
5223 int pref_len;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005224 char *str;
5225
Michal Vasko6346ece2019-09-24 13:12:53 +02005226 if ((ptr = ly_strnchr(*qname, ':', *qname_len))) {
5227 /* specific module */
5228 pref_len = ptr - *qname;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005229
Michal Vasko6346ece2019-09-24 13:12:53 +02005230 switch (set->format) {
5231 case LYD_UNKNOWN:
5232 /* schema, search all local module imports */
5233 mod = lys_module_find_prefix(set->local_mod, *qname, pref_len);
5234 break;
5235 case LYD_JSON:
5236 /* JSON data, search in context */
5237 str = strndup(*qname, pref_len);
5238 mod = ly_ctx_get_module(set->ctx, str, NULL);
5239 free(str);
5240 break;
5241 default:
5242 LOGINT_RET(set->ctx);
5243 }
5244
5245 if (!mod->implemented) {
5246 /* non-implemented module is not valid */
5247 mod = NULL;
5248 }
5249 if (!mod) {
5250 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INMOD, pref_len, *qname);
5251 return LY_EVALID;
5252 }
5253 *qname += pref_len + 1;
5254 *qname_len -= pref_len + 1;
5255 } else if (((*qname)[0] == '*') && (*qname_len == 1)) {
5256 /* all modules - special case */
Michal Vasko03ff5a72019-09-11 13:49:33 +02005257 mod = NULL;
Michal Vasko6346ece2019-09-24 13:12:53 +02005258 } else {
5259 /* local module */
5260 mod = set->local_mod;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005261 }
5262
Michal Vasko6346ece2019-09-24 13:12:53 +02005263 *moveto_mod = mod;
5264 return LY_SUCCESS;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005265}
5266
5267/**
5268 * @brief Get the context root.
5269 *
5270 * @param[in] ctx_node Original context node.
5271 * @param[in] options XPath options.
5272 * @param[out] root_type Root type, differs only for when/must evaluation.
5273 * @return Context root.
5274 */
5275static const struct lyd_node *
5276moveto_get_root(const struct lyd_node *ctx_node, int options, enum lyxp_node_type *root_type)
5277{
5278 const struct lyd_node *root;
5279
5280 if (!ctx_node) {
5281 return NULL;
5282 }
5283
5284 if (!(options & LYXP_SCHEMA)) {
5285 /* special kind of root that can access everything */
5286 for (root = ctx_node; root->parent; root = (struct lyd_node *)root->parent);
5287 for (; root->prev->next; root = root->prev);
5288 *root_type = LYXP_NODE_ROOT;
5289 return root;
5290 }
5291
5292 if (ctx_node->schema->flags & LYS_CONFIG_W) {
5293 *root_type = LYXP_NODE_ROOT_CONFIG;
5294 } else {
5295 *root_type = LYXP_NODE_ROOT;
5296 }
5297
5298 for (root = ctx_node; root->parent; root = (struct lyd_node *)root->parent);
5299 for (; root->prev->next; root = root->prev);
5300
5301 return root;
5302}
5303
5304/**
5305 * @brief Get the schema context root.
5306 *
5307 * @param[in] ctx_scnode Original schema context node.
5308 * @param[in] options XPath options.
5309 * @param[out] root_type Root type, doffers only for when/must evaluation.
5310 * @return Context schema root.
5311 */
5312static const struct lysc_node *
5313moveto_scnode_get_root(const struct lysc_node *ctx_scnode, int options, enum lyxp_node_type *root_type)
5314{
5315 const struct lysc_node *root;
5316
5317 assert(ctx_scnode && root_type);
5318
5319 if (options & LYXP_SCNODE) {
5320 /* general root that can access everything */
5321 *root_type = LYXP_NODE_ROOT;
5322 } else if (ctx_scnode->flags & LYS_CONFIG_W) {
5323 *root_type = LYXP_NODE_ROOT_CONFIG;
5324 } else {
5325 *root_type = LYXP_NODE_ROOT;
5326 }
5327
5328 root = lys_getnext(NULL, NULL, ctx_scnode->module->compiled, LYS_GETNEXT_NOSTATECHECK);
5329
5330 return root;
5331}
5332
5333/**
5334 * @brief Move context @p set to the root. Handles absolute path.
5335 * Result is LYXP_SET_NODE_SET.
5336 *
5337 * @param[in,out] set Set to use.
5338 * @param[in] options Xpath options.
5339 */
5340static void
5341moveto_root(struct lyxp_set *set, int options)
5342{
5343 const struct lysc_node *scroot;
5344 const struct lyd_node *root;
5345 enum lyxp_node_type root_type;
5346
5347 if (!set) {
5348 return;
5349 }
5350
5351 if (options & LYXP_SCNODE_ALL) {
5352 scroot = moveto_scnode_get_root(set->ctx_scnode, options, &root_type);
5353 set_scnode_clear_ctx(set);
5354 set_scnode_insert_node(set, scroot, root_type);
5355 } else {
5356 root = moveto_get_root(set->ctx_node, options, &root_type);
5357 lyxp_set_cast(set, LYXP_SET_EMPTY, options);
5358 if (root) {
5359 set_insert_node(set, root, 0, root_type, 0);
5360 }
5361 }
5362}
5363
5364/**
5365 * @brief Check @p node as a part of NameTest processing.
5366 *
5367 * @param[in] node Node to check.
5368 * @param[in] root_type XPath root node type.
5369 * @param[in] node_name Node name to move to. Must be in the dictionary!
5370 * @param[in] moveto_mod Expected module of the node.
Michal Vasko6346ece2019-09-24 13:12:53 +02005371 * @return LY_ERR (LY_ENOT if node does not match, LY_EINCOMPLETE on unresolved when,
5372 * LY_EINVAL if netither node nor any children match)
Michal Vasko03ff5a72019-09-11 13:49:33 +02005373 */
5374static LY_ERR
5375moveto_node_check(const struct lyd_node *node, enum lyxp_node_type root_type, const char *node_name,
5376 const struct lys_module *moveto_mod)
5377{
5378 /* module check */
5379 if (moveto_mod && (node->schema->module != moveto_mod)) {
Michal Vasko6346ece2019-09-24 13:12:53 +02005380 return LY_ENOT;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005381 }
5382
Michal Vasko6346ece2019-09-24 13:12:53 +02005383 /* dummy and context check */
5384 if ((node->flags & LYD_DUMMY) || ((root_type == LYXP_NODE_ROOT_CONFIG) && (node->schema->flags & LYS_CONFIG_R))) {
Michal Vasko03ff5a72019-09-11 13:49:33 +02005385 return LY_EINVAL;
5386 }
5387
5388 /* name check */
5389 if (strcmp(node_name, "*") && !strcmp(node->schema->name, node_name)) {
Michal Vasko6346ece2019-09-24 13:12:53 +02005390 return LY_ENOT;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005391 }
5392
5393 /* TODO when check */
5394 /*if (!LYD_WHEN_DONE(node->when_status)) {
5395 return LY_EINCOMPLETE;
5396 }*/
5397
5398 /* match */
5399 return LY_SUCCESS;
5400}
5401
5402/**
5403 * @brief Check @p node as a part of schema NameTest processing.
5404 *
5405 * @param[in] node Schema node to check.
5406 * @param[in] root_type XPath root node type.
5407 * @param[in] node_name Node name to move to. Must be in the dictionary!
5408 * @param[in] moveto_mod Expected module of the node.
5409 * @param[in] options XPath options.
Michal Vasko6346ece2019-09-24 13:12:53 +02005410 * @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 +02005411 */
5412static LY_ERR
5413moveto_scnode_check(const struct lysc_node *node, enum lyxp_node_type root_type, const char *node_name,
5414 const struct lys_module *moveto_mod, int options)
5415{
5416 struct lysc_node *parent;
5417
5418 /* RPC input/output check */
5419 for (parent = node->parent; parent && (parent->nodetype != LYS_ACTION); parent = parent->parent);
5420 if (options & LYXP_SCNODE_OUTPUT) {
5421 if (parent && (node->flags & LYS_CONFIG_W)) {
5422 return LY_EINVAL;
5423 }
5424 } else {
5425 if (parent && (node->flags & LYS_CONFIG_R)) {
5426 return LY_EINVAL;
5427 }
5428 }
5429
5430 /* module check */
5431 if (strcmp(node_name, "*") && (node->module != moveto_mod)) {
Michal Vasko6346ece2019-09-24 13:12:53 +02005432 return LY_ENOT;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005433 }
5434
5435 /* context check */
5436 if ((root_type == LYXP_NODE_ROOT_CONFIG) && (node->flags & LYS_CONFIG_R)) {
5437 return LY_EINVAL;
5438 }
5439
5440 /* name check */
5441 if (strcmp(node_name, "*") && !strcmp(node->name, node_name)) {
Michal Vasko6346ece2019-09-24 13:12:53 +02005442 return LY_ENOT;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005443 }
5444
5445 /* match */
5446 return LY_SUCCESS;
5447}
5448
5449/**
5450 * @brief Move context @p set to a node. Handles '/' and '*', 'NAME', 'PREFIX:*', or 'PREFIX:NAME'.
5451 * Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY). Context position aware.
5452 *
5453 * @param[in,out] set Set to use.
5454 * @param[in] qname Qualified node name to move to.
5455 * @param[in] qname_len Length of @p qname.
5456 * @param[in] options XPath options.
5457 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
5458 */
5459static LY_ERR
5460moveto_node(struct lyxp_set *set, const char *qname, uint16_t qname_len, int options)
5461{
5462 uint32_t i;
Michal Vasko6346ece2019-09-24 13:12:53 +02005463 int replaced;
5464 const char *name_dict = NULL; /* optimization - so we can do (==) instead (!strncmp(...)) in moveto_node_check() */
Michal Vasko03ff5a72019-09-11 13:49:33 +02005465 const struct lys_module *moveto_mod;
5466 const struct lyd_node *sub;
5467 enum lyxp_node_type root_type;
5468 LY_ERR rc;
5469
5470 if (!set || (set->type == LYXP_SET_EMPTY)) {
5471 return LY_SUCCESS;
5472 }
5473
5474 if (set->type != LYXP_SET_NODE_SET) {
5475 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
5476 return LY_EVALID;
5477 }
5478
5479 moveto_get_root(set->ctx_node, options, &root_type);
Michal Vasko6346ece2019-09-24 13:12:53 +02005480 rc = moveto_resolve_model(&qname, &qname_len, set, &moveto_mod);
5481 LY_CHECK_RET(rc);
Michal Vasko03ff5a72019-09-11 13:49:33 +02005482
5483 /* name */
5484 name_dict = lydict_insert(set->ctx, qname, qname_len);
5485
5486 for (i = 0; i < set->used; ) {
5487 replaced = 0;
5488
5489 if ((set->val.nodes[i].type == LYXP_NODE_ROOT_CONFIG) || (set->val.nodes[i].type == LYXP_NODE_ROOT)) {
5490 if (set->trees) {
5491 /* search in all the trees */
5492 LY_ARRAY_FOR(set->trees, i) {
5493 for (sub = set->trees[i]; sub; sub = sub->next) {
5494 rc = moveto_node_check(sub, root_type, name_dict, moveto_mod);
5495 if (rc == LY_SUCCESS) {
5496 /* pos filled later */
5497 if (!replaced) {
5498 set_replace_node(set, sub, 0, LYXP_NODE_ELEM, i);
5499 replaced = 1;
5500 } else {
5501 set_insert_node(set, sub, 0, LYXP_NODE_ELEM, i);
5502 }
5503 ++i;
5504 } else if (rc == LY_EINCOMPLETE) {
5505 lydict_remove(set->ctx, name_dict);
5506 return rc;
5507 }
5508 }
5509 }
5510 } else {
5511 /* use just the context node */
5512 for (sub = set->val.nodes[i].node; sub; sub = sub->next) {
5513 rc = moveto_node_check(sub, root_type, name_dict, moveto_mod);
5514 if (rc == LY_SUCCESS) {
5515 /* pos filled later */
5516 if (!replaced) {
5517 set_replace_node(set, sub, 0, LYXP_NODE_ELEM, i);
5518 replaced = 1;
5519 } else {
5520 set_insert_node(set, sub, 0, LYXP_NODE_ELEM, i);
5521 }
5522 ++i;
5523 } else if (rc == LY_EINCOMPLETE) {
5524 lydict_remove(set->ctx, name_dict);
5525 return rc;
5526 }
5527 }
5528 }
5529
5530 /* skip nodes without children - leaves, leaflists, anyxmls, and dummy nodes (ouput root will eval to true) */
5531 } else if (!(set->val.nodes[i].node->flags & LYD_DUMMY)
5532 && !(set->val.nodes[i].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
5533
5534 for (sub = lyd_node_children(set->val.nodes[i].node); sub; sub = sub->next) {
5535 rc = moveto_node_check(sub, root_type, name_dict, moveto_mod);
5536 if (rc == LY_SUCCESS) {
5537 if (!replaced) {
5538 set_replace_node(set, sub, 0, LYXP_NODE_ELEM, i);
5539 replaced = 1;
5540 } else {
5541 set_insert_node(set, sub, 0, LYXP_NODE_ELEM, i);
5542 }
5543 ++i;
5544 } else if (rc == LY_EINCOMPLETE) {
5545 lydict_remove(set->ctx, name_dict);
5546 return rc;
5547 }
5548 }
5549 }
5550
5551 if (!replaced) {
5552 /* no match */
5553 set_remove_node(set, i);
5554 }
5555 }
5556 lydict_remove(set->ctx, name_dict);
5557
5558 return LY_SUCCESS;
5559}
5560
5561/**
5562 * @brief Move context @p set to a schema node. Handles '/' and '*', 'NAME', 'PREFIX:*', or 'PREFIX:NAME'.
5563 * Result is LYXP_SET_SCNODE_SET (or LYXP_SET_EMPTY).
5564 *
5565 * @param[in,out] set Set to use.
5566 * @param[in] qname Qualified node name to move to.
5567 * @param[in] qname_len Length of @p qname.
5568 * @param[in] options XPath options.
5569 * @return LY_ERR
5570 */
5571static LY_ERR
5572moveto_scnode(struct lyxp_set *set, const char *qname, uint16_t qname_len, int options)
5573{
Michal Vasko6346ece2019-09-24 13:12:53 +02005574 int i, orig_used, idx, temp_ctx = 0;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005575 uint32_t mod_idx;
Michal Vasko6346ece2019-09-24 13:12:53 +02005576 const char *name_dict = NULL; /* optimization - so we can do (==) instead (!strncmp(...)) in moveto_node_check() */
Michal Vasko03ff5a72019-09-11 13:49:33 +02005577 const struct lys_module *moveto_mod;
5578 const struct lysc_node *sub, *start_parent;
5579 enum lyxp_node_type root_type;
Michal Vasko6346ece2019-09-24 13:12:53 +02005580 LY_ERR rc;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005581
5582 if (!set || (set->type == LYXP_SET_EMPTY)) {
5583 return LY_SUCCESS;
5584 }
5585
5586 if (set->type != LYXP_SET_SCNODE_SET) {
5587 LOGVAL(set->ctx, LY_VLOG_LYS, set->ctx_scnode, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
5588 return LY_EVALID;
5589 }
5590
5591 moveto_scnode_get_root(set->ctx_scnode, options, &root_type);
Michal Vasko6346ece2019-09-24 13:12:53 +02005592 rc = moveto_resolve_model(&qname, &qname_len, set, &moveto_mod);
5593 LY_CHECK_RET(rc);
Michal Vasko03ff5a72019-09-11 13:49:33 +02005594
5595 /* name */
5596 name_dict = lydict_insert(set->ctx, qname, qname_len);
5597
5598 orig_used = set->used;
5599 for (i = 0; i < orig_used; ++i) {
5600 if (set->val.scnodes[i].in_ctx != 1) {
5601 continue;
5602 }
5603 set->val.scnodes[i].in_ctx = 0;
5604
5605 start_parent = set->val.scnodes[i].scnode;
5606
5607 if ((set->val.scnodes[i].type == LYXP_NODE_ROOT_CONFIG) || (set->val.scnodes[i].type == LYXP_NODE_ROOT)) {
5608 /* it can actually be in any module, it's all <running>, but we know it's moveto_mod (if set),
5609 * so use it directly (root node itself is useless in this case) */
5610 mod_idx = 0;
5611 while (moveto_mod || (moveto_mod = (struct lys_module *)ly_ctx_get_module_iter(set->ctx, &mod_idx))) {
5612 sub = NULL;
5613 while ((sub = lys_getnext(sub, NULL, moveto_mod->compiled, LYS_GETNEXT_NOSTATECHECK))) {
5614 if (!moveto_scnode_check(sub, root_type, name_dict, moveto_mod, options)) {
5615 idx = set_scnode_insert_node(set, sub, LYXP_NODE_ELEM);
5616 /* we need to prevent these nodes from being considered in this moveto */
5617 if ((idx < orig_used) && (idx > i)) {
5618 set->val.scnodes[idx].in_ctx = 2;
5619 temp_ctx = 1;
5620 }
5621 }
5622 }
5623
5624 if (!mod_idx) {
5625 /* moveto_mod was specified, we are not going through the whole context */
5626 break;
5627 }
5628 /* next iteration */
5629 moveto_mod = NULL;
5630 }
5631
5632 /* skip nodes without children - leaves, leaflists, and anyxmls (ouput root will eval to true) */
5633 } else if (!(start_parent->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
5634 sub = NULL;
5635 while ((sub = lys_getnext(sub, start_parent, NULL, LYS_GETNEXT_NOSTATECHECK))) {
5636 if (!moveto_scnode_check(sub, root_type, name_dict, (moveto_mod ? moveto_mod : set->local_mod), options)) {
5637 idx = set_scnode_insert_node(set, sub, LYXP_NODE_ELEM);
5638 if ((idx < orig_used) && (idx > i)) {
5639 set->val.scnodes[idx].in_ctx = 2;
5640 temp_ctx = 1;
5641 }
5642 }
5643 }
5644 }
5645 }
5646 lydict_remove(set->ctx, name_dict);
5647
5648 /* correct temporary in_ctx values */
5649 if (temp_ctx) {
5650 for (i = 0; i < orig_used; ++i) {
5651 if (set->val.scnodes[i].in_ctx == 2) {
5652 set->val.scnodes[i].in_ctx = 1;
5653 }
5654 }
5655 }
5656
5657 return LY_SUCCESS;
5658}
5659
5660/**
5661 * @brief Move context @p set to a node and all its descendants. Handles '//' and '*', 'NAME',
5662 * 'PREFIX:*', or 'PREFIX:NAME'. Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY).
5663 * Context position aware.
5664 *
5665 * @param[in] set Set to use.
5666 * @param[in] qname Qualified node name to move to.
5667 * @param[in] qname_len Length of @p qname.
5668 * @param[in] options XPath options.
5669 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
5670 */
5671static LY_ERR
5672moveto_node_alldesc(struct lyxp_set *set, const char *qname, uint16_t qname_len, int options)
5673{
5674 uint32_t i;
Michal Vasko6346ece2019-09-24 13:12:53 +02005675 const char *name_dict = NULL; /* optimization - so we can do (==) instead (!strncmp(...)) in moveto_node_check() */
Michal Vasko03ff5a72019-09-11 13:49:33 +02005676 const struct lyd_node *next, *elem, *start;
5677 const struct lys_module *moveto_mod;
5678 enum lyxp_node_type root_type;
5679 struct lyxp_set ret_set;
5680 LY_ERR rc;
5681
5682 if (!set || (set->type == LYXP_SET_EMPTY)) {
5683 return LY_SUCCESS;
5684 }
5685
5686 if (set->type != LYXP_SET_NODE_SET) {
5687 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
5688 return LY_EVALID;
5689 }
5690
5691 moveto_get_root(set->ctx_node, options, &root_type);
Michal Vasko6346ece2019-09-24 13:12:53 +02005692 rc = moveto_resolve_model(&qname, &qname_len, set, &moveto_mod);
5693 LY_CHECK_RET(rc);
Michal Vasko03ff5a72019-09-11 13:49:33 +02005694
5695 /* replace the original nodes (and throws away all text and attr nodes, root is replaced by a child) */
5696 rc = moveto_node(set, "*", 1, options);
5697 LY_CHECK_RET(rc);
5698
Michal Vasko6346ece2019-09-24 13:12:53 +02005699 /* name */
5700 name_dict = lydict_insert(set->ctx, qname, qname_len);
Michal Vasko03ff5a72019-09-11 13:49:33 +02005701
Michal Vasko6346ece2019-09-24 13:12:53 +02005702 /* this loop traverses all the nodes in the set and adds/keeps only those that match qname */
Michal Vasko03ff5a72019-09-11 13:49:33 +02005703 set_init(&ret_set, set);
5704 for (i = 0; i < set->used; ++i) {
5705
5706 /* TREE DFS */
5707 start = set->val.nodes[i].node;
5708 for (elem = next = start; elem; elem = next) {
Michal Vasko6346ece2019-09-24 13:12:53 +02005709 rc = moveto_node_check(elem, root_type, name_dict, moveto_mod);
5710 if (!rc) {
Michal Vasko03ff5a72019-09-11 13:49:33 +02005711 /* add matching node into result set */
5712 set_insert_node(&ret_set, elem, 0, LYXP_NODE_ELEM, ret_set.used);
5713 if (set_dup_node_check(set, elem, LYXP_NODE_ELEM, i)) {
5714 /* the node is a duplicate, we'll process it later in the set */
5715 goto skip_children;
5716 }
Michal Vasko6346ece2019-09-24 13:12:53 +02005717 } else if (rc == LY_EINCOMPLETE) {
5718 lydict_remove(set->ctx, name_dict);
5719 return rc;
5720 } else if (rc == LY_EINVAL) {
5721 goto skip_children;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005722 }
5723
5724 /* TREE DFS NEXT ELEM */
5725 /* select element for the next run - children first */
5726 if (elem->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
5727 next = NULL;
5728 } else {
5729 next = lyd_node_children(elem);
5730 }
5731 if (!next) {
5732skip_children:
5733 /* no children, so try siblings, but only if it's not the start,
5734 * that is considered to be the root and it's siblings are not traversed */
5735 if (elem != start) {
5736 next = elem->next;
5737 } else {
5738 break;
5739 }
5740 }
5741 while (!next) {
5742 /* no siblings, go back through the parents */
5743 if ((struct lyd_node *)elem->parent == start) {
5744 /* we are done, no next element to process */
5745 break;
5746 }
5747 /* parent is already processed, go to its sibling */
5748 elem = (struct lyd_node *)elem->parent;
5749 next = elem->next;
5750 }
5751 }
5752 }
5753
5754 /* make the temporary set the current one */
5755 ret_set.ctx_pos = set->ctx_pos;
5756 ret_set.ctx_size = set->ctx_size;
5757 set_free_content(set);
5758 memcpy(set, &ret_set, sizeof *set);
5759
Michal Vasko6346ece2019-09-24 13:12:53 +02005760 lydict_remove(set->ctx, name_dict);
Michal Vasko03ff5a72019-09-11 13:49:33 +02005761 return LY_SUCCESS;
5762}
5763
5764/**
5765 * @brief Move context @p set to a schema node and all its descendants. Handles '//' and '*', 'NAME',
5766 * 'PREFIX:*', or 'PREFIX:NAME'. Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY).
5767 *
5768 * @param[in] set Set to use.
5769 * @param[in] qname Qualified node name to move to.
5770 * @param[in] qname_len Length of @p qname.
5771 * @param[in] options XPath options.
5772 * @return LY_ERR
5773 */
5774static LY_ERR
5775moveto_scnode_alldesc(struct lyxp_set *set, const char *qname, uint16_t qname_len, int options)
5776{
Michal Vasko6346ece2019-09-24 13:12:53 +02005777 int i, orig_used, idx;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005778 const struct lysc_node *next, *elem, *start;
5779 const struct lys_module *moveto_mod;
5780 enum lyxp_node_type root_type;
Michal Vasko6346ece2019-09-24 13:12:53 +02005781 LY_ERR rc;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005782
5783 if (!set || (set->type == LYXP_SET_EMPTY)) {
5784 return LY_SUCCESS;
5785 }
5786
5787 if (set->type != LYXP_SET_SCNODE_SET) {
5788 LOGVAL(set->ctx, LY_VLOG_LYS, set->ctx_scnode, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
5789 return LY_EVALID;
5790 }
5791
5792 moveto_scnode_get_root(set->ctx_scnode, options, &root_type);
Michal Vasko6346ece2019-09-24 13:12:53 +02005793 rc = moveto_resolve_model(&qname, &qname_len, set, &moveto_mod);
5794 LY_CHECK_RET(rc);
Michal Vasko03ff5a72019-09-11 13:49:33 +02005795
5796 orig_used = set->used;
5797 for (i = 0; i < orig_used; ++i) {
5798 if (set->val.scnodes[i].in_ctx != 1) {
5799 continue;
5800 }
5801 set->val.scnodes[i].in_ctx = 0;
5802
5803 /* TREE DFS */
5804 start = set->val.scnodes[i].scnode;
5805 for (elem = next = start; elem; elem = next) {
Michal Vasko6346ece2019-09-24 13:12:53 +02005806 if ((elem == start) || (elem->nodetype & (LYS_CHOICE | LYS_CASE))) {
5807 /* schema-only nodes, skip root */
Michal Vasko03ff5a72019-09-11 13:49:33 +02005808 goto next_iter;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005809 }
5810
Michal Vasko6346ece2019-09-24 13:12:53 +02005811 rc = moveto_scnode_check(elem, root_type, qname, moveto_mod, options);
5812 if (!rc) {
Michal Vasko03ff5a72019-09-11 13:49:33 +02005813 if ((idx = set_scnode_dup_node_check(set, elem, LYXP_NODE_ELEM, i)) > -1) {
5814 set->val.scnodes[idx].in_ctx = 1;
5815 if (idx > i) {
5816 /* we will process it later in the set */
5817 goto skip_children;
5818 }
5819 } else {
5820 set_scnode_insert_node(set, elem, LYXP_NODE_ELEM);
5821 }
Michal Vasko6346ece2019-09-24 13:12:53 +02005822 } else if (rc == LY_EINVAL) {
5823 goto skip_children;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005824 }
5825
5826next_iter:
5827 /* TREE DFS NEXT ELEM */
5828 /* select element for the next run - children first */
5829 next = lysc_node_children(elem, options & LYXP_SCNODE_OUTPUT ? LYS_CONFIG_R : LYS_CONFIG_W);
5830 if (elem->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
5831 next = NULL;
5832 }
5833 if (!next) {
5834skip_children:
5835 /* no children, so try siblings, but only if it's not the start,
5836 * that is considered to be the root and it's siblings are not traversed */
5837 if (elem != start) {
5838 next = elem->next;
5839 } else {
5840 break;
5841 }
5842 }
5843 while (!next) {
5844 /* no siblings, go back through the parents */
5845 if (elem->parent == start) {
5846 /* we are done, no next element to process */
5847 break;
5848 }
5849 /* parent is already processed, go to its sibling */
5850 elem = elem->parent;
5851 next = elem->next;
5852 }
5853 }
5854 }
5855
5856 return LY_SUCCESS;
5857}
5858
5859/**
5860 * @brief Move context @p set to an attribute. Handles '/' and '@*', '@NAME', '@PREFIX:*',
5861 * or '@PREFIX:NAME'. Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY).
5862 * Indirectly context position aware.
5863 *
5864 * @param[in,out] set Set to use.
5865 * @param[in] qname Qualified node name to move to.
5866 * @param[in] qname_len Length of @p qname.
5867 * @param[in] options XPath options.
5868 * @return LY_ERR
5869 */
5870static LY_ERR
5871moveto_attr(struct lyxp_set *set, const char *qname, uint16_t qname_len, int UNUSED(options))
5872{
5873 uint32_t i;
Michal Vasko6346ece2019-09-24 13:12:53 +02005874 int replaced, all = 0;
5875 const struct lys_module *moveto_mod;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005876 struct lyd_attr *sub;
Michal Vasko6346ece2019-09-24 13:12:53 +02005877 LY_ERR rc;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005878
5879 if (!set || (set->type == LYXP_SET_EMPTY)) {
5880 return LY_SUCCESS;
5881 }
5882
5883 if (set->type != LYXP_SET_NODE_SET) {
5884 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
5885 return LY_EVALID;
5886 }
5887
Michal Vasko6346ece2019-09-24 13:12:53 +02005888 rc = moveto_resolve_model(&qname, &qname_len, set, &moveto_mod);
5889 LY_CHECK_RET(rc);
Michal Vasko03ff5a72019-09-11 13:49:33 +02005890
5891 if ((qname_len == 1) && (qname[0] == '*')) {
5892 all = 1;
5893 }
5894
5895 for (i = 0; i < set->used; ) {
5896 replaced = 0;
5897
5898 /* only attributes of an elem (not dummy) can be in the result, skip all the rest;
5899 * our attributes are always qualified */
5900 if ((set->val.nodes[i].type == LYXP_NODE_ELEM) && !(set->val.nodes[i].node->flags & LYD_DUMMY)) {
5901 for (sub = set->val.nodes[i].node->attr; sub; sub = sub->next) {
5902
5903 /* check "namespace" */
5904 if (moveto_mod && (sub->annotation->module != moveto_mod)) {
5905 continue;
5906 }
5907
5908 if (all || (!strncmp(sub->name, qname, qname_len) && !sub->name[qname_len])) {
5909 /* match */
5910 if (!replaced) {
5911 set->val.attrs[i].attr = sub;
5912 set->val.attrs[i].type = LYXP_NODE_ATTR;
5913 /* pos does not change */
5914 replaced = 1;
5915 } else {
5916 set_insert_node(set, (struct lyd_node *)sub, set->val.nodes[i].pos, LYXP_NODE_ATTR, i + 1);
5917 }
5918 ++i;
5919 }
5920 }
5921 }
5922
5923 if (!replaced) {
5924 /* no match */
5925 set_remove_node(set, i);
5926 }
5927 }
5928
5929 return LY_SUCCESS;
5930}
5931
5932/**
5933 * @brief Move context @p set1 to union with @p set2. @p set2 is emptied afterwards.
5934 * Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY). Context position aware.
5935 *
5936 * @param[in,out] set1 Set to use for the result.
5937 * @param[in] set2 Set that is copied to @p set1.
5938 * @param[in] options XPath options.
5939 * @return LY_ERR
5940 */
5941static LY_ERR
5942moveto_union(struct lyxp_set *set1, struct lyxp_set *set2, int options)
5943{
5944 LY_ERR rc;
5945
5946 if (((set1->type != LYXP_SET_NODE_SET) && (set1->type != LYXP_SET_EMPTY))
5947 || ((set2->type != LYXP_SET_NODE_SET) && (set2->type != LYXP_SET_EMPTY))) {
5948 LOGVAL(set1->ctx, LY_VLOG_LYD, set1->ctx_node, LY_VCODE_XP_INOP_2, "union", print_set_type(set1), print_set_type(set2));
5949 return LY_EVALID;
5950 }
5951
5952 /* set2 is empty or both set1 and set2 */
5953 if (set2->type == LYXP_SET_EMPTY) {
5954 return LY_SUCCESS;
5955 }
5956
5957 if (set1->type == LYXP_SET_EMPTY) {
5958 memcpy(set1, set2, sizeof *set1);
5959 /* dynamic memory belongs to set1 now, do not free */
5960 set2->type = LYXP_SET_EMPTY;
5961 return LY_SUCCESS;
5962 }
5963
5964 /* we assume sets are sorted */
5965 assert(!set_sort(set1, options) && !set_sort(set2, options));
5966
5967 /* sort, remove duplicates */
5968 rc = set_sorted_merge(set1, set2, options);
5969 LY_CHECK_RET(rc);
5970
5971 /* final set must be sorted */
5972 assert(!set_sort(set1, options));
5973
5974 return LY_SUCCESS;
5975}
5976
5977/**
5978 * @brief Move context @p set to an attribute in any of the descendants. Handles '//' and '@*',
5979 * '@NAME', '@PREFIX:*', or '@PREFIX:NAME'. Result is LYXP_SET_NODE_SET (or LYXP_SET_EMPTY).
5980 * Context position aware.
5981 *
5982 * @param[in,out] set Set to use.
5983 * @param[in] qname Qualified node name to move to.
5984 * @param[in] qname_len Length of @p qname.
5985 * @param[in] options XPath options.
5986 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
5987 */
5988static int
5989moveto_attr_alldesc(struct lyxp_set *set, const char *qname, uint16_t qname_len, int options)
5990{
5991 uint32_t i;
Michal Vasko6346ece2019-09-24 13:12:53 +02005992 int replaced, all = 0;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005993 struct lyd_attr *sub;
Michal Vasko6346ece2019-09-24 13:12:53 +02005994 const struct lys_module *moveto_mod;
Michal Vasko03ff5a72019-09-11 13:49:33 +02005995 struct lyxp_set *set_all_desc = NULL;
5996 LY_ERR rc;
5997
5998 if (!set || (set->type == LYXP_SET_EMPTY)) {
5999 return LY_SUCCESS;
6000 }
6001
6002 if (set->type != LYXP_SET_NODE_SET) {
6003 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
6004 return LY_EVALID;
6005 }
6006
Michal Vasko6346ece2019-09-24 13:12:53 +02006007 rc = moveto_resolve_model(&qname, &qname_len, set, &moveto_mod);
6008 LY_CHECK_RET(rc);
Michal Vasko03ff5a72019-09-11 13:49:33 +02006009
6010 /* can be optimized similarly to moveto_node_alldesc() and save considerable amount of memory,
6011 * but it likely won't be used much, so it's a waste of time */
6012 /* copy the context */
6013 set_all_desc = set_copy(set);
6014 /* get all descendant nodes (the original context nodes are removed) */
6015 rc = moveto_node_alldesc(set_all_desc, "*", 1, options);
6016 if (rc != LY_SUCCESS) {
6017 lyxp_set_free(set_all_desc);
6018 return rc;
6019 }
6020 /* prepend the original context nodes */
6021 rc = moveto_union(set, set_all_desc, options);
6022 if (rc != LY_SUCCESS) {
6023 lyxp_set_free(set_all_desc);
6024 return rc;
6025 }
6026 lyxp_set_free(set_all_desc);
6027
6028 if ((qname_len == 1) && (qname[0] == '*')) {
6029 all = 1;
6030 }
6031
6032 for (i = 0; i < set->used; ) {
6033 replaced = 0;
6034
6035 /* only attributes of an elem can be in the result, skip all the rest,
6036 * we have all attributes qualified in lyd tree */
6037 if (set->val.nodes[i].type == LYXP_NODE_ELEM) {
6038 for (sub = set->val.nodes[i].node->attr; sub; sub = sub->next) {
6039 /* check "namespace" */
6040 if (moveto_mod && (sub->annotation->module != moveto_mod)) {
6041 continue;
6042 }
6043
6044 if (all || (!strncmp(sub->name, qname, qname_len) && !sub->name[qname_len])) {
6045 /* match */
6046 if (!replaced) {
6047 set->val.attrs[i].attr = sub;
6048 set->val.attrs[i].type = LYXP_NODE_ATTR;
6049 /* pos does not change */
6050 replaced = 1;
6051 } else {
6052 set_insert_node(set, (struct lyd_node *)sub, set->val.attrs[i].pos, LYXP_NODE_ATTR, i + 1);
6053 }
6054 ++i;
6055 }
6056 }
6057 }
6058
6059 if (!replaced) {
6060 /* no match */
6061 set_remove_node(set, i);
6062 }
6063 }
6064
6065 return LY_SUCCESS;
6066}
6067
6068/**
6069 * @brief Move context @p set to self and al chilren, recursively. Handles '/' or '//' and '.'. Result is LYXP_SET_NODE_SET
6070 * (or LYXP_SET_EMPTY). Context position aware.
6071 *
6072 * @param[in] parent Current parent.
6073 * @param[in] parent_pos Position of @p parent.
6074 * @param[in] parent_type Node type of @p parent.
6075 * @param[in,out] to_set Set to use.
6076 * @param[in] dup_check_set Set for checking duplicities.
6077 * @param[in] root_type Node type of root.
6078 * @param[in] options XPath options.
6079 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
6080 */
6081static LY_ERR
6082moveto_self_add_children_r(const struct lyd_node *parent, uint32_t parent_pos, enum lyxp_node_type parent_type,
6083 struct lyxp_set *to_set, const struct lyxp_set *dup_check_set, enum lyxp_node_type root_type,
6084 int options)
6085{
6086 const struct lyd_node *sub;
6087 LY_ERR rc;
6088
6089 switch (parent_type) {
6090 case LYXP_NODE_ROOT:
6091 case LYXP_NODE_ROOT_CONFIG:
6092 /* add the same node but as an element */
6093 if (!set_dup_node_check(dup_check_set, parent, LYXP_NODE_ELEM, -1)) {
6094 set_insert_node(to_set, parent, 0, LYXP_NODE_ELEM, to_set->used);
6095
6096 /* skip anydata/anyxml and dummy nodes */
6097 if (!(parent->schema->nodetype & LYS_ANYDATA) && !(parent->flags & LYD_DUMMY)) {
6098 /* also add all the children of this node, recursively */
6099 rc = moveto_self_add_children_r(parent, 0, LYXP_NODE_ELEM, to_set, dup_check_set, root_type, options);
6100 LY_CHECK_RET(rc);
6101 }
6102 }
6103 break;
6104 case LYXP_NODE_ELEM:
6105 /* add all the children ... */
6106 if (!(parent->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
6107 for (sub = lyd_node_children(parent); sub; sub = sub->next) {
6108 /* context check */
6109 if ((root_type == LYXP_NODE_ROOT_CONFIG) && (sub->schema->flags & LYS_CONFIG_R)) {
6110 continue;
6111 }
6112
6113 /* TODO when check */
6114 /*if (!LYD_WHEN_DONE(sub->when_status)) {
6115 return LY_EINCOMPLETE;
6116 }*/
6117
6118 if (!set_dup_node_check(dup_check_set, sub, LYXP_NODE_ELEM, -1)) {
6119 set_insert_node(to_set, sub, 0, LYXP_NODE_ELEM, to_set->used);
6120
6121 /* skip anydata/anyxml and dummy nodes */
6122 if ((sub->schema->nodetype & LYS_ANYDATA) || (sub->flags & LYD_DUMMY)) {
6123 continue;
6124 }
6125
6126 /* also add all the children of this node, recursively */
6127 rc = moveto_self_add_children_r(sub, 0, LYXP_NODE_ELEM, to_set, dup_check_set, root_type, options);
6128 LY_CHECK_RET(rc);
6129 }
6130 }
6131
6132 /* ... or add their text node, ... */
6133 } else {
6134 if (!set_dup_node_check(dup_check_set, parent, LYXP_NODE_TEXT, -1)) {
6135 set_insert_node(to_set, parent, parent_pos, LYXP_NODE_TEXT, to_set->used);
6136 }
6137 }
6138 break;
6139 default:
6140 LOGINT_RET(parent->schema->module->ctx);
6141 }
6142
6143 return LY_SUCCESS;
6144}
6145
6146/**
6147 * @brief Move context @p set to self. Handles '/' or '//' and '.'. Result is LYXP_SET_NODE_SET
6148 * (or LYXP_SET_EMPTY). Context position aware.
6149 *
6150 * @param[in,out] set Set to use.
6151 * @param[in] all_desc Whether to go to all descendants ('//') or not ('/').
6152 * @param[in] options XPath options.
6153 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
6154 */
6155static LY_ERR
6156moveto_self(struct lyxp_set *set, int all_desc, int options)
6157{
6158 uint32_t i;
6159 enum lyxp_node_type root_type;
6160 struct lyxp_set ret_set;
6161 LY_ERR rc;
6162
6163 if (!set || (set->type == LYXP_SET_EMPTY)) {
6164 return LY_SUCCESS;
6165 }
6166
6167 if (set->type != LYXP_SET_NODE_SET) {
6168 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
6169 return LY_EVALID;
6170 }
6171
6172 /* nothing to do */
6173 if (!all_desc) {
6174 return LY_SUCCESS;
6175 }
6176
6177 moveto_get_root(set->ctx_node, options, &root_type);
6178
6179 /* add all the children, they get added recursively */
6180 set_init(&ret_set, set);
6181 for (i = 0; i < set->used; ++i) {
6182 /* copy the current node to tmp */
6183 set_insert_node(&ret_set, set->val.nodes[i].node, set->val.nodes[i].pos, set->val.nodes[i].type, ret_set.used);
6184
6185 /* do not touch attributes and text nodes */
6186 if ((set->val.nodes[i].type == LYXP_NODE_TEXT) || (set->val.nodes[i].type == LYXP_NODE_ATTR)) {
6187 continue;
6188 }
6189
6190 /* skip anydata/anyxml and dummy nodes */
6191 if ((set->val.nodes[i].node->schema->nodetype & LYS_ANYDATA) || (set->val.nodes[i].node->flags & LYD_DUMMY)) {
6192 continue;
6193 }
6194
6195 /* add all the children */
6196 rc = moveto_self_add_children_r(set->val.nodes[i].node, set->val.nodes[i].pos, set->val.nodes[i].type, &ret_set,
6197 set, root_type, options);
6198 if (rc != LY_SUCCESS) {
6199 set_free_content(&ret_set);
6200 return rc;
6201 }
6202 }
6203
6204 /* use the temporary set as the current one */
6205 ret_set.ctx_pos = set->ctx_pos;
6206 ret_set.ctx_size = set->ctx_size;
6207 set_free_content(set);
6208 memcpy(set, &ret_set, sizeof *set);
6209
6210 return LY_SUCCESS;
6211}
6212
6213/**
6214 * @brief Move context schema @p set to self. Handles '/' or '//' and '.'. Result is LYXP_SET_SCNODE_SET
6215 * (or LYXP_SET_EMPTY).
6216 *
6217 * @param[in,out] set Set to use.
6218 * @param[in] all_desc Whether to go to all descendants ('//') or not ('/').
6219 * @param[in] options XPath options.
6220 * @return LY_ERR
6221 */
6222static LY_ERR
6223moveto_scnode_self(struct lyxp_set *set, int all_desc, int options)
6224{
6225 const struct lysc_node *sub;
6226 uint32_t i;
6227 enum lyxp_node_type root_type;
6228
6229 if (!set || (set->type == LYXP_SET_EMPTY)) {
6230 return LY_SUCCESS;
6231 }
6232
6233 if (set->type != LYXP_SET_SCNODE_SET) {
6234 LOGVAL(set->ctx, LY_VLOG_LYS, set->ctx_scnode, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
6235 return LY_EVALID;
6236 }
6237
6238 /* nothing to do */
6239 if (!all_desc) {
6240 return LY_SUCCESS;
6241 }
6242
6243 moveto_scnode_get_root(set->ctx_scnode, options, &root_type);
6244
6245 /* add all the children, they get added recursively */
6246 for (i = 0; i < set->used; ++i) {
6247 if (set->val.scnodes[i].in_ctx != 1) {
6248 continue;
6249 }
6250
6251 /* add all the children */
6252 if (set->val.scnodes[i].scnode->nodetype & (LYS_LIST | LYS_CONTAINER)) {
6253 sub = NULL;
6254 while ((sub = lys_getnext(sub, set->val.scnodes[i].scnode, NULL, LYS_GETNEXT_NOSTATECHECK))) {
6255 /* RPC input/output check */
6256 if (options & LYXP_SCNODE_OUTPUT) {
6257 if (sub->parent->nodetype == LYS_INPUT) {
6258 continue;
6259 }
6260 } else {
6261 if (sub->parent->nodetype == LYS_OUTPUT) {
6262 continue;
6263 }
6264 }
6265
6266 /* context check */
6267 if ((root_type == LYXP_NODE_ROOT_CONFIG) && (sub->flags & LYS_CONFIG_R)) {
6268 continue;
6269 }
6270
6271 set_scnode_insert_node(set, sub, LYXP_NODE_ELEM);
6272 /* throw away the insert index, we want to consider that node again, recursively */
6273 }
6274 }
6275 }
6276
6277 return LY_SUCCESS;
6278}
6279
6280/**
6281 * @brief Move context @p set to parent. Handles '/' or '//' and '..'. Result is LYXP_SET_NODE_SET
6282 * (or LYXP_SET_EMPTY). Context position aware.
6283 *
6284 * @param[in] set Set to use.
6285 * @param[in] all_desc Whether to go to all descendants ('//') or not ('/').
6286 * @param[in] options XPath options.
6287 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
6288 */
6289static LY_ERR
6290moveto_parent(struct lyxp_set *set, int all_desc, int options)
6291{
6292 LY_ERR rc;
6293 uint32_t i;
6294 struct lyd_node *node, *new_node;
6295 const struct lyd_node *root;
6296 enum lyxp_node_type root_type, new_type;
6297
6298 if (!set || (set->type == LYXP_SET_EMPTY)) {
6299 return LY_SUCCESS;
6300 }
6301
6302 if (set->type != LYXP_SET_NODE_SET) {
6303 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
6304 return LY_EVALID;
6305 }
6306
6307 if (all_desc) {
6308 /* <path>//.. == <path>//./.. */
6309 rc = moveto_self(set, 1, options);
6310 LY_CHECK_RET(rc);
6311 }
6312
6313 root = moveto_get_root(set->ctx_node, options, &root_type);
6314
Michal Vasko57eab132019-09-24 11:46:26 +02006315 for (i = 0; i < set->used; ++i) {
Michal Vasko03ff5a72019-09-11 13:49:33 +02006316 node = set->val.nodes[i].node;
6317
6318 if (set->val.nodes[i].type == LYXP_NODE_ELEM) {
6319 new_node = (struct lyd_node *)node->parent;
6320 } else if (set->val.nodes[i].type == LYXP_NODE_TEXT) {
6321 new_node = node;
6322 } else if (set->val.nodes[i].type == LYXP_NODE_ATTR) {
6323 new_node = set->val.attrs[i].attr->parent;
6324 if (!new_node) {
6325 LOGINT_RET(set->ctx);
6326 }
6327 } else {
6328 /* root does not have a parent */
Michal Vasko57eab132019-09-24 11:46:26 +02006329 set_remove_node_null(set, i);
Michal Vasko03ff5a72019-09-11 13:49:33 +02006330 continue;
6331 }
6332
6333 /* TODO when check */
6334 /*if (new_node && !LYD_WHEN_DONE(new_node->when_status)) {
6335 return LY_EINCOMPLETE;
6336 }*/
6337
6338 /* node already there can also be the root */
6339 if (root == node) {
6340 if (options && (set->ctx_node->schema->flags & LYS_CONFIG_W)) {
6341 new_type = LYXP_NODE_ROOT_CONFIG;
6342 } else {
6343 new_type = LYXP_NODE_ROOT;
6344 }
6345 new_node = node;
6346
6347 /* node has no parent */
6348 } else if (!new_node) {
6349 if (options && (set->ctx_node->schema->flags & LYS_CONFIG_W)) {
6350 new_type = LYXP_NODE_ROOT_CONFIG;
6351 } else {
6352 new_type = LYXP_NODE_ROOT;
6353 }
6354#ifndef NDEBUG
6355 for (; node->prev->next; node = node->prev);
6356 if (node != root) {
6357 LOGINT(set->ctx);
6358 }
6359#endif
6360 new_node = (struct lyd_node *)root;
6361
6362 /* node has a standard parent (it can equal the root, it's not the root yet since they are fake) */
6363 } else {
6364 new_type = LYXP_NODE_ELEM;
6365 }
6366
6367 assert((new_type == LYXP_NODE_ELEM) || ((new_type == root_type) && (new_node == root)));
6368
6369 if (set_dup_node_check(set, new_node, new_type, -1)) {
Michal Vasko57eab132019-09-24 11:46:26 +02006370 set_remove_node_null(set, i);
Michal Vasko03ff5a72019-09-11 13:49:33 +02006371 } else {
6372 set_replace_node(set, new_node, 0, new_type, i);
Michal Vasko03ff5a72019-09-11 13:49:33 +02006373 }
6374 }
6375
Michal Vasko57eab132019-09-24 11:46:26 +02006376 set_remove_nodes_null(set);
Michal Vasko03ff5a72019-09-11 13:49:33 +02006377 assert(!set_sort(set, options) && !set_sorted_dup_node_clean(set));
6378
6379 return LY_SUCCESS;
6380}
6381
6382/**
6383 * @brief Move context schema @p set to parent. Handles '/' or '//' and '..'. Result is LYXP_SET_SCNODE_SET
6384 * (or LYXP_SET_EMPTY).
6385 *
6386 * @param[in] set Set to use.
6387 * @param[in] all_desc Whether to go to all descendants ('//') or not ('/').
6388 * @param[in] options XPath options.
6389 * @return LY_ERR
6390 */
6391static LY_ERR
6392moveto_scnode_parent(struct lyxp_set *set, int all_desc, int options)
6393{
6394 int idx, i, orig_used, temp_ctx = 0;
6395 const struct lysc_node *root, *node, *new_node;
6396 enum lyxp_node_type root_type, new_type;
6397 LY_ERR rc;
6398
6399 if (!set || (set->type == LYXP_SET_EMPTY)) {
6400 return LY_SUCCESS;
6401 }
6402
6403 if (set->type != LYXP_SET_SCNODE_SET) {
6404 LOGVAL(set->ctx, LY_VLOG_LYS, set->ctx_scnode, LY_VCODE_XP_INOP_1, "path operator", print_set_type(set));
6405 return LY_EVALID;
6406 }
6407
6408 if (all_desc) {
6409 /* <path>//.. == <path>//./.. */
6410 rc = moveto_scnode_self(set, 1, options);
6411 LY_CHECK_RET(rc);
6412 }
6413
6414 root = moveto_scnode_get_root(set->ctx_scnode, options, &root_type);
6415
6416 orig_used = set->used;
6417 for (i = 0; i < orig_used; ++i) {
6418 if (set->val.scnodes[i].in_ctx != 1) {
6419 continue;
6420 }
6421 set->val.scnodes[i].in_ctx = 0;
6422
6423 node = set->val.scnodes[i].scnode;
6424
6425 if (set->val.scnodes[i].type == LYXP_NODE_ELEM) {
6426 for (new_node = node->parent;
6427 new_node && (new_node->nodetype & (LYS_CHOICE | LYS_CASE));
6428 new_node = new_node->parent);
6429 } else {
6430 /* root does not have a parent */
6431 continue;
6432 }
6433
6434 /* node already there can also be the root */
6435 if (root == node) {
6436 if ((options & LYXP_SCNODE_SCHEMA) && (set->ctx_scnode->flags & LYS_CONFIG_W)) {
6437 new_type = LYXP_NODE_ROOT_CONFIG;
6438 } else {
6439 new_type = LYXP_NODE_ROOT;
6440 }
6441 new_node = node;
6442
6443 /* node has no parent */
6444 } else if (!new_node) {
6445 if ((options & LYXP_SCNODE_SCHEMA) && (set->ctx_scnode->flags & LYS_CONFIG_W)) {
6446 new_type = LYXP_NODE_ROOT_CONFIG;
6447 } else {
6448 new_type = LYXP_NODE_ROOT;
6449 }
6450#ifndef NDEBUG
6451 node = lys_getnext(NULL, NULL, node->module->compiled, LYS_GETNEXT_NOSTATECHECK);
6452 if (node != root) {
6453 LOGINT(set->ctx);
6454 }
6455#endif
6456 new_node = root;
6457
6458 /* node has a standard parent (it can equal the root, it's not the root yet since they are fake) */
6459 } else {
6460 new_type = LYXP_NODE_ELEM;
6461 }
6462
6463 assert((new_type == LYXP_NODE_ELEM) || ((new_type == root_type) && (new_node == root)));
6464
6465 idx = set_scnode_insert_node(set, new_node, new_type);
6466 if ((idx < orig_used) && (idx > i)) {
6467 set->val.scnodes[idx].in_ctx = 2;
6468 temp_ctx = 1;
6469 }
6470 }
6471
6472 if (temp_ctx) {
6473 for (i = 0; i < orig_used; ++i) {
6474 if (set->val.scnodes[i].in_ctx == 2) {
6475 set->val.scnodes[i].in_ctx = 1;
6476 }
6477 }
6478 }
6479
6480 return LY_SUCCESS;
6481}
6482
6483/**
6484 * @brief Move context @p set to the result of a comparison. Handles '=', '!=', '<=', '<', '>=', or '>'.
6485 * Result is LYXP_SET_BOOLEAN. Indirectly context position aware.
6486 *
6487 * @param[in,out] set1 Set to use for the result.
6488 * @param[in] set2 Set acting as the second operand for @p op.
6489 * @param[in] op Comparison operator to process.
6490 * @param[in] options XPath options.
6491 * @return LY_ERR
6492 */
6493static LY_ERR
6494moveto_op_comp(struct lyxp_set *set1, struct lyxp_set *set2, const char *op, int options)
6495{
6496 /*
6497 * NODE SET + NODE SET = NODE SET + STRING /(1 NODE SET) 2 STRING
6498 * NODE SET + STRING = STRING + STRING /1 STRING (2 STRING)
6499 * NODE SET + NUMBER = NUMBER + NUMBER /1 NUMBER (2 NUMBER)
6500 * NODE SET + BOOLEAN = BOOLEAN + BOOLEAN /1 BOOLEAN (2 BOOLEAN)
6501 * STRING + NODE SET = STRING + STRING /(1 STRING) 2 STRING
6502 * NUMBER + NODE SET = NUMBER + NUMBER /(1 NUMBER) 2 NUMBER
6503 * BOOLEAN + NODE SET = BOOLEAN + BOOLEAN /(1 BOOLEAN) 2 BOOLEAN
6504 *
6505 * '=' or '!='
6506 * BOOLEAN + BOOLEAN
6507 * BOOLEAN + STRING = BOOLEAN + BOOLEAN /(1 BOOLEAN) 2 BOOLEAN
6508 * BOOLEAN + NUMBER = BOOLEAN + BOOLEAN /(1 BOOLEAN) 2 BOOLEAN
6509 * STRING + BOOLEAN = BOOLEAN + BOOLEAN /1 BOOLEAN (2 BOOLEAN)
6510 * NUMBER + BOOLEAN = BOOLEAN + BOOLEAN /1 BOOLEAN (2 BOOLEAN)
6511 * NUMBER + NUMBER
6512 * NUMBER + STRING = NUMBER + NUMBER /(1 NUMBER) 2 NUMBER
6513 * STRING + NUMBER = NUMBER + NUMBER /1 NUMBER (2 NUMBER)
6514 * STRING + STRING
6515 *
6516 * '<=', '<', '>=', '>'
6517 * NUMBER + NUMBER
6518 * BOOLEAN + BOOLEAN = NUMBER + NUMBER /1 NUMBER, 2 NUMBER
6519 * BOOLEAN + NUMBER = NUMBER + NUMBER /1 NUMBER (2 NUMBER)
6520 * BOOLEAN + STRING = NUMBER + NUMBER /1 NUMBER, 2 NUMBER
6521 * NUMBER + STRING = NUMBER + NUMBER /(1 NUMBER) 2 NUMBER
6522 * STRING + STRING = NUMBER + NUMBER /1 NUMBER, 2 NUMBER
6523 * STRING + NUMBER = NUMBER + NUMBER /1 NUMBER (2 NUMBER)
6524 * NUMBER + BOOLEAN = NUMBER + NUMBER /(1 NUMBER) 2 NUMBER
6525 * STRING + BOOLEAN = NUMBER + NUMBER /(1 NUMBER) 2 NUMBER
6526 */
6527 struct lyxp_set iter1, iter2;
6528 int result;
6529 int64_t i;
6530 LY_ERR rc;
6531
6532 iter1.type = LYXP_SET_EMPTY;
6533
6534 /* empty node-sets are always false */
6535 if ((set1->type == LYXP_SET_EMPTY) || (set2->type == LYXP_SET_EMPTY)) {
6536 set_fill_boolean(set1, 0);
6537 return LY_SUCCESS;
6538 }
6539
6540 /* iterative evaluation with node-sets */
6541 if ((set1->type == LYXP_SET_NODE_SET) || (set2->type == LYXP_SET_NODE_SET)) {
6542 if (set1->type == LYXP_SET_NODE_SET) {
6543 for (i = 0; i < set1->used; ++i) {
6544 switch (set2->type) {
6545 case LYXP_SET_NUMBER:
6546 rc = set_comp_cast(&iter1, set1, LYXP_SET_NUMBER, i, options);
6547 break;
6548 case LYXP_SET_BOOLEAN:
6549 rc = set_comp_cast(&iter1, set1, LYXP_SET_BOOLEAN, i, options);
6550 break;
6551 default:
6552 rc = set_comp_cast(&iter1, set1, LYXP_SET_STRING, i, options);
6553 break;
6554 }
6555 LY_CHECK_RET(rc);
6556
6557 rc = moveto_op_comp(&iter1, set2, op, options);
6558 if (rc != LY_SUCCESS) {
6559 set_free_content(&iter1);
6560 return rc;
6561 }
6562
6563 /* lazy evaluation until true */
6564 if (iter1.val.bool) {
6565 set_fill_boolean(set1, 1);
6566 return LY_SUCCESS;
6567 }
6568 }
6569 } else {
6570 for (i = 0; i < set2->used; ++i) {
6571 switch (set1->type) {
6572 case LYXP_SET_NUMBER:
6573 rc = set_comp_cast(&iter2, set2, LYXP_SET_NUMBER, i, options);
6574 break;
6575 case LYXP_SET_BOOLEAN:
6576 rc = set_comp_cast(&iter2, set2, LYXP_SET_BOOLEAN, i, options);
6577 break;
6578 default:
6579 rc = set_comp_cast(&iter2, set2, LYXP_SET_STRING, i, options);
6580 break;
6581 }
6582 LY_CHECK_RET(rc);
6583
6584 set_fill_set(&iter1, set1);
6585
6586 rc = moveto_op_comp(&iter1, &iter2, op, options);
6587 if (rc != LY_SUCCESS) {
6588 set_free_content(&iter1);
6589 set_free_content(&iter2);
6590 return rc;
6591 }
6592 set_free_content(&iter2);
6593
6594 /* lazy evaluation until true */
6595 if (iter1.val.bool) {
6596 set_fill_boolean(set1, 1);
6597 return LY_SUCCESS;
6598 }
6599 }
6600 }
6601
6602 /* false for all nodes */
6603 set_fill_boolean(set1, 0);
6604 return LY_SUCCESS;
6605 }
6606
6607 /* first convert properly */
6608 if ((op[0] == '=') || (op[0] == '!')) {
6609 if ((set1->type == LYXP_SET_BOOLEAN) || (set2->type == LYXP_SET_BOOLEAN)) {
6610 lyxp_set_cast(set1, LYXP_SET_BOOLEAN, options);
6611 lyxp_set_cast(set2, LYXP_SET_BOOLEAN, options);
6612 } else if ((set1->type == LYXP_SET_NUMBER) || (set2->type == LYXP_SET_NUMBER)) {
6613 rc = lyxp_set_cast(set1, LYXP_SET_NUMBER, options);
6614 LY_CHECK_RET(rc);
6615 rc = lyxp_set_cast(set2, LYXP_SET_NUMBER, options);
6616 LY_CHECK_RET(rc);
6617 } /* else we have 2 strings */
6618 } else {
6619 rc = lyxp_set_cast(set1, LYXP_SET_NUMBER, options);
6620 LY_CHECK_RET(rc);
6621 rc = lyxp_set_cast(set2, LYXP_SET_NUMBER, options);
6622 LY_CHECK_RET(rc);
6623 }
6624
6625 assert(set1->type == set2->type);
6626
6627 /* compute result */
6628 if (op[0] == '=') {
6629 if (set1->type == LYXP_SET_BOOLEAN) {
6630 result = (set1->val.bool == set2->val.bool);
6631 } else if (set1->type == LYXP_SET_NUMBER) {
6632 result = (set1->val.num == set2->val.num);
6633 } else {
6634 assert(set1->type == LYXP_SET_STRING);
6635 result = strcmp(set1->val.str, set2->val.str);
6636 }
6637 } else if (op[0] == '!') {
6638 if (set1->type == LYXP_SET_BOOLEAN) {
6639 result = (set1->val.bool != set2->val.bool);
6640 } else if (set1->type == LYXP_SET_NUMBER) {
6641 result = (set1->val.num != set2->val.num);
6642 } else {
6643 assert(set1->type == LYXP_SET_STRING);
6644 result = strcmp(set1->val.str, set2->val.str);
6645 }
6646 } else {
6647 assert(set1->type == LYXP_SET_NUMBER);
6648 if (op[0] == '<') {
6649 if (op[1] == '=') {
6650 result = (set1->val.num <= set2->val.num);
6651 } else {
6652 result = (set1->val.num < set2->val.num);
6653 }
6654 } else {
6655 if (op[1] == '=') {
6656 result = (set1->val.num >= set2->val.num);
6657 } else {
6658 result = (set1->val.num > set2->val.num);
6659 }
6660 }
6661 }
6662
6663 /* assign result */
6664 if (result) {
6665 set_fill_boolean(set1, 1);
6666 } else {
6667 set_fill_boolean(set1, 0);
6668 }
6669
6670 return LY_SUCCESS;
6671}
6672
6673/**
6674 * @brief Move context @p set to the result of a basic operation. Handles '+', '-', unary '-', '*', 'div',
6675 * or 'mod'. Result is LYXP_SET_NUMBER. Indirectly context position aware.
6676 *
6677 * @param[in,out] set1 Set to use for the result.
6678 * @param[in] set2 Set acting as the second operand for @p op.
6679 * @param[in] op Operator to process.
6680 * @param[in] options XPath options.
6681 * @return LY_ERR
6682 */
6683static LY_ERR
6684moveto_op_math(struct lyxp_set *set1, struct lyxp_set *set2, const char *op, int options)
6685{
6686 LY_ERR rc;
6687
6688 /* unary '-' */
6689 if (!set2 && (op[0] == '-')) {
6690 rc = lyxp_set_cast(set1, LYXP_SET_NUMBER, options);
6691 LY_CHECK_RET(rc);
6692 set1->val.num *= -1;
6693 lyxp_set_free(set2);
6694 return LY_SUCCESS;
6695 }
6696
6697 assert(set1 && set2);
6698
6699 rc = lyxp_set_cast(set1, LYXP_SET_NUMBER, options);
6700 LY_CHECK_RET(rc);
6701 rc = lyxp_set_cast(set2, LYXP_SET_NUMBER, options);
6702 LY_CHECK_RET(rc);
6703
6704 switch (op[0]) {
6705 /* '+' */
6706 case '+':
6707 set1->val.num += set2->val.num;
6708 break;
6709
6710 /* '-' */
6711 case '-':
6712 set1->val.num -= set2->val.num;
6713 break;
6714
6715 /* '*' */
6716 case '*':
6717 set1->val.num *= set2->val.num;
6718 break;
6719
6720 /* 'div' */
6721 case 'd':
6722 set1->val.num /= set2->val.num;
6723 break;
6724
6725 /* 'mod' */
6726 case 'm':
6727 set1->val.num = ((long long)set1->val.num) % ((long long)set2->val.num);
6728 break;
6729
6730 default:
6731 LOGINT_RET(set1->ctx);
6732 }
6733
6734 return LY_SUCCESS;
6735}
6736
6737/*
6738 * eval functions
6739 *
6740 * They execute a parsed XPath expression on some data subtree.
6741 */
6742
6743/**
6744 * @brief Evaluate Literal. Logs directly on error.
6745 *
6746 * @param[in] exp Parsed XPath expression.
6747 * @param[in] exp_idx Position in the expression @p exp.
6748 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
6749 */
6750static void
6751eval_literal(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyxp_set *set)
6752{
6753 if (set) {
6754 if (exp->tok_len[*exp_idx] == 2) {
6755 set_fill_string(set, "", 0);
6756 } else {
6757 set_fill_string(set, &exp->expr[exp->tok_pos[*exp_idx] + 1], exp->tok_len[*exp_idx] - 2);
6758 }
6759 }
6760 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
6761 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
6762 ++(*exp_idx);
6763}
6764
6765/**
6766 * @brief Evaluate NodeTest. Logs directly on error.
6767 *
6768 * [6] NodeTest ::= NameTest | NodeType '(' ')'
6769 *
6770 * @param[in] exp Parsed XPath expression.
6771 * @param[in] exp_idx Position in the expression @p exp.
6772 * @param[in] attr_axis Whether to search attributes or standard nodes.
6773 * @param[in] all_desc Whether to search all the descendants or children only.
6774 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
6775 * @param[in] options XPath options.
6776 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
6777 */
6778static int
6779eval_node_test(struct lyxp_expr *exp, uint16_t *exp_idx, int attr_axis, int all_desc,
6780 struct lyxp_set *set, int options)
6781{
6782 int i;
6783 char *path;
6784 LY_ERR rc;
6785
6786 switch (exp->tokens[*exp_idx]) {
6787 case LYXP_TOKEN_NAMETEST:
6788 if (attr_axis) {
6789 if (set && (options & LYXP_SCNODE_ALL)) {
6790 set_scnode_clear_ctx(set);
6791 rc = LY_SUCCESS;
6792 } else {
6793 if (all_desc) {
6794 rc = moveto_attr_alldesc(set, &exp->expr[exp->tok_pos[*exp_idx]], exp->tok_len[*exp_idx], options);
6795 } else {
6796 rc = moveto_attr(set, &exp->expr[exp->tok_pos[*exp_idx]], exp->tok_len[*exp_idx], options);
6797 }
6798 }
6799 } else {
6800 if (all_desc) {
6801 if (set && (options & LYXP_SCNODE_ALL)) {
6802 rc = moveto_scnode_alldesc(set, &exp->expr[exp->tok_pos[*exp_idx]], exp->tok_len[*exp_idx], options);
6803 } else {
6804 rc = moveto_node_alldesc(set, &exp->expr[exp->tok_pos[*exp_idx]], exp->tok_len[*exp_idx], options);
6805 }
6806 } else {
6807 if (set && (options & LYXP_SCNODE_ALL)) {
6808 rc = moveto_scnode(set, &exp->expr[exp->tok_pos[*exp_idx]], exp->tok_len[*exp_idx], options);
6809 } else {
6810 rc = moveto_node(set, &exp->expr[exp->tok_pos[*exp_idx]], exp->tok_len[*exp_idx], options);
6811 }
6812 }
6813
6814 if ((rc == LY_SUCCESS) && set && (options & LYXP_SCNODE_ALL)) {
6815 for (i = set->used - 1; i > -1; --i) {
6816 if (set->val.scnodes[i].in_ctx) {
6817 break;
6818 }
6819 }
6820 if (i == -1) {
6821 path = lysc_path(set->ctx_scnode, LYSC_PATH_LOG, NULL, 0);
6822 LOGWRN(set->ctx, "Schema node \"%.*s\" not found (%.*s) with context node \"%s\".",
6823 exp->tok_len[*exp_idx], &exp->expr[exp->tok_pos[*exp_idx]],
6824 exp->tok_pos[*exp_idx] + exp->tok_len[*exp_idx], exp->expr, path);
6825 free(path);
6826 }
6827 }
6828 }
6829 LY_CHECK_RET(rc);
6830
6831 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
6832 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
6833 ++(*exp_idx);
6834 break;
6835
6836 case LYXP_TOKEN_NODETYPE:
6837 if (set) {
6838 assert(exp->tok_len[*exp_idx] == 4);
6839 if (set->type == LYXP_SET_SCNODE_SET) {
6840 set_scnode_clear_ctx(set);
6841 /* just for the debug message underneath */
6842 set = NULL;
6843 } else {
6844 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "node", 4)) {
6845 rc = xpath_node(NULL, 0, set, options);
6846 LY_CHECK_RET(rc);
6847 } else {
6848 assert(!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "text", 4));
6849 rc = xpath_text(NULL, 0, set, options);
6850 LY_CHECK_RET(rc);
6851 }
6852 }
6853 }
6854 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
6855 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
6856 ++(*exp_idx);
6857
6858 /* '(' */
6859 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR1);
6860 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
6861 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
6862 ++(*exp_idx);
6863
6864 /* ')' */
6865 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR2);
6866 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
6867 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
6868 ++(*exp_idx);
6869 break;
6870
6871 default:
Michal Vasko02a77382019-09-12 11:47:35 +02006872 LOGINT_RET(set ? set->ctx : NULL);
Michal Vasko03ff5a72019-09-11 13:49:33 +02006873 }
6874
6875 return LY_SUCCESS;
6876}
6877
6878/**
6879 * @brief Evaluate Predicate. Logs directly on error.
6880 *
6881 * [7] Predicate ::= '[' Expr ']'
6882 *
6883 * @param[in] exp Parsed XPath expression.
6884 * @param[in] exp_idx Position in the expression @p exp.
6885 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
6886 * @param[in] options XPath options.
6887 * @param[in] parent_pos_pred Whether parent predicate was a positional one.
6888 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
6889 */
6890static LY_ERR
6891eval_predicate(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyxp_set *set, int options, int parent_pos_pred)
6892{
6893 LY_ERR rc;
Michal Vasko57eab132019-09-24 11:46:26 +02006894 uint16_t i, orig_exp;
Michal Vasko03ff5a72019-09-11 13:49:33 +02006895 uint32_t orig_pos, orig_size, pred_in_ctx;
6896 struct lyxp_set set2;
6897 struct lyd_node *orig_parent;
6898
6899 /* '[' */
6900 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
6901 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
6902 ++(*exp_idx);
6903
6904 if (!set) {
6905only_parse:
6906 rc = eval_expr_select(exp, exp_idx, 0, NULL, options);
6907 LY_CHECK_RET(rc);
6908 } else if (set->type == LYXP_SET_NODE_SET) {
6909 /* we (possibly) need the set sorted, it can affect the result (if the predicate result is a number) */
6910 assert(!set_sort(set, options));
6911
6912 /* empty set, nothing to evaluate */
6913 if (!set->used) {
6914 goto only_parse;
6915 }
6916
6917 orig_exp = *exp_idx;
Michal Vasko03ff5a72019-09-11 13:49:33 +02006918 orig_pos = 0;
6919 orig_size = set->used;
6920 orig_parent = NULL;
6921 for (i = 0; i < set->used; ) {
6922 set_init(&set2, set);
6923 set_insert_node(&set2, set->val.nodes[i].node, set->val.nodes[i].pos, set->val.nodes[i].type, 0);
6924 /* remember the node context position for position() and context size for last(),
6925 * predicates should always be evaluated with respect to the child axis (since we do
6926 * not support explicit axes) so we assign positions based on their parents */
6927 if (parent_pos_pred && ((struct lyd_node *)set->val.nodes[i].node->parent != orig_parent)) {
6928 orig_parent = (struct lyd_node *)set->val.nodes[i].node->parent;
6929 orig_pos = 1;
6930 } else {
6931 ++orig_pos;
6932 }
6933
6934 set2.ctx_pos = orig_pos;
6935 set2.ctx_size = orig_size;
6936 *exp_idx = orig_exp;
6937
6938 rc = eval_expr_select(exp, exp_idx, 0, &set2, options);
6939 if (rc != LY_SUCCESS) {
6940 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
6941 return rc;
6942 }
6943
6944 /* number is a position */
6945 if (set2.type == LYXP_SET_NUMBER) {
6946 if ((long long)set2.val.num == orig_pos) {
6947 set2.val.num = 1;
6948 } else {
6949 set2.val.num = 0;
6950 }
6951 }
6952 lyxp_set_cast(&set2, LYXP_SET_BOOLEAN, options);
6953
6954 /* predicate satisfied or not? */
Michal Vasko57eab132019-09-24 11:46:26 +02006955 if (!set2.val.bool) {
6956 set_remove_node_null(set, i);
Michal Vasko03ff5a72019-09-11 13:49:33 +02006957 }
6958 }
Michal Vasko57eab132019-09-24 11:46:26 +02006959 set_remove_nodes_null(set);
Michal Vasko03ff5a72019-09-11 13:49:33 +02006960
6961 } else if (set->type == LYXP_SET_SCNODE_SET) {
6962 for (i = 0; i < set->used; ++i) {
6963 if (set->val.scnodes[i].in_ctx == 1) {
6964 /* there is a currently-valid node */
6965 break;
6966 }
6967 }
6968 /* empty set, nothing to evaluate */
6969 if (i == set->used) {
6970 goto only_parse;
6971 }
6972
6973 orig_exp = *exp_idx;
6974
Michal Vasko03ff5a72019-09-11 13:49:33 +02006975 /* set special in_ctx to all the valid snodes */
6976 pred_in_ctx = set_scnode_new_in_ctx(set);
6977
6978 /* use the valid snodes one-by-one */
6979 for (i = 0; i < set->used; ++i) {
6980 if (set->val.scnodes[i].in_ctx != pred_in_ctx) {
6981 continue;
6982 }
6983 set->val.scnodes[i].in_ctx = 1;
6984
6985 *exp_idx = orig_exp;
6986
6987 rc = eval_expr_select(exp, exp_idx, 0, set, options);
6988 LY_CHECK_RET(rc);
6989
6990 set->val.scnodes[i].in_ctx = pred_in_ctx;
6991 }
6992
6993 /* restore the state as it was before the predicate */
6994 for (i = 0; i < set->used; ++i) {
6995 if (set->val.scnodes[i].in_ctx == 1) {
6996 set->val.scnodes[i].in_ctx = 0;
6997 } else if (set->val.scnodes[i].in_ctx == pred_in_ctx) {
6998 set->val.scnodes[i].in_ctx = 1;
6999 }
7000 }
7001
7002 } else {
7003 set2.type = LYXP_SET_EMPTY;
7004 set_fill_set(&set2, set);
7005
7006 rc = eval_expr_select(exp, exp_idx, 0, &set2, options);
7007 if (rc != LY_SUCCESS) {
7008 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
7009 return rc;
7010 }
7011
7012 lyxp_set_cast(&set2, LYXP_SET_BOOLEAN, options);
7013 if (!set2.val.bool) {
7014 lyxp_set_cast(set, LYXP_SET_EMPTY, options);
7015 }
7016 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
7017 }
7018
7019 /* ']' */
7020 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_BRACK2);
7021 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7022 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7023 ++(*exp_idx);
7024
7025 return LY_SUCCESS;
7026}
7027
7028/**
7029 * @brief Evaluate RelativeLocationPath. Logs directly on error.
7030 *
7031 * [4] RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step
7032 * [5] Step ::= '@'? NodeTest Predicate* | '.' | '..'
7033 *
7034 * @param[in] exp Parsed XPath expression.
7035 * @param[in] exp_idx Position in the expression @p exp.
7036 * @param[in] all_desc Whether to search all the descendants or children only.
7037 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7038 * @param[in] options XPath options.
7039 * @return LY_ERR (YL_EINCOMPLETE on unresolved when)
7040 */
7041static LY_ERR
7042eval_relative_location_path(struct lyxp_expr *exp, uint16_t *exp_idx, int all_desc, struct lyxp_set *set, int options)
7043{
7044 int attr_axis;
7045 LY_ERR rc;
7046
7047 goto step;
7048 do {
7049 /* evaluate '/' or '//' */
7050 if (exp->tok_len[*exp_idx] == 1) {
7051 all_desc = 0;
7052 } else {
7053 assert(exp->tok_len[*exp_idx] == 2);
7054 all_desc = 1;
7055 }
7056 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7057 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7058 ++(*exp_idx);
7059
7060step:
7061 /* Step */
7062 attr_axis = 0;
7063 switch (exp->tokens[*exp_idx]) {
7064 case LYXP_TOKEN_DOT:
7065 /* evaluate '.' */
7066 if (set && (options & LYXP_SCNODE_ALL)) {
7067 rc = moveto_scnode_self(set, all_desc, options);
7068 } else {
7069 rc = moveto_self(set, all_desc, options);
7070 }
7071 LY_CHECK_RET(rc);
7072 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7073 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7074 ++(*exp_idx);
7075 break;
7076
7077 case LYXP_TOKEN_DDOT:
7078 /* evaluate '..' */
7079 if (set && (options & LYXP_SCNODE_ALL)) {
7080 rc = moveto_scnode_parent(set, all_desc, options);
7081 } else {
7082 rc = moveto_parent(set, all_desc, options);
7083 }
7084 LY_CHECK_RET(rc);
7085 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7086 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7087 ++(*exp_idx);
7088 break;
7089
7090 case LYXP_TOKEN_AT:
7091 /* evaluate '@' */
7092 attr_axis = 1;
7093 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7094 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7095 ++(*exp_idx);
7096
7097 /* fall through */
7098 case LYXP_TOKEN_NAMETEST:
7099 case LYXP_TOKEN_NODETYPE:
7100 rc = eval_node_test(exp, exp_idx, attr_axis, all_desc, set, options);
7101 LY_CHECK_RET(rc);
7102
7103 while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_BRACK1)) {
7104 rc = eval_predicate(exp, exp_idx, set, options, 1);
7105 LY_CHECK_RET(rc);
7106 }
7107 break;
7108
7109 default:
Michal Vasko02a77382019-09-12 11:47:35 +02007110 LOGINT_RET(set ? set->ctx : NULL);
Michal Vasko03ff5a72019-09-11 13:49:33 +02007111 }
7112 } while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_PATH));
7113
7114 return LY_SUCCESS;
7115}
7116
7117/**
7118 * @brief Evaluate AbsoluteLocationPath. Logs directly on error.
7119 *
7120 * [3] AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath
7121 *
7122 * @param[in] exp Parsed XPath expression.
7123 * @param[in] exp_idx Position in the expression @p exp.
7124 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7125 * @param[in] options XPath options.
7126 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7127 */
7128static LY_ERR
7129eval_absolute_location_path(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyxp_set *set, int options)
7130{
7131 int all_desc;
7132 LY_ERR rc;
7133
7134 if (set) {
7135 /* no matter what tokens follow, we need to be at the root */
7136 moveto_root(set, options);
7137 }
7138
7139 /* '/' RelativeLocationPath? */
7140 if (exp->tok_len[*exp_idx] == 1) {
7141 /* evaluate '/' - deferred */
7142 all_desc = 0;
7143 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7144 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7145 ++(*exp_idx);
7146
Michal Vasko4b9e1052019-09-13 11:25:37 +02007147 if (exp_check_token(set ? set->ctx : NULL, exp, *exp_idx, LYXP_TOKEN_NONE, 0)) {
Michal Vasko03ff5a72019-09-11 13:49:33 +02007148 return LY_SUCCESS;
7149 }
7150 switch (exp->tokens[*exp_idx]) {
7151 case LYXP_TOKEN_DOT:
7152 case LYXP_TOKEN_DDOT:
7153 case LYXP_TOKEN_AT:
7154 case LYXP_TOKEN_NAMETEST:
7155 case LYXP_TOKEN_NODETYPE:
7156 rc = eval_relative_location_path(exp, exp_idx, all_desc, set, options);
7157 LY_CHECK_RET(rc);
7158 break;
7159 default:
7160 break;
7161 }
7162
7163 /* '//' RelativeLocationPath */
7164 } else {
7165 /* evaluate '//' - deferred so as not to waste memory by remembering all the nodes */
7166 all_desc = 1;
7167 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7168 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7169 ++(*exp_idx);
7170
7171 rc = eval_relative_location_path(exp, exp_idx, all_desc, set, options);
7172 LY_CHECK_RET(rc);
7173 }
7174
7175 return LY_SUCCESS;
7176}
7177
7178/**
7179 * @brief Evaluate FunctionCall. Logs directly on error.
7180 *
7181 * [9] FunctionCall ::= FunctionName '(' ( Expr ( ',' Expr )* )? ')'
7182 *
7183 * @param[in] exp Parsed XPath expression.
7184 * @param[in] exp_idx Position in the expression @p exp.
7185 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7186 * @param[in] options XPath options.
7187 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7188 */
7189static LY_ERR
7190eval_function_call(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyxp_set *set, int options)
7191{
7192 LY_ERR rc;
7193 LY_ERR (*xpath_func)(struct lyxp_set **, uint16_t, struct lyxp_set *, int) = NULL;
7194 uint16_t arg_count = 0, i, func_exp = *exp_idx;
7195 struct lyxp_set **args = NULL, **args_aux;
7196
7197 if (set) {
7198 /* FunctionName */
7199 switch (exp->tok_len[*exp_idx]) {
7200 case 3:
7201 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "not", 3)) {
7202 xpath_func = &xpath_not;
7203 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "sum", 3)) {
7204 xpath_func = &xpath_sum;
7205 }
7206 break;
7207 case 4:
7208 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "lang", 4)) {
7209 xpath_func = &xpath_lang;
7210 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "last", 4)) {
7211 xpath_func = &xpath_last;
7212 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "name", 4)) {
7213 xpath_func = &xpath_name;
7214 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "true", 4)) {
7215 xpath_func = &xpath_true;
7216 }
7217 break;
7218 case 5:
7219 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "count", 5)) {
7220 xpath_func = &xpath_count;
7221 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "false", 5)) {
7222 xpath_func = &xpath_false;
7223 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "floor", 5)) {
7224 xpath_func = &xpath_floor;
7225 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "round", 5)) {
7226 xpath_func = &xpath_round;
7227 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "deref", 5)) {
7228 xpath_func = &xpath_deref;
7229 }
7230 break;
7231 case 6:
7232 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "concat", 6)) {
7233 xpath_func = &xpath_concat;
7234 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "number", 6)) {
7235 xpath_func = &xpath_number;
7236 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "string", 6)) {
7237 xpath_func = &xpath_string;
7238 }
7239 break;
7240 case 7:
7241 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "boolean", 7)) {
7242 xpath_func = &xpath_boolean;
7243 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "ceiling", 7)) {
7244 xpath_func = &xpath_ceiling;
7245 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "current", 7)) {
7246 xpath_func = &xpath_current;
7247 }
7248 break;
7249 case 8:
7250 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "contains", 8)) {
7251 xpath_func = &xpath_contains;
7252 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "position", 8)) {
7253 xpath_func = &xpath_position;
7254 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "re-match", 8)) {
7255 xpath_func = &xpath_re_match;
7256 }
7257 break;
7258 case 9:
7259 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "substring", 9)) {
7260 xpath_func = &xpath_substring;
7261 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "translate", 9)) {
7262 xpath_func = &xpath_translate;
7263 }
7264 break;
7265 case 10:
7266 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "local-name", 10)) {
7267 xpath_func = &xpath_local_name;
7268 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "enum-value", 10)) {
7269 xpath_func = &xpath_enum_value;
7270 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "bit-is-set", 10)) {
7271 xpath_func = &xpath_bit_is_set;
7272 }
7273 break;
7274 case 11:
7275 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "starts-with", 11)) {
7276 xpath_func = &xpath_starts_with;
7277 }
7278 break;
7279 case 12:
7280 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "derived-from", 12)) {
7281 xpath_func = &xpath_derived_from;
7282 }
7283 break;
7284 case 13:
7285 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "namespace-uri", 13)) {
7286 xpath_func = &xpath_namespace_uri;
7287 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "string-length", 13)) {
7288 xpath_func = &xpath_string_length;
7289 }
7290 break;
7291 case 15:
7292 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "normalize-space", 15)) {
7293 xpath_func = &xpath_normalize_space;
7294 } else if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "substring-after", 15)) {
7295 xpath_func = &xpath_substring_after;
7296 }
7297 break;
7298 case 16:
7299 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "substring-before", 16)) {
7300 xpath_func = &xpath_substring_before;
7301 }
7302 break;
7303 case 20:
7304 if (!strncmp(&exp->expr[exp->tok_pos[*exp_idx]], "derived-from-or-self", 20)) {
7305 xpath_func = &xpath_derived_from_or_self;
7306 }
7307 break;
7308 }
7309
7310 if (!xpath_func) {
7311 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INTOK, "Unknown", &exp->expr[exp->tok_pos[*exp_idx]]);
7312 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]]);
7313 return LY_EVALID;
7314 }
7315 }
7316
7317 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7318 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7319 ++(*exp_idx);
7320
7321 /* '(' */
7322 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR1);
7323 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7324 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7325 ++(*exp_idx);
7326
7327 /* ( Expr ( ',' Expr )* )? */
7328 if (exp->tokens[*exp_idx] != LYXP_TOKEN_PAR2) {
7329 if (set) {
7330 args = malloc(sizeof *args);
7331 LY_CHECK_ERR_GOTO(!args, LOGMEM(set->ctx); rc = LY_EMEM, cleanup);
7332 arg_count = 1;
7333 args[0] = set_copy(set);
7334 if (!args[0]) {
7335 rc = LY_EMEM;
7336 goto cleanup;
7337 }
7338
7339 rc = eval_expr_select(exp, exp_idx, 0, args[0], options);
7340 LY_CHECK_GOTO(rc, cleanup);
7341 } else {
7342 rc = eval_expr_select(exp, exp_idx, 0, NULL, options);
7343 LY_CHECK_GOTO(rc, cleanup);
7344 }
7345 }
7346 while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_COMMA)) {
7347 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7348 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7349 ++(*exp_idx);
7350
7351 if (set) {
7352 ++arg_count;
7353 args_aux = realloc(args, arg_count * sizeof *args);
7354 LY_CHECK_ERR_GOTO(!args_aux, arg_count--; LOGMEM(set->ctx); rc = LY_EMEM, cleanup);
7355 args = args_aux;
7356 args[arg_count - 1] = set_copy(set);
7357 if (!args[arg_count - 1]) {
7358 rc = LY_EMEM;
7359 goto cleanup;
7360 }
7361
7362 rc = eval_expr_select(exp, exp_idx, 0, args[arg_count - 1], options);
7363 LY_CHECK_GOTO(rc, cleanup);
7364 } else {
7365 rc = eval_expr_select(exp, exp_idx, 0, NULL, options);
7366 LY_CHECK_GOTO(rc, cleanup);
7367 }
7368 }
7369
7370 /* ')' */
7371 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR2);
7372 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7373 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7374 ++(*exp_idx);
7375
7376 if (set) {
7377 /* evaluate function */
7378 rc = xpath_func(args, arg_count, set, options);
7379
7380 if (options & LYXP_SCNODE_ALL) {
7381 if (rc == LY_EINVAL) {
7382 /* some validation warning TODO log everything immediately? */
7383 LOGWRN(set->ctx, "Previous warning generated by XPath function \"%.*s\".",
7384 (exp->tok_pos[*exp_idx - 1] - exp->tok_pos[func_exp]) + 1, &exp->expr[exp->tok_pos[func_exp]]);
7385 rc = LY_SUCCESS;
7386 }
7387
7388 /* merge all nodes from arg evaluations */
7389 for (i = 0; i < arg_count; ++i) {
7390 set_scnode_clear_ctx(args[i]);
7391 set_scnode_merge(set, args[i]);
7392 }
7393 }
7394 } else {
7395 rc = LY_SUCCESS;
7396 }
7397
7398cleanup:
7399 for (i = 0; i < arg_count; ++i) {
7400 lyxp_set_free(args[i]);
7401 }
7402 free(args);
7403
7404 return rc;
7405}
7406
7407/**
7408 * @brief Evaluate Number. Logs directly on error.
7409 *
7410 * @param[in] ctx Context for errors.
7411 * @param[in] exp Parsed XPath expression.
7412 * @param[in] exp_idx Position in the expression @p exp.
7413 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7414 * @return LY_ERR
7415 */
7416static LY_ERR
7417eval_number(struct ly_ctx *ctx, struct lyxp_expr *exp, uint16_t *exp_idx, struct lyxp_set *set)
7418{
7419 long double num;
7420 char *endptr;
7421
7422 if (set) {
7423 errno = 0;
7424 num = strtold(&exp->expr[exp->tok_pos[*exp_idx]], &endptr);
7425 if (errno) {
7426 LOGVAL(ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INTOK, "Unknown", &exp->expr[exp->tok_pos[*exp_idx]]);
7427 LOGVAL(ctx, LY_VLOG_LYD, set->ctx_node, LYVE_XPATH, "Failed to convert \"%.*s\" into a long double (%s).",
7428 exp->tok_len[*exp_idx], &exp->expr[exp->tok_pos[*exp_idx]], strerror(errno));
7429 return LY_EVALID;
7430 } else if (endptr - &exp->expr[exp->tok_pos[*exp_idx]] != exp->tok_len[*exp_idx]) {
7431 LOGVAL(ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INTOK, "Unknown", &exp->expr[exp->tok_pos[*exp_idx]]);
7432 LOGVAL(ctx, LY_VLOG_LYD, set->ctx_node, LYVE_XPATH, "Failed to convert \"%.*s\" into a long double.",
7433 exp->tok_len[*exp_idx], &exp->expr[exp->tok_pos[*exp_idx]]);
7434 return LY_EVALID;
7435 }
7436
7437 set_fill_number(set, num);
7438 }
7439
7440 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7441 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7442 ++(*exp_idx);
7443 return LY_SUCCESS;
7444}
7445
7446/**
7447 * @brief Evaluate PathExpr. Logs directly on error.
7448 *
7449 * [10] PathExpr ::= LocationPath | PrimaryExpr Predicate*
7450 * | PrimaryExpr Predicate* '/' RelativeLocationPath
7451 * | PrimaryExpr Predicate* '//' RelativeLocationPath
7452 * [2] LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
7453 * [8] PrimaryExpr ::= '(' Expr ')' | Literal | Number | FunctionCall
7454 *
7455 * @param[in] exp Parsed XPath expression.
7456 * @param[in] exp_idx Position in the expression @p exp.
7457 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7458 * @param[in] options XPath options.
7459 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7460 */
7461static LY_ERR
7462eval_path_expr(struct lyxp_expr *exp, uint16_t *exp_idx, struct lyxp_set *set, int options)
7463{
7464 int all_desc, parent_pos_pred;
7465 LY_ERR rc;
7466
7467 switch (exp->tokens[*exp_idx]) {
7468 case LYXP_TOKEN_PAR1:
7469 /* '(' Expr ')' */
7470
7471 /* '(' */
7472 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7473 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7474 ++(*exp_idx);
7475
7476 /* Expr */
7477 rc = eval_expr_select(exp, exp_idx, 0, set, options);
7478 LY_CHECK_RET(rc);
7479
7480 /* ')' */
7481 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_PAR2);
7482 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7483 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7484 ++(*exp_idx);
7485
7486 parent_pos_pred = 0;
7487 goto predicate;
7488
7489 case LYXP_TOKEN_DOT:
7490 case LYXP_TOKEN_DDOT:
7491 case LYXP_TOKEN_AT:
7492 case LYXP_TOKEN_NAMETEST:
7493 case LYXP_TOKEN_NODETYPE:
7494 /* RelativeLocationPath */
7495 rc = eval_relative_location_path(exp, exp_idx, 0, set, options);
7496 LY_CHECK_RET(rc);
7497 break;
7498
7499 case LYXP_TOKEN_FUNCNAME:
7500 /* FunctionCall */
7501 if (!set) {
7502 rc = eval_function_call(exp, exp_idx, NULL, options);
7503 } else {
7504 rc = eval_function_call(exp, exp_idx, set, options);
7505 }
7506 LY_CHECK_RET(rc);
7507
7508 parent_pos_pred = 1;
7509 goto predicate;
7510
7511 case LYXP_TOKEN_OPERATOR_PATH:
7512 /* AbsoluteLocationPath */
7513 rc = eval_absolute_location_path(exp, exp_idx, set, options);
7514 LY_CHECK_RET(rc);
7515 break;
7516
7517 case LYXP_TOKEN_LITERAL:
7518 /* Literal */
7519 if (!set || (options & LYXP_SCNODE_ALL)) {
7520 if (set) {
7521 set_scnode_clear_ctx(set);
7522 }
7523 eval_literal(exp, exp_idx, NULL);
7524 } else {
7525 eval_literal(exp, exp_idx, set);
7526 }
7527
7528 parent_pos_pred = 1;
7529 goto predicate;
7530
7531 case LYXP_TOKEN_NUMBER:
7532 /* Number */
7533 if (!set || (options & LYXP_SCNODE_ALL)) {
7534 if (set) {
7535 set_scnode_clear_ctx(set);
7536 }
Michal Vasko02a77382019-09-12 11:47:35 +02007537 rc = eval_number(NULL, exp, exp_idx, NULL);
Michal Vasko03ff5a72019-09-11 13:49:33 +02007538 } else {
7539 rc = eval_number(set->ctx, exp, exp_idx, set);
7540 }
7541 LY_CHECK_RET(rc);
7542
7543 parent_pos_pred = 1;
7544 goto predicate;
7545
7546 default:
7547 LOGVAL(set->ctx, LY_VLOG_LYD, set->ctx_node, LY_VCODE_XP_INTOK, print_token(exp->tokens[*exp_idx]),
7548 &exp->expr[exp->tok_pos[*exp_idx]]);
7549 return LY_EVALID;
7550 }
7551
7552 return LY_SUCCESS;
7553
7554predicate:
7555 /* Predicate* */
7556 while ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_BRACK1)) {
7557 rc = eval_predicate(exp, exp_idx, set, options, parent_pos_pred);
7558 LY_CHECK_RET(rc);
7559 }
7560
7561 /* ('/' or '//') RelativeLocationPath */
7562 if ((exp->used > *exp_idx) && (exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_PATH)) {
7563
7564 /* evaluate '/' or '//' */
7565 if (exp->tok_len[*exp_idx] == 1) {
7566 all_desc = 0;
7567 } else {
7568 assert(exp->tok_len[*exp_idx] == 2);
7569 all_desc = 1;
7570 }
7571
7572 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7573 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7574 ++(*exp_idx);
7575
7576 rc = eval_relative_location_path(exp, exp_idx, all_desc, set, options);
7577 LY_CHECK_RET(rc);
7578 }
7579
7580 return LY_SUCCESS;
7581}
7582
7583/**
7584 * @brief Evaluate UnionExpr. Logs directly on error.
7585 *
7586 * [18] UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
7587 *
7588 * @param[in] exp Parsed XPath expression.
7589 * @param[in] exp_idx Position in the expression @p exp.
7590 * @param[in] repeat How many times this expression is repeated.
7591 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7592 * @param[in] options XPath options.
7593 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7594 */
7595static LY_ERR
7596eval_union_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyxp_set *set, int options)
7597{
7598 LY_ERR rc = LY_SUCCESS;
7599 struct lyxp_set orig_set, set2;
7600 uint16_t i;
7601
7602 assert(repeat);
7603
7604 set_init(&orig_set, set);
7605 set_init(&set2, set);
7606
7607 set_fill_set(&orig_set, set);
7608
7609 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_UNION, set, options);
7610 LY_CHECK_GOTO(rc, cleanup);
7611
7612 /* ('|' PathExpr)* */
7613 for (i = 0; i < repeat; ++i) {
7614 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_UNI);
7615 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7616 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7617 ++(*exp_idx);
7618
7619 if (!set) {
7620 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_UNION, NULL, options);
7621 LY_CHECK_GOTO(rc, cleanup);
7622 continue;
7623 }
7624
7625 set_fill_set(&set2, &orig_set);
7626 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_UNION, &set2, options);
7627 LY_CHECK_GOTO(rc, cleanup);
7628
7629 /* eval */
7630 if (options & LYXP_SCNODE_ALL) {
7631 set_scnode_merge(set, &set2);
7632 } else {
7633 rc = moveto_union(set, &set2, options);
7634 LY_CHECK_GOTO(rc, cleanup);
7635 }
7636 }
7637
7638cleanup:
7639 lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, options);
7640 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
7641 return rc;
7642}
7643
7644/**
7645 * @brief Evaluate UnaryExpr. Logs directly on error.
7646 *
7647 * [17] UnaryExpr ::= UnionExpr | '-' UnaryExpr
7648 *
7649 * @param[in] exp Parsed XPath expression.
7650 * @param[in] exp_idx Position in the expression @p exp.
7651 * @param[in] repeat How many times this expression is repeated.
7652 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7653 * @param[in] options XPath options.
7654 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7655 */
7656static LY_ERR
7657eval_unary_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyxp_set *set, int options)
7658{
7659 LY_ERR rc;
7660 uint16_t this_op, i;
7661
7662 assert(repeat);
7663
7664 /* ('-')+ */
7665 this_op = *exp_idx;
7666 for (i = 0; i < repeat; ++i) {
7667 assert(!exp_check_token(set->ctx, exp, *exp_idx, LYXP_TOKEN_OPERATOR_MATH, 0) && (exp->expr[exp->tok_pos[*exp_idx]] == '-'));
7668
7669 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7670 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7671 ++(*exp_idx);
7672 }
7673
7674 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_UNARY, set, options);
7675 LY_CHECK_RET(rc);
7676
7677 if (set && (repeat % 2)) {
7678 if (options & LYXP_SCNODE_ALL) {
7679 warn_operands(set->ctx, set, NULL, 1, exp->expr, exp->tok_pos[this_op]);
7680 } else {
7681 rc = moveto_op_math(set, NULL, &exp->expr[exp->tok_pos[this_op]], options);
7682 LY_CHECK_RET(rc);
7683 }
7684 }
7685
7686 return LY_SUCCESS;
7687}
7688
7689/**
7690 * @brief Evaluate MultiplicativeExpr. Logs directly on error.
7691 *
7692 * [16] MultiplicativeExpr ::= UnaryExpr
7693 * | MultiplicativeExpr '*' UnaryExpr
7694 * | MultiplicativeExpr 'div' UnaryExpr
7695 * | MultiplicativeExpr 'mod' UnaryExpr
7696 *
7697 * @param[in] exp Parsed XPath expression.
7698 * @param[in] exp_idx Position in the expression @p exp.
7699 * @param[in] repeat How many times this expression is repeated.
7700 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7701 * @param[in] options XPath options.
7702 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7703 */
7704static LY_ERR
7705eval_multiplicative_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyxp_set *set, int options)
7706{
7707 LY_ERR rc;
7708 uint16_t this_op;
7709 struct lyxp_set orig_set, set2;
7710 uint16_t i;
7711
7712 assert(repeat);
7713
7714 set_init(&orig_set, set);
7715 set_init(&set2, set);
7716
7717 set_fill_set(&orig_set, set);
7718
7719 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_MULTIPLICATIVE, set, options);
7720 LY_CHECK_GOTO(rc, cleanup);
7721
7722 /* ('*' / 'div' / 'mod' UnaryExpr)* */
7723 for (i = 0; i < repeat; ++i) {
7724 this_op = *exp_idx;
7725
7726 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_MATH);
7727 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7728 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7729 ++(*exp_idx);
7730
7731 if (!set) {
7732 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_MULTIPLICATIVE, NULL, options);
7733 LY_CHECK_GOTO(rc, cleanup);
7734 continue;
7735 }
7736
7737 set_fill_set(&set2, &orig_set);
7738 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_MULTIPLICATIVE, &set2, options);
7739 LY_CHECK_GOTO(rc, cleanup);
7740
7741 /* eval */
7742 if (options & LYXP_SCNODE_ALL) {
7743 warn_operands(set->ctx, set, &set2, 1, exp->expr, exp->tok_pos[this_op - 1]);
7744 set_scnode_merge(set, &set2);
7745 set_scnode_clear_ctx(set);
7746 } else {
7747 rc = moveto_op_math(set, &set2, &exp->expr[exp->tok_pos[this_op]], options);
7748 LY_CHECK_GOTO(rc, cleanup);
7749 }
7750 }
7751
7752cleanup:
7753 lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, options);
7754 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
7755 return rc;
7756}
7757
7758/**
7759 * @brief Evaluate AdditiveExpr. Logs directly on error.
7760 *
7761 * [15] AdditiveExpr ::= MultiplicativeExpr
7762 * | AdditiveExpr '+' MultiplicativeExpr
7763 * | AdditiveExpr '-' MultiplicativeExpr
7764 *
7765 * @param[in] exp Parsed XPath expression.
7766 * @param[in] exp_idx Position in the expression @p exp.
7767 * @param[in] repeat How many times this expression is repeated.
7768 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7769 * @param[in] options XPath options.
7770 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7771 */
7772static LY_ERR
7773eval_additive_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyxp_set *set, int options)
7774{
7775 LY_ERR rc;
7776 uint16_t this_op;
7777 struct lyxp_set orig_set, set2;
7778 uint16_t i;
7779
7780 assert(repeat);
7781
7782 set_init(&orig_set, set);
7783 set_init(&set2, set);
7784
7785 set_fill_set(&orig_set, set);
7786
7787 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_ADDITIVE, set, options);
7788 LY_CHECK_GOTO(rc, cleanup);
7789
7790 /* ('+' / '-' MultiplicativeExpr)* */
7791 for (i = 0; i < repeat; ++i) {
7792 this_op = *exp_idx;
7793
7794 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_MATH);
7795 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7796 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7797 ++(*exp_idx);
7798
7799 if (!set) {
7800 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_ADDITIVE, NULL, options);
7801 LY_CHECK_GOTO(rc, cleanup);
7802 continue;
7803 }
7804
7805 set_fill_set(&set2, &orig_set);
7806 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_ADDITIVE, &set2, options);
7807 LY_CHECK_GOTO(rc, cleanup);
7808
7809 /* eval */
7810 if (options & LYXP_SCNODE_ALL) {
7811 warn_operands(set->ctx, set, &set2, 1, exp->expr, exp->tok_pos[this_op - 1]);
7812 set_scnode_merge(set, &set2);
7813 set_scnode_clear_ctx(set);
7814 } else {
7815 rc = moveto_op_math(set, &set2, &exp->expr[exp->tok_pos[this_op]], options);
7816 LY_CHECK_GOTO(rc, cleanup);
7817 }
7818 }
7819
7820cleanup:
7821 lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, options);
7822 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
7823 return rc;
7824}
7825
7826/**
7827 * @brief Evaluate RelationalExpr. Logs directly on error.
7828 *
7829 * [14] RelationalExpr ::= AdditiveExpr
7830 * | RelationalExpr '<' AdditiveExpr
7831 * | RelationalExpr '>' AdditiveExpr
7832 * | RelationalExpr '<=' AdditiveExpr
7833 * | RelationalExpr '>=' AdditiveExpr
7834 *
7835 * @param[in] exp Parsed XPath expression.
7836 * @param[in] exp_idx Position in the expression @p exp.
7837 * @param[in] repeat How many times this expression is repeated.
7838 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7839 * @param[in] options XPath options.
7840 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7841 */
7842static LY_ERR
7843eval_relational_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyxp_set *set, int options)
7844{
7845 LY_ERR rc;
7846 uint16_t this_op;
7847 struct lyxp_set orig_set, set2;
7848 uint16_t i;
7849
7850 assert(repeat);
7851
7852 set_init(&orig_set, set);
7853 set_init(&set2, set);
7854
7855 set_fill_set(&orig_set, set);
7856
7857 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_RELATIONAL, set, options);
7858 LY_CHECK_GOTO(rc, cleanup);
7859
7860 /* ('<' / '>' / '<=' / '>=' AdditiveExpr)* */
7861 for (i = 0; i < repeat; ++i) {
7862 this_op = *exp_idx;
7863
7864 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_COMP);
7865 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7866 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7867 ++(*exp_idx);
7868
7869 if (!set) {
7870 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_RELATIONAL, NULL, options);
7871 LY_CHECK_GOTO(rc, cleanup);
7872 continue;
7873 }
7874
7875 set_fill_set(&set2, &orig_set);
7876 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_RELATIONAL, &set2, options);
7877 LY_CHECK_GOTO(rc, cleanup);
7878
7879 /* eval */
7880 if (options & LYXP_SCNODE_ALL) {
7881 warn_operands(set->ctx, set, &set2, 1, exp->expr, exp->tok_pos[this_op - 1]);
7882 set_scnode_merge(set, &set2);
7883 set_scnode_clear_ctx(set);
7884 } else {
7885 rc = moveto_op_comp(set, &set2, &exp->expr[exp->tok_pos[this_op]], options);
7886 LY_CHECK_GOTO(rc, cleanup);
7887 }
7888 }
7889
7890cleanup:
7891 lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, options);
7892 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
7893 return rc;
7894}
7895
7896/**
7897 * @brief Evaluate EqualityExpr. Logs directly on error.
7898 *
7899 * [13] EqualityExpr ::= RelationalExpr | EqualityExpr '=' RelationalExpr
7900 * | EqualityExpr '!=' RelationalExpr
7901 *
7902 * @param[in] exp Parsed XPath expression.
7903 * @param[in] exp_idx Position in the expression @p exp.
7904 * @param[in] repeat How many times this expression is repeated.
7905 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7906 * @param[in] options XPath options.
7907 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7908 */
7909static LY_ERR
7910eval_equality_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyxp_set *set, int options)
7911{
7912 LY_ERR rc;
7913 uint16_t this_op;
7914 struct lyxp_set orig_set, set2;
7915 uint16_t i;
7916
7917 assert(repeat);
7918
7919 set_init(&orig_set, set);
7920 set_init(&set2, set);
7921
7922 set_fill_set(&orig_set, set);
7923
7924 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_EQUALITY, set, options);
7925 LY_CHECK_GOTO(rc, cleanup);
7926
7927 /* ('=' / '!=' RelationalExpr)* */
7928 for (i = 0; i < repeat; ++i) {
7929 this_op = *exp_idx;
7930
7931 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_COMP);
7932 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (set ? "parsed" : "skipped"),
7933 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
7934 ++(*exp_idx);
7935
7936 if (!set) {
7937 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_EQUALITY, NULL, options);
7938 LY_CHECK_GOTO(rc, cleanup);
7939 continue;
7940 }
7941
7942 set_fill_set(&set2, &orig_set);
7943 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_EQUALITY, &set2, options);
7944 LY_CHECK_GOTO(rc, cleanup);
7945
7946 /* eval */
7947 if (options & LYXP_SCNODE_ALL) {
7948 warn_operands(set->ctx, set, &set2, 0, exp->expr, exp->tok_pos[this_op - 1]);
7949 warn_equality_value(exp, set, *exp_idx - 1, this_op - 1, *exp_idx - 1);
7950 warn_equality_value(exp, &set2, this_op - 1, this_op - 1, *exp_idx - 1);
7951 set_scnode_merge(set, &set2);
7952 set_scnode_clear_ctx(set);
7953 } else {
7954 /* special handling of evaluations of identityref comparisons, always compare prefixed identites */
7955 if ((set->type == LYXP_SET_NODE_SET) && (set->val.nodes[0].node->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST))
7956 && (((struct lysc_node_leaf *)set->val.nodes[0].node->schema)->type->basetype == LY_TYPE_IDENT)) {
7957 /* left operand is identityref */
7958 if ((set2.type == LYXP_SET_STRING) && !strchr(set2.val.str, ':')) {
7959 /* missing prefix in the right operand */
7960 set2.val.str = ly_realloc(set2.val.str, strlen(set->local_mod->name) + 1 + strlen(set2.val.str) + 1);
7961 if (!set2.val.str) {
7962 goto cleanup;
7963 }
7964
7965 memmove(set2.val.str + strlen(set->local_mod->name) + 1, set2.val.str, strlen(set2.val.str) + 1);
7966 memcpy(set2.val.str, set->local_mod->name, strlen(set->local_mod->name));
7967 set2.val.str[strlen(set->local_mod->name)] = ':';
7968 }
7969 }
7970
7971 rc = moveto_op_comp(set, &set2, &exp->expr[exp->tok_pos[this_op]], options);
7972 LY_CHECK_GOTO(rc, cleanup);
7973 }
7974 }
7975
7976cleanup:
7977 lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, options);
7978 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
7979 return rc;
7980}
7981
7982/**
7983 * @brief Evaluate AndExpr. Logs directly on error.
7984 *
7985 * [12] AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
7986 *
7987 * @param[in] exp Parsed XPath expression.
7988 * @param[in] exp_idx Position in the expression @p exp.
7989 * @param[in] repeat How many times this expression is repeated.
7990 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
7991 * @param[in] options XPath options.
7992 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
7993 */
7994static LY_ERR
7995eval_and_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyxp_set *set, int options)
7996{
7997 LY_ERR rc;
7998 struct lyxp_set orig_set, set2;
7999 uint16_t i;
8000
8001 assert(repeat);
8002
8003 set_init(&orig_set, set);
8004 set_init(&set2, set);
8005
8006 set_fill_set(&orig_set, set);
8007
8008 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_AND, set, options);
8009 LY_CHECK_GOTO(rc, cleanup);
8010
8011 /* cast to boolean, we know that will be the final result */
8012 if (set && (options & LYXP_SCNODE_ALL)) {
8013 set_scnode_clear_ctx(set);
8014 } else {
8015 lyxp_set_cast(set, LYXP_SET_BOOLEAN, options);
8016 }
8017
8018 /* ('and' EqualityExpr)* */
8019 for (i = 0; i < repeat; ++i) {
8020 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_LOG);
8021 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (!set || !set->val.bool ? "skipped" : "parsed"),
8022 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
8023 ++(*exp_idx);
8024
8025 /* lazy evaluation */
8026 if (!set || ((set->type == LYXP_SET_BOOLEAN) && !set->val.bool)) {
8027 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_AND, NULL, options);
8028 LY_CHECK_GOTO(rc, cleanup);
8029 continue;
8030 }
8031
8032 set_fill_set(&set2, &orig_set);
8033 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_AND, &set2, options);
8034 LY_CHECK_GOTO(rc, cleanup);
8035
8036 /* eval - just get boolean value actually */
8037 if (set->type == LYXP_SET_SCNODE_SET) {
8038 set_scnode_clear_ctx(&set2);
8039 set_scnode_merge(set, &set2);
8040 } else {
8041 lyxp_set_cast(&set2, LYXP_SET_BOOLEAN, options);
8042 set_fill_set(set, &set2);
8043 }
8044 }
8045
8046cleanup:
8047 lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, options);
8048 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
8049 return rc;
8050}
8051
8052/**
8053 * @brief Evaluate OrExpr. Logs directly on error.
8054 *
8055 * [11] OrExpr ::= AndExpr | OrExpr 'or' AndExpr
8056 *
8057 * @param[in] exp Parsed XPath expression.
8058 * @param[in] exp_idx Position in the expression @p exp.
8059 * @param[in] repeat How many times this expression is repeated.
8060 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8061 * @param[in] options XPath options.
8062 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
8063 */
8064static LY_ERR
8065eval_or_expr(struct lyxp_expr *exp, uint16_t *exp_idx, uint16_t repeat, struct lyxp_set *set, int options)
8066{
8067 LY_ERR rc;
8068 struct lyxp_set orig_set, set2;
8069 uint16_t i;
8070
8071 assert(repeat);
8072
8073 set_init(&orig_set, set);
8074 set_init(&set2, set);
8075
8076 set_fill_set(&orig_set, set);
8077
8078 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_OR, set, options);
8079 LY_CHECK_GOTO(rc, cleanup);
8080
8081 /* cast to boolean, we know that will be the final result */
8082 if (set && (options & LYXP_SCNODE_ALL)) {
8083 set_scnode_clear_ctx(set);
8084 } else {
8085 lyxp_set_cast(set, LYXP_SET_BOOLEAN, options);
8086 }
8087
8088 /* ('or' AndExpr)* */
8089 for (i = 0; i < repeat; ++i) {
8090 assert(exp->tokens[*exp_idx] == LYXP_TOKEN_OPERATOR_LOG);
8091 LOGDBG(LY_LDGXPATH, "%-27s %s %s[%u]", __func__, (!set || set->val.bool ? "skipped" : "parsed"),
8092 print_token(exp->tokens[*exp_idx]), exp->tok_pos[*exp_idx]);
8093 ++(*exp_idx);
8094
8095 /* lazy evaluation */
8096 if (!set || ((set->type == LYXP_SET_BOOLEAN) && set->val.bool)) {
8097 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_OR, NULL, options);
8098 LY_CHECK_GOTO(rc, cleanup);
8099 continue;
8100 }
8101
8102 set_fill_set(&set2, &orig_set);
8103 /* expr_type cound have been LYXP_EXPR_NONE in all these later calls (except for the first one),
8104 * but it does not matter */
8105 rc = eval_expr_select(exp, exp_idx, LYXP_EXPR_OR, &set2, options);
8106 LY_CHECK_GOTO(rc, cleanup);
8107
8108 /* eval - just get boolean value actually */
8109 if (set->type == LYXP_SET_SCNODE_SET) {
8110 set_scnode_clear_ctx(&set2);
8111 set_scnode_merge(set, &set2);
8112 } else {
8113 lyxp_set_cast(&set2, LYXP_SET_BOOLEAN, options);
8114 set_fill_set(set, &set2);
8115 }
8116 }
8117
8118cleanup:
8119 lyxp_set_cast(&orig_set, LYXP_SET_EMPTY, options);
8120 lyxp_set_cast(&set2, LYXP_SET_EMPTY, options);
8121 return rc;
8122}
8123
8124/**
8125 * @brief Decide what expression is at the pointer @p exp_idx and evaluate it accordingly.
8126 *
8127 * @param[in] exp Parsed XPath expression.
8128 * @param[in] exp_idx Position in the expression @p exp.
8129 * @param[in] etype Expression type to evaluate.
8130 * @param[in,out] set Context and result set. On NULL the rule is only parsed.
8131 * @param[in] options XPath options.
8132 * @return LY_ERR (LY_EINCOMPLETE on unresolved when)
8133 */
8134static LY_ERR
8135eval_expr_select(struct lyxp_expr *exp, uint16_t *exp_idx, enum lyxp_expr_type etype, struct lyxp_set *set, int options)
8136{
8137 uint16_t i, count;
8138 enum lyxp_expr_type next_etype;
8139 LY_ERR rc;
8140
8141 /* process operator repeats */
8142 if (!exp->repeat[*exp_idx]) {
8143 next_etype = LYXP_EXPR_NONE;
8144 } else {
8145 /* find etype repeat */
8146 for (i = 0; exp->repeat[*exp_idx][i] > etype; ++i);
8147
8148 /* select one-priority lower because etype expression called us */
8149 if (i) {
8150 next_etype = exp->repeat[*exp_idx][i - 1];
8151 /* count repeats for that expression */
8152 for (count = 0; i && exp->repeat[*exp_idx][i - 1] == next_etype; ++count, --i);
8153 } else {
8154 next_etype = LYXP_EXPR_NONE;
8155 }
8156 }
8157
8158 /* decide what expression are we parsing based on the repeat */
8159 switch (next_etype) {
8160 case LYXP_EXPR_OR:
8161 rc = eval_or_expr(exp, exp_idx, count, set, options);
8162 break;
8163 case LYXP_EXPR_AND:
8164 rc = eval_and_expr(exp, exp_idx, count, set, options);
8165 break;
8166 case LYXP_EXPR_EQUALITY:
8167 rc = eval_equality_expr(exp, exp_idx, count, set, options);
8168 break;
8169 case LYXP_EXPR_RELATIONAL:
8170 rc = eval_relational_expr(exp, exp_idx, count, set, options);
8171 break;
8172 case LYXP_EXPR_ADDITIVE:
8173 rc = eval_additive_expr(exp, exp_idx, count, set, options);
8174 break;
8175 case LYXP_EXPR_MULTIPLICATIVE:
8176 rc = eval_multiplicative_expr(exp, exp_idx, count, set, options);
8177 break;
8178 case LYXP_EXPR_UNARY:
8179 rc = eval_unary_expr(exp, exp_idx, count, set, options);
8180 break;
8181 case LYXP_EXPR_UNION:
8182 rc = eval_union_expr(exp, exp_idx, count, set, options);
8183 break;
8184 case LYXP_EXPR_NONE:
8185 rc = eval_path_expr(exp, exp_idx, set, options);
8186 break;
8187 default:
8188 LOGINT_RET(set->ctx);
8189 }
8190
8191 return rc;
8192}
8193
8194LY_ERR
8195lyxp_eval(const char *expr, LYD_FORMAT format, const struct lys_module *local_mod, const struct lyd_node *ctx_node,
8196 enum lyxp_node_type ctx_node_type, const struct lyd_node **trees, struct lyxp_set *set, int options)
8197{
8198 struct ly_ctx *ctx;
8199 struct lyxp_expr *exp;
8200 uint16_t exp_idx = 0;
8201 LY_ERR rc;
8202
8203 LY_CHECK_ARG_RET(NULL, !expr || !local_mod || !ctx_node || !set, LY_EINVAL);
8204
8205 ctx = local_mod->ctx;
8206
8207 exp = lyxp_expr_parse(ctx, expr);
8208 if (!exp) {
8209 return LY_EINVAL;
8210 }
8211
8212 /* prepare set for evaluation */
8213 exp_idx = 0;
8214 memset(set, 0, sizeof *set);
8215 set->type = LYXP_SET_EMPTY;
8216 set_insert_node(set, (struct lyd_node *)ctx_node, 0, ctx_node_type, options);
8217 set->ctx = ctx;
8218 set->ctx_node = ctx_node;
8219 set->local_mod = local_mod;
8220 set->trees = trees;
8221 set->format = format;
8222
8223 /* evaluate */
8224 rc = eval_expr_select(exp, &exp_idx, 0, set, options);
8225 if (rc != LY_SUCCESS) {
8226 lyxp_set_cast(set, LYXP_SET_EMPTY, options);
8227 }
8228
8229 lyxp_expr_free(ctx, exp);
8230 return rc;
8231}
8232
8233#if 0
8234
8235/* full xml printing of set elements, not used currently */
8236
8237void
8238lyxp_set_print_xml(FILE *f, struct lyxp_set *set)
8239{
8240 uint32_t i;
8241 char *str_num;
8242 struct lyout out;
8243
8244 memset(&out, 0, sizeof out);
8245
8246 out.type = LYOUT_STREAM;
8247 out.method.f = f;
8248
8249 switch (set->type) {
8250 case LYXP_SET_EMPTY:
8251 ly_print(&out, "Empty XPath set\n\n");
8252 break;
8253 case LYXP_SET_BOOLEAN:
8254 ly_print(&out, "Boolean XPath set:\n");
8255 ly_print(&out, "%s\n\n", set->value.bool ? "true" : "false");
8256 break;
8257 case LYXP_SET_STRING:
8258 ly_print(&out, "String XPath set:\n");
8259 ly_print(&out, "\"%s\"\n\n", set->value.str);
8260 break;
8261 case LYXP_SET_NUMBER:
8262 ly_print(&out, "Number XPath set:\n");
8263
8264 if (isnan(set->value.num)) {
8265 str_num = strdup("NaN");
8266 } else if ((set->value.num == 0) || (set->value.num == -0.0f)) {
8267 str_num = strdup("0");
8268 } else if (isinf(set->value.num) && !signbit(set->value.num)) {
8269 str_num = strdup("Infinity");
8270 } else if (isinf(set->value.num) && signbit(set->value.num)) {
8271 str_num = strdup("-Infinity");
8272 } else if ((long long)set->value.num == set->value.num) {
8273 if (asprintf(&str_num, "%lld", (long long)set->value.num) == -1) {
8274 str_num = NULL;
8275 }
8276 } else {
8277 if (asprintf(&str_num, "%03.1Lf", set->value.num) == -1) {
8278 str_num = NULL;
8279 }
8280 }
8281 if (!str_num) {
8282 LOGMEM;
8283 return;
8284 }
8285 ly_print(&out, "%s\n\n", str_num);
8286 free(str_num);
8287 break;
8288 case LYXP_SET_NODE_SET:
8289 ly_print(&out, "Node XPath set:\n");
8290
8291 for (i = 0; i < set->used; ++i) {
8292 ly_print(&out, "%d. ", i + 1);
8293 switch (set->node_type[i]) {
8294 case LYXP_NODE_ROOT_ALL:
8295 ly_print(&out, "ROOT all\n\n");
8296 break;
8297 case LYXP_NODE_ROOT_CONFIG:
8298 ly_print(&out, "ROOT config\n\n");
8299 break;
8300 case LYXP_NODE_ROOT_STATE:
8301 ly_print(&out, "ROOT state\n\n");
8302 break;
8303 case LYXP_NODE_ROOT_NOTIF:
8304 ly_print(&out, "ROOT notification \"%s\"\n\n", set->value.nodes[i]->schema->name);
8305 break;
8306 case LYXP_NODE_ROOT_RPC:
8307 ly_print(&out, "ROOT rpc \"%s\"\n\n", set->value.nodes[i]->schema->name);
8308 break;
8309 case LYXP_NODE_ROOT_OUTPUT:
8310 ly_print(&out, "ROOT output \"%s\"\n\n", set->value.nodes[i]->schema->name);
8311 break;
8312 case LYXP_NODE_ELEM:
8313 ly_print(&out, "ELEM \"%s\"\n", set->value.nodes[i]->schema->name);
8314 xml_print_node(&out, 1, set->value.nodes[i], 1, LYP_FORMAT);
8315 ly_print(&out, "\n");
8316 break;
8317 case LYXP_NODE_TEXT:
8318 ly_print(&out, "TEXT \"%s\"\n\n", ((struct lyd_node_leaf_list *)set->value.nodes[i])->value_str);
8319 break;
8320 case LYXP_NODE_ATTR:
8321 ly_print(&out, "ATTR \"%s\" = \"%s\"\n\n", set->value.attrs[i]->name, set->value.attrs[i]->value);
8322 break;
8323 }
8324 }
8325 break;
8326 }
8327}
8328
8329#endif
8330
8331LY_ERR
8332lyxp_set_cast(struct lyxp_set *set, enum lyxp_set_type target, int options)
8333{
8334 long double num;
8335 char *str;
8336 LY_ERR rc;
8337
8338 if (!set || (set->type == target)) {
8339 return LY_SUCCESS;
8340 }
8341
8342 /* it's not possible to convert anything into a node set */
8343 assert((target != LYXP_SET_NODE_SET) && ((set->type != LYXP_SET_SCNODE_SET) || (target == LYXP_SET_EMPTY)));
8344
8345 if (set->type == LYXP_SET_SCNODE_SET) {
8346 set_free_content(set);
8347 return LY_EINVAL;
8348 }
8349
8350 /* to STRING */
8351 if ((target == LYXP_SET_STRING) || ((target == LYXP_SET_NUMBER)
8352 && ((set->type == LYXP_SET_NODE_SET) || (set->type == LYXP_SET_EMPTY)))) {
8353 switch (set->type) {
8354 case LYXP_SET_NUMBER:
8355 if (isnan(set->val.num)) {
8356 set->val.str = strdup("NaN");
8357 LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), -1);
8358 } else if ((set->val.num == 0) || (set->val.num == -0.0f)) {
8359 set->val.str = strdup("0");
8360 LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), -1);
8361 } else if (isinf(set->val.num) && !signbit(set->val.num)) {
8362 set->val.str = strdup("Infinity");
8363 LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), -1);
8364 } else if (isinf(set->val.num) && signbit(set->val.num)) {
8365 set->val.str = strdup("-Infinity");
8366 LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), -1);
8367 } else if ((long long)set->val.num == set->val.num) {
8368 if (asprintf(&str, "%lld", (long long)set->val.num) == -1) {
8369 LOGMEM_RET(set->ctx);
8370 }
8371 set->val.str = str;
8372 } else {
8373 if (asprintf(&str, "%03.1Lf", set->val.num) == -1) {
8374 LOGMEM_RET(set->ctx);
8375 }
8376 set->val.str = str;
8377 }
8378 break;
8379 case LYXP_SET_BOOLEAN:
8380 if (set->val.bool) {
8381 set->val.str = strdup("true");
8382 } else {
8383 set->val.str = strdup("false");
8384 }
8385 LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), LY_EMEM);
8386 break;
8387 case LYXP_SET_NODE_SET:
8388 assert(set->used);
8389
8390 /* we need the set sorted, it affects the result */
8391 assert(!set_sort(set, options));
8392
8393 rc = cast_node_set_to_string(set, options, &str);
8394 LY_CHECK_RET(rc);
8395 set_free_content(set);
8396 set->val.str = str;
8397 break;
8398 case LYXP_SET_EMPTY:
8399 set->val.str = strdup("");
8400 LY_CHECK_ERR_RET(!set->val.str, LOGMEM(set->ctx), LY_EMEM);
8401 break;
8402 default:
8403 LOGINT_RET(set->ctx);
8404 }
8405 set->type = LYXP_SET_STRING;
8406 }
8407
8408 /* to NUMBER */
8409 if (target == LYXP_SET_NUMBER) {
8410 switch (set->type) {
8411 case LYXP_SET_STRING:
8412 num = cast_string_to_number(set->val.str);
8413 set_free_content(set);
8414 set->val.num = num;
8415 break;
8416 case LYXP_SET_BOOLEAN:
8417 if (set->val.bool) {
8418 set->val.num = 1;
8419 } else {
8420 set->val.num = 0;
8421 }
8422 break;
8423 default:
8424 LOGINT_RET(set->ctx);
8425 }
8426 set->type = LYXP_SET_NUMBER;
8427 }
8428
8429 /* to BOOLEAN */
8430 if (target == LYXP_SET_BOOLEAN) {
8431 switch (set->type) {
8432 case LYXP_SET_NUMBER:
8433 if ((set->val.num == 0) || (set->val.num == -0.0f) || isnan(set->val.num)) {
8434 set->val.bool = 0;
8435 } else {
8436 set->val.bool = 1;
8437 }
8438 break;
8439 case LYXP_SET_STRING:
8440 if (set->val.str[0]) {
8441 set_free_content(set);
8442 set->val.bool = 1;
8443 } else {
8444 set_free_content(set);
8445 set->val.bool = 0;
8446 }
8447 break;
8448 case LYXP_SET_NODE_SET:
8449 set_free_content(set);
8450
8451 assert(set->used);
8452 set->val.bool = 1;
8453 break;
8454 case LYXP_SET_EMPTY:
8455 set->val.bool = 0;
8456 break;
8457 default:
8458 LOGINT_RET(set->ctx);
8459 }
8460 set->type = LYXP_SET_BOOLEAN;
8461 }
8462
8463 /* to EMPTY */
8464 if (target == LYXP_SET_EMPTY) {
8465 set_free_content(set);
8466 set->type = LYXP_SET_EMPTY;
8467 }
8468
8469 return LY_SUCCESS;
8470}
8471
8472LY_ERR
8473lyxp_atomize(struct lyxp_expr *exp, LYD_FORMAT format, const struct lys_module *local_mod, const struct lysc_node *ctx_scnode,
8474 enum lyxp_node_type ctx_scnode_type, struct lyxp_set *set, int options)
8475{
8476 struct ly_ctx *ctx;
8477 uint16_t exp_idx = 0;
8478
8479 LY_CHECK_ARG_RET(NULL, !exp || !local_mod || !ctx_scnode || !set, LY_EINVAL);
8480
8481 ctx = local_mod->ctx;
8482
8483 /* prepare set for evaluation */
8484 exp_idx = 0;
8485 memset(set, 0, sizeof *set);
8486 set->type = LYXP_SET_SCNODE_SET;
8487 set_scnode_insert_node(set, ctx_scnode, ctx_scnode_type);
8488 set->ctx = ctx;
8489 set->ctx_scnode = ctx_scnode;
8490 set->local_mod = local_mod;
8491 set->format = format;
8492
8493 /* evaluate */
8494 return eval_expr_select(exp, &exp_idx, 0, set, options);
8495}
8496
8497LY_ERR
8498lyxp_node_atomize(const struct lysc_node *node, struct lyxp_set *set, int set_ext_dep_flags)
8499{
8500 struct ly_ctx *ctx;
8501 struct lysc_ctx cctx;
8502 struct lysc_node *parent, *elem;
8503 struct lyxp_set tmp_set;
8504 uint32_t i, j;
8505 int opts;
8506 struct lysc_when **when = NULL;
8507 struct lysc_must *musts = NULL;
8508 LY_ERR rc;
8509
8510 ctx = node->module->ctx;
8511
8512 memset(&tmp_set, 0, sizeof tmp_set);
8513 memset(set, 0, sizeof *set);
8514 set->ctx = ctx;
8515
8516 /* check if we will be traversing RPC output */
8517 for (parent = (struct lysc_node *)node; parent && (parent->nodetype != LYS_ACTION); parent = parent->parent);
8518 if (parent && (node->flags & LYS_CONFIG_R)) {
8519 opts = LYXP_SCNODE_OUTPUT;
8520 } else {
8521 opts = LYXP_SCNODE_SCHEMA;
8522 }
8523
8524 switch (node->nodetype) {
8525 case LYS_CONTAINER:
8526 when = ((struct lysc_node_container *)node)->when;
8527 musts = ((struct lysc_node_container *)node)->musts;
8528 break;
8529 case LYS_CHOICE:
8530 when = ((struct lysc_node_choice *)node)->when;
8531 break;
8532 case LYS_LEAF:
8533 when = ((struct lysc_node_leaf *)node)->when;
8534 musts = ((struct lysc_node_leaf *)node)->musts;
8535 break;
8536 case LYS_LEAFLIST:
8537 when = ((struct lysc_node_leaflist *)node)->when;
8538 musts = ((struct lysc_node_leaflist *)node)->musts;
8539 break;
8540 case LYS_LIST:
8541 when = ((struct lysc_node_list *)node)->when;
8542 musts = ((struct lysc_node_list *)node)->musts;
8543 break;
8544 case LYS_ANYXML:
8545 case LYS_ANYDATA:
8546 when = ((struct lysc_node_anydata *)node)->when;
8547 musts = ((struct lysc_node_anydata *)node)->musts;
8548 break;
8549 case LYS_CASE:
8550 when = ((struct lysc_node_case *)node)->when;
8551 break;
8552 case LYS_NOTIF:
8553 musts = ((struct lysc_notif *)node)->musts;
8554 break;
8555 default:
8556 /* nothing to check */
8557 break;
8558 }
8559
8560 if (set_ext_dep_flags) {
8561 /* find operation if in one, used later */
8562 for (parent = (struct lysc_node *)node;
8563 parent && !(parent->nodetype & (LYS_ACTION | LYS_NOTIF));
8564 parent = parent->parent);
8565 }
8566
8567 /* check "when" */
8568 LY_ARRAY_FOR(when, i) {
8569 rc = lyxp_atomize(when[i]->cond, LYD_UNKNOWN, when[i]->module, when[i]->context, LYXP_NODE_ELEM, &tmp_set, opts);
8570 if (rc != LY_SUCCESS) {
8571 free(tmp_set.val.scnodes);
8572 LOGVAL(ctx, LY_VLOG_LYS, when[i]->context, LYVE_SEMANTICS, "Invalid when condition \"%s\".", when[i]->cond->expr);
8573 goto error;
8574 } else {
8575 if (set_ext_dep_flags) {
8576 for (j = 0; j < tmp_set.used; ++j) {
8577 /* skip roots'n'stuff */
8578 if (tmp_set.val.scnodes[j].type == LYXP_NODE_ELEM) {
8579 /* XPath expression cannot reference "lower" status than the node that has the definition */
8580 cctx.ctx = ctx;
8581 lysc_path((struct lysc_node *)node, LYSC_PATH_LOG, cctx.path, LYSC_CTX_BUFSIZE);
8582 rc = lysc_check_status(&cctx, node->flags, node->module, node->name, tmp_set.val.scnodes[j].scnode->flags,
8583 tmp_set.val.scnodes[j].scnode->module, tmp_set.val.scnodes[j].scnode->name);
8584 LY_CHECK_GOTO(rc, error);
8585
8586 if (parent) {
8587 for (elem = tmp_set.val.scnodes[j].scnode; elem && (elem != parent); elem = elem->parent);
8588 if (!elem) {
8589 /* not in node's RPC or notification subtree, set the correct dep flag */
8590 when[i]->flags |= LYS_XPATH_DEP;
8591 ((struct lysc_node *)node)->flags |= LYS_XPATH_DEP;
8592 }
8593 }
8594 }
8595 }
8596 }
8597 set_scnode_merge(set, &tmp_set);
8598 memset(&tmp_set, 0, sizeof tmp_set);
8599 }
8600 }
8601
8602 /* check "must" */
8603 LY_ARRAY_FOR(musts, i) {
8604 rc = lyxp_atomize(musts[i].cond, LYD_UNKNOWN, musts[i].module, node, LYXP_NODE_ELEM, &tmp_set, opts);
8605 if (rc != LY_SUCCESS) {
8606 free(tmp_set.val.scnodes);
8607 LOGVAL(ctx, LY_VLOG_LYS, node, LYVE_SEMANTICS, "Invalid must restriction \"%s\".", musts[i].cond->expr);
8608 goto error;
8609 } else {
8610 if (set_ext_dep_flags) {
8611 for (j = 0; j < tmp_set.used; ++j) {
8612 /* skip roots'n'stuff */
8613 if (tmp_set.val.scnodes[j].type == LYXP_NODE_ELEM) {
8614 /* XPath expression cannot reference "lower" status than the node that has the definition */
8615 cctx.ctx = ctx;
8616 lysc_path((struct lysc_node *)node, LYSC_PATH_LOG, cctx.path, LYSC_CTX_BUFSIZE);
8617 rc = lysc_check_status(&cctx, node->flags, node->module, node->name, tmp_set.val.scnodes[j].scnode->flags,
8618 tmp_set.val.scnodes[j].scnode->module, tmp_set.val.scnodes[j].scnode->name);
8619 LY_CHECK_GOTO(rc, error);
8620
8621 if (parent) {
8622 for (elem = tmp_set.val.scnodes[j].scnode; elem && (elem != parent); elem = elem->parent);
8623 if (!elem) {
8624 /* not in node's RPC or notification subtree, set the correct dep flag */
8625 musts[i].flags |= LYS_XPATH_DEP;
8626 ((struct lysc_node *)node)->flags |= LYS_XPATH_DEP;
8627 }
8628 }
8629 }
8630 }
8631 }
8632 set_scnode_merge(set, &tmp_set);
8633 memset(&tmp_set, 0, sizeof tmp_set);
8634 }
8635 }
8636
8637 return LY_SUCCESS;
8638
8639error:
8640 free(set->val.scnodes);
8641 memset(set, 0, sizeof *set);
8642 return rc;
8643}