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