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