1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright 2016, Olivier MATZ <zer0@droids-corp.org>
11 #include <ecoli_log.h>
12 #include <ecoli_malloc.h>
13 #include <ecoli_test.h>
14 #include <ecoli_strvec.h>
15 #include <ecoli_node.h>
16 #include <ecoli_parse.h>
17 #include <ecoli_complete.h>
18 #include <ecoli_node_re.h>
20 EC_LOG_TYPE_REGISTER(node_re);
29 ec_node_re_parse(const struct ec_node *gen_node,
30 struct ec_parse *state,
31 const struct ec_strvec *strvec)
33 struct ec_node_re *node = (struct ec_node_re *)gen_node;
39 if (ec_strvec_len(strvec) == 0)
40 return EC_PARSE_NOMATCH;
42 str = ec_strvec_val(strvec, 0);
43 if (regexec(&node->re, str, 1, &pos, 0) != 0)
44 return EC_PARSE_NOMATCH;
45 if (pos.rm_so != 0 || pos.rm_eo != (int)strlen(str))
46 return EC_PARSE_NOMATCH;
51 static void ec_node_re_free_priv(struct ec_node *gen_node)
53 struct ec_node_re *node = (struct ec_node_re *)gen_node;
55 if (node->re_str != NULL) {
56 ec_free(node->re_str);
61 static struct ec_node_type ec_node_re_type = {
63 .parse = ec_node_re_parse,
64 .complete = ec_node_complete_unknown,
65 .size = sizeof(struct ec_node_re),
66 .free_priv = ec_node_re_free_priv,
69 EC_NODE_TYPE_REGISTER(ec_node_re_type);
71 int ec_node_re_set_regexp(struct ec_node *gen_node, const char *str)
73 struct ec_node_re *node = (struct ec_node_re *)gen_node;
74 char *str_copy = NULL;
78 EC_CHECK_ARG(str != NULL, -1, EINVAL);
80 str_copy = ec_strdup(str);
84 ret = regcomp(&re, str_copy, REG_EXTENDED);
86 if (ret == REG_ESPACE)
93 if (node->re_str != NULL) {
94 ec_free(node->re_str);
97 node->re_str = str_copy;
107 struct ec_node *ec_node_re(const char *id, const char *re_str)
109 struct ec_node *gen_node = NULL;
111 gen_node = __ec_node(&ec_node_re_type, id);
112 if (gen_node == NULL)
115 if (ec_node_re_set_regexp(gen_node, re_str) < 0)
121 ec_node_free(gen_node);
125 /* LCOV_EXCL_START */
126 static int ec_node_re_testcase(void)
128 struct ec_node *node;
131 node = ec_node_re(EC_NO_ID, "fo+|bar");
133 EC_LOG(EC_LOG_ERR, "cannot create node\n");
136 testres |= EC_TEST_CHECK_PARSE(node, 1, "foo");
137 testres |= EC_TEST_CHECK_PARSE(node, 1, "foo", "bar");
138 testres |= EC_TEST_CHECK_PARSE(node, 1, "bar");
139 testres |= EC_TEST_CHECK_PARSE(node, -1, "foobar");
140 testres |= EC_TEST_CHECK_PARSE(node, -1, " foo");
141 testres |= EC_TEST_CHECK_PARSE(node, -1, "");
148 static struct ec_test ec_node_re_test = {
150 .test = ec_node_re_testcase,
153 EC_TEST_REGISTER(ec_node_re_test);