example_expr_full.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* _
  2. * ___ __ _ __ _ _ _(_)
  3. * / __|/ _` |/ _` | | | | |
  4. * \__ \ (_| | (_| | |_| | |
  5. * |___/\__,_|\__, |\__,_|_|
  6. * |___/
  7. *
  8. * Cross-platform library which helps to develop web servers or frameworks.
  9. *
  10. * Copyright (C) 2016-2020 Silvio Clecio <[email protected]>
  11. *
  12. * Sagui library is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * Sagui library is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with Sagui library; if not, write to the Free Software
  24. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <math.h>
  29. #include <sagui.h>
  30. #define DUMMY_EXPR \
  31. "$(sum, $1 + $2), x = 2.3, y = 4.5, mul(6.7, sum(x, y)) + 0.11"
  32. /* NOTE: Error checking has been omitted to make it clear. */
  33. static double my_mul(__SG_UNUSED void *cls, struct sg_expr_argument *args,
  34. __SG_UNUSED const char *identifier) {
  35. if (!args)
  36. return NAN;
  37. return sg_expr_arg(args, 0) * sg_expr_arg(args, 1);
  38. }
  39. int main(int argc, const char *argv[]) {
  40. struct sg_expr_extension extensions[] = {
  41. {.func = my_mul, .identifier = "mul", .cls = NULL},
  42. {.func = NULL, .identifier = NULL, .cls = NULL},
  43. };
  44. struct sg_expr *expr;
  45. const char *s = argc == 2 ? argv[1] : DUMMY_EXPR;
  46. int ret;
  47. expr = sg_expr_new();
  48. ret = sg_expr_compile(expr, s, strlen(s), extensions);
  49. if (ret == 0)
  50. printf("Result: %f\n", sg_expr_eval(expr));
  51. else {
  52. printf("%s: %s", s, sg_expr_strerror(expr));
  53. printf("%*s^--- Error near here.\n", sg_expr_near(expr), "");
  54. }
  55. sg_expr_free(expr);
  56. return EXIT_SUCCESS;
  57. }