math.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* math.h - interface to shell math "library" -- this allows shells to share
  2. * the implementation of arithmetic $((...)) expansions.
  3. *
  4. * This aims to be a POSIX shell math library as documented here:
  5. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_04
  6. *
  7. * See math.c for internal documentation.
  8. */
  9. /* The math library has just one function:
  10. *
  11. * arith_t arith(arith_state_t *state, const char *expr);
  12. *
  13. * The expr argument is the math string to parse. All normal expansions must
  14. * be done already. i.e. no dollar symbols should be present.
  15. *
  16. * The state argument is a pointer to a struct of hooks for your shell (see below),
  17. * and an error message string (NULL if no error).
  18. *
  19. * The function returns the answer to the expression. So if you called it
  20. * with the expression:
  21. * "1 + 2 + 3"
  22. * you would obviously get back 6.
  23. */
  24. /* To add support to a shell, you need to implement three functions:
  25. *
  26. * lookupvar() - look up and return the value of a variable
  27. *
  28. * If the shell does:
  29. * foo=123
  30. * Then the code:
  31. * const char *val = lookupvar("foo");
  32. * will result in val pointing to "123"
  33. *
  34. * setvar() - set a variable to some value
  35. *
  36. * If the arithmetic expansion does something like:
  37. * $((i = 1))
  38. * then the math code will make a call like so:
  39. * setvar("i", "1");
  40. * The storage for the first two parameters are not allocated, so your
  41. * shell implementation will most likely need to strdup() them to save.
  42. */
  43. #ifndef SHELL_MATH_H
  44. #define SHELL_MATH_H 1
  45. PUSH_AND_SET_FUNCTION_VISIBILITY_TO_HIDDEN
  46. #if ENABLE_FEATURE_SH_MATH_64
  47. typedef long long arith_t;
  48. # define ARITH_FMT "%lld"
  49. #else
  50. typedef long arith_t;
  51. # define ARITH_FMT "%ld"
  52. #endif
  53. typedef const char* FAST_FUNC (*arith_var_lookup_t)(const char *name);
  54. typedef void FAST_FUNC (*arith_var_set_t)(const char *name, const char *val);
  55. typedef struct arith_state_t {
  56. unsigned evaluation_disabled;
  57. const char *errmsg;
  58. void *list_of_recursed_names;
  59. arith_var_lookup_t lookupvar;
  60. arith_var_set_t setvar;
  61. } arith_state_t;
  62. arith_t FAST_FUNC arith(arith_state_t *state, const char *expr);
  63. POP_SAVED_FUNCTION_VISIBILITY
  64. #endif