xref: /openbmc/linux/tools/perf/tests/expr.c (revision b593bce5)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "util/debug.h"
3 #include "util/expr.h"
4 #include "tests.h"
5 #include <stdlib.h>
6 #include <linux/zalloc.h>
7 
8 static int test(struct parse_ctx *ctx, const char *e, double val2)
9 {
10 	double val;
11 
12 	if (expr__parse(&val, ctx, &e))
13 		TEST_ASSERT_VAL("parse test failed", 0);
14 	TEST_ASSERT_VAL("unexpected value", val == val2);
15 	return 0;
16 }
17 
18 int test__expr(struct test *t __maybe_unused, int subtest __maybe_unused)
19 {
20 	const char *p;
21 	const char **other;
22 	double val;
23 	int i, ret;
24 	struct parse_ctx ctx;
25 	int num_other;
26 
27 	expr__ctx_init(&ctx);
28 	expr__add_id(&ctx, "FOO", 1);
29 	expr__add_id(&ctx, "BAR", 2);
30 
31 	ret = test(&ctx, "1+1", 2);
32 	ret |= test(&ctx, "FOO+BAR", 3);
33 	ret |= test(&ctx, "(BAR/2)%2", 1);
34 	ret |= test(&ctx, "1 - -4",  5);
35 	ret |= test(&ctx, "(FOO-1)*2 + (BAR/2)%2 - -4",  5);
36 	ret |= test(&ctx, "1-1 | 1", 1);
37 	ret |= test(&ctx, "1-1 & 1", 0);
38 	ret |= test(&ctx, "min(1,2) + 1", 2);
39 	ret |= test(&ctx, "max(1,2) + 1", 3);
40 	ret |= test(&ctx, "1+1 if 3*4 else 0", 2);
41 
42 	if (ret)
43 		return ret;
44 
45 	p = "FOO/0";
46 	ret = expr__parse(&val, &ctx, &p);
47 	TEST_ASSERT_VAL("division by zero", ret == 1);
48 
49 	p = "BAR/";
50 	ret = expr__parse(&val, &ctx, &p);
51 	TEST_ASSERT_VAL("missing operand", ret == 1);
52 
53 	TEST_ASSERT_VAL("find other",
54 			expr__find_other("FOO + BAR + BAZ + BOZO", "FOO", &other, &num_other) == 0);
55 	TEST_ASSERT_VAL("find other", num_other == 3);
56 	TEST_ASSERT_VAL("find other", !strcmp(other[0], "BAR"));
57 	TEST_ASSERT_VAL("find other", !strcmp(other[1], "BAZ"));
58 	TEST_ASSERT_VAL("find other", !strcmp(other[2], "BOZO"));
59 	TEST_ASSERT_VAL("find other", other[3] == NULL);
60 
61 	for (i = 0; i < num_other; i++)
62 		zfree(&other[i]);
63 	free((void *)other);
64 
65 	return 0;
66 }
67