xref: /third_party/ltp/include/tst_bool_expr.h (revision f08c3bdf)
1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * Copyright (c) 2020 Cyril Hrubis <chrubis@suse.cz>
4 */
5
6#ifndef TST_BOOL_EXPR_H__
7#define TST_BOOL_EXPR_H__
8
9enum tst_op {
10	TST_OP_NOT,
11	TST_OP_AND,
12	TST_OP_OR,
13	TST_OP_VAR,
14	/* Used only internally */
15	TST_OP_LPAR,
16	TST_OP_RPAR,
17};
18
19struct tst_expr_tok {
20	enum tst_op op;
21	const char *tok;
22	size_t tok_len;
23	struct tst_expr_tok *next;
24	const void *priv;
25};
26
27struct tst_expr {
28	struct tst_expr_tok *rpn;
29	struct tst_expr_tok buf[];
30};
31
32/*
33 * Parses an boolean expression and returns a simplified RPN version.
34 *
35 * If expression is not valid the call prints error into stderr and returns
36 * NULL. On success pointer to an expression is returned which can be evaluated
37 * by the tst_bool_expr_eval() function and has to be later freed by the
38 * caller.
39 *
40 * The boolean expression can consists of:
41 *
42 * - unary negation opeartion !
43 * - two binary operations & and |
44 * - correct sequence of parentheses ()
45 * - strings that are treated as boolean variables
46 *
47 *  e.g. '(A | B) & C' or 'Variable_1 & Variable_2' are both a valid boolean
48 *  expressions.
49 *
50 *  @expr String containing a boolean expression to be parsed.
51 *  @return Pointer to an RPN expression.
52 */
53struct tst_expr *tst_bool_expr_parse(const char *expr);
54
55/*
56 * Prints an string representation of the expression into a FILE.
57 *
58 * @param A FILE to print to.
59 * @expr An expression to print.
60 */
61void tst_bool_expr_print(FILE *f, struct tst_expr *expr);
62
63/*
64 * Evaluates an expression given a map for variables.
65 *
66 * The call will fail if:
67 * - map function returns -1 which indicates undefined variable
68 * - the eval function runs out of stack
69 *
70 * @param expr Boolean expression in RPN.
71 * @param map Mapping function for boolean variables.
72 *
73 * @return Returns 0 or 1 if expression was evaluated correctly and -1 on error.
74 */
75int tst_bool_expr_eval(struct tst_expr *expr,
76                       int (*map)(struct tst_expr_tok *var));
77
78/*
79 * Frees the memory allocated by the tst_bool_expr_parse().
80 *
81 * @param Boolean expression.
82 */
83void tst_bool_expr_free(struct tst_expr *expr);
84
85#endif	/* TST_BOOL_EXPR_H__ */
86