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