expr.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. static int test(struct parse_ctx *ctx, const char *e, double val2)
  7. {
  8. double val;
  9. if (expr__parse(&val, ctx, &e))
  10. TEST_ASSERT_VAL("parse test failed", 0);
  11. TEST_ASSERT_VAL("unexpected value", val == val2);
  12. return 0;
  13. }
  14. int test__expr(struct test *t __maybe_unused, int subtest __maybe_unused)
  15. {
  16. const char *p;
  17. const char **other;
  18. double val;
  19. int i, ret;
  20. struct parse_ctx ctx;
  21. int num_other;
  22. expr__ctx_init(&ctx);
  23. expr__add_id(&ctx, "FOO", 1);
  24. expr__add_id(&ctx, "BAR", 2);
  25. ret = test(&ctx, "1+1", 2);
  26. ret |= test(&ctx, "FOO+BAR", 3);
  27. ret |= test(&ctx, "(BAR/2)%2", 1);
  28. ret |= test(&ctx, "1 - -4", 5);
  29. ret |= test(&ctx, "(FOO-1)*2 + (BAR/2)%2 - -4", 5);
  30. ret |= test(&ctx, "1-1 | 1", 1);
  31. ret |= test(&ctx, "1-1 & 1", 0);
  32. ret |= test(&ctx, "min(1,2) + 1", 2);
  33. ret |= test(&ctx, "max(1,2) + 1", 3);
  34. ret |= test(&ctx, "1+1 if 3*4 else 0", 2);
  35. if (ret)
  36. return ret;
  37. p = "FOO/0";
  38. ret = expr__parse(&val, &ctx, &p);
  39. TEST_ASSERT_VAL("division by zero", ret == 1);
  40. p = "BAR/";
  41. ret = expr__parse(&val, &ctx, &p);
  42. TEST_ASSERT_VAL("missing operand", ret == 1);
  43. TEST_ASSERT_VAL("find other",
  44. expr__find_other("FOO + BAR + BAZ + BOZO", "FOO", &other, &num_other) == 0);
  45. TEST_ASSERT_VAL("find other", num_other == 3);
  46. TEST_ASSERT_VAL("find other", !strcmp(other[0], "BAR"));
  47. TEST_ASSERT_VAL("find other", !strcmp(other[1], "BAZ"));
  48. TEST_ASSERT_VAL("find other", !strcmp(other[2], "BOZO"));
  49. TEST_ASSERT_VAL("find other", other[3] == NULL);
  50. for (i = 0; i < num_other; i++)
  51. free((void *)other[i]);
  52. free((void *)other);
  53. return 0;
  54. }