tinyexpr.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // SPDX-License-Identifier: Zlib
  2. /*
  3. * TINYEXPR - Tiny recursive descent parser and evaluation engine in C
  4. *
  5. * Copyright (c) 2015-2020 Lewis Van Winkle
  6. *
  7. * http://CodePlea.com
  8. *
  9. * This software is provided 'as-is', without any express or implied
  10. * warranty. In no event will the authors be held liable for any damages
  11. * arising from the use of this software.
  12. *
  13. * Permission is granted to anyone to use this software for any purpose,
  14. * including commercial applications, and to alter it and redistribute it
  15. * freely, subject to the following restrictions:
  16. *
  17. * 1. The origin of this software must not be misrepresented; you must not
  18. * claim that you wrote the original software. If you use this software
  19. * in a product, an acknowledgement in the product documentation would be
  20. * appreciated but is not required.
  21. * 2. Altered source versions must be plainly marked as such, and must not be
  22. * misrepresented as being the original software.
  23. * 3. This notice may not be removed or altered from any source distribution.
  24. */
  25. #ifndef TINYEXPR_H
  26. #define TINYEXPR_H
  27. #ifdef __cplusplus
  28. extern "C" {
  29. #endif
  30. typedef struct te_expr {
  31. int type;
  32. union {
  33. double value;
  34. const double* bound;
  35. const void* function;
  36. };
  37. void* parameters[1];
  38. } te_expr;
  39. enum {
  40. TE_VARIABLE = 0,
  41. TE_FUNCTION0 = 8,
  42. TE_FUNCTION1,
  43. TE_FUNCTION2,
  44. TE_FUNCTION3,
  45. TE_FUNCTION4,
  46. TE_FUNCTION5,
  47. TE_FUNCTION6,
  48. TE_FUNCTION7,
  49. TE_CLOSURE0 = 16,
  50. TE_CLOSURE1,
  51. TE_CLOSURE2,
  52. TE_CLOSURE3,
  53. TE_CLOSURE4,
  54. TE_CLOSURE5,
  55. TE_CLOSURE6,
  56. TE_CLOSURE7,
  57. TE_FLAG_PURE = 32
  58. };
  59. typedef struct te_variable {
  60. const char* name;
  61. const void* address;
  62. int type;
  63. void* context;
  64. } te_variable;
  65. /* Parses the input expression, evaluates it, and frees it. */
  66. /* Returns NaN on error. */
  67. double te_interp(const char* expression, int* error);
  68. /* Parses the input expression and binds variables. */
  69. /* Returns NULL on error. */
  70. te_expr*
  71. te_compile(const char* expression, const te_variable* variables, int var_count, int* error);
  72. /* Evaluates the expression. */
  73. double te_eval(const te_expr* n);
  74. /* Prints debugging information on the syntax tree. */
  75. void te_print(const te_expr* n);
  76. /* Frees the expression. */
  77. /* This is safe to call on NULL pointers. */
  78. void te_free(te_expr* n);
  79. #ifdef __cplusplus
  80. }
  81. #endif
  82. #endif /*TINYEXPR_H*/