expr.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. #ifndef EXPR_H
  2. #define EXPR_H
  3. #ifdef _MSC_VER
  4. #pragma warning(push)
  5. // Disable warning for zero-sized array:
  6. #pragma warning(disable : 4200)
  7. #endif
  8. #ifdef __cplusplus
  9. extern "C" {
  10. #endif
  11. #include <ctype.h> /* for isspace */
  12. #include <limits.h>
  13. #include <math.h> /* for pow */
  14. #include <stdint.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. /*
  19. * Simple expandable vector implementation
  20. */
  21. static int vec_expand(char **buf, int *length, int *cap, int memsz) {
  22. if (*length + 1 > *cap) {
  23. void *ptr;
  24. int n = (*cap == 0) ? 1 : *cap << 1;
  25. ptr = realloc(*buf, n * memsz);
  26. if (ptr == NULL) {
  27. return -1; /* allocation failed */
  28. }
  29. *buf = (char *)ptr;
  30. *cap = n;
  31. }
  32. return 0;
  33. }
  34. #define vec(T) \
  35. struct { \
  36. T *buf; \
  37. int len; \
  38. int cap; \
  39. }
  40. #define vec_init() \
  41. { NULL, 0, 0 }
  42. #define vec_len(v) ((v)->len)
  43. #define vec_unpack(v) \
  44. (char **)&(v)->buf, &(v)->len, &(v)->cap, sizeof(*(v)->buf)
  45. #define vec_push(v, val) \
  46. vec_expand(vec_unpack(v)) ? -1 : ((v)->buf[(v)->len++] = (val), 0)
  47. #define vec_nth(v, i) (v)->buf[i]
  48. #define vec_peek(v) (v)->buf[(v)->len - 1]
  49. #define vec_pop(v) (v)->buf[--(v)->len]
  50. #define vec_free(v) (free((v)->buf), (v)->buf = NULL, (v)->len = (v)->cap = 0)
  51. #define vec_foreach(v, var, iter) \
  52. if ((v)->len > 0) \
  53. for ((iter) = 0; (iter) < (v)->len && (((var) = (v)->buf[(iter)]), 1); \
  54. ++(iter))
  55. /*
  56. * Expression data types
  57. */
  58. struct expr;
  59. struct expr_func;
  60. enum expr_type {
  61. OP_UNKNOWN,
  62. OP_UNARY_MINUS,
  63. OP_UNARY_LOGICAL_NOT,
  64. OP_UNARY_BITWISE_NOT,
  65. OP_POWER,
  66. OP_DIVIDE,
  67. OP_MULTIPLY,
  68. OP_REMAINDER,
  69. OP_PLUS,
  70. OP_MINUS,
  71. OP_SHL,
  72. OP_SHR,
  73. OP_LT,
  74. OP_LE,
  75. OP_GT,
  76. OP_GE,
  77. OP_EQ,
  78. OP_NE,
  79. OP_BITWISE_AND,
  80. OP_BITWISE_OR,
  81. OP_BITWISE_XOR,
  82. OP_LOGICAL_AND,
  83. OP_LOGICAL_OR,
  84. OP_ASSIGN,
  85. OP_COMMA,
  86. OP_CONST,
  87. OP_VAR,
  88. OP_STRING,
  89. OP_FUNC,
  90. };
  91. static int prec[] = {0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5,
  92. 5, 5, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0};
  93. typedef vec(struct expr) vec_expr_t;
  94. typedef void (*exprfn_cleanup_t)(struct expr_func *f, void *context);
  95. typedef double (*exprfn_t)(struct expr_func *f, vec_expr_t *args,
  96. void *context);
  97. struct expr {
  98. enum expr_type type;
  99. union {
  100. struct {
  101. double value;
  102. } num;
  103. struct {
  104. double *value;
  105. } var;
  106. struct {
  107. vec_expr_t args;
  108. } op;
  109. struct {
  110. char *s;
  111. } str;
  112. struct {
  113. struct expr_func *f;
  114. vec_expr_t args;
  115. void *context;
  116. } func;
  117. } param;
  118. };
  119. #define expr_init() \
  120. { (enum expr_type)0 }
  121. struct expr_string {
  122. const char *s;
  123. int n;
  124. };
  125. struct expr_arg {
  126. int oslen;
  127. int eslen;
  128. vec_expr_t args;
  129. };
  130. typedef vec(struct expr_string) vec_str_t;
  131. typedef vec(struct expr_arg) vec_arg_t;
  132. static int expr_is_unary(enum expr_type op) {
  133. return op == OP_UNARY_MINUS || op == OP_UNARY_LOGICAL_NOT ||
  134. op == OP_UNARY_BITWISE_NOT;
  135. }
  136. static int expr_is_binary(enum expr_type op) {
  137. return !expr_is_unary(op) && op != OP_CONST && op != OP_VAR &&
  138. op != OP_FUNC && op != OP_UNKNOWN && op != OP_STRING;
  139. }
  140. static int expr_prec(enum expr_type a, enum expr_type b) {
  141. int left =
  142. expr_is_binary(a) && a != OP_ASSIGN && a != OP_POWER && a != OP_COMMA;
  143. return (left && prec[a] >= prec[b]) || (prec[a] > prec[b]);
  144. }
  145. #define isfirstvarchr(c) \
  146. (((unsigned char)c >= '@' && c != '^' && c != '|' && c != '~') || c == '$')
  147. #define isvarchr(c) \
  148. (((unsigned char)c >= '@' && c != '^' && c != '|' && c != '~') || \
  149. c == '$' || c == '#' || (c >= '0' && c <= '9'))
  150. static struct {
  151. const char *s;
  152. const enum expr_type op;
  153. } OPS[] = {
  154. {"-u", OP_UNARY_MINUS},
  155. {"!u", OP_UNARY_LOGICAL_NOT},
  156. {"~u", OP_UNARY_BITWISE_NOT},
  157. {"**", OP_POWER},
  158. {"*", OP_MULTIPLY},
  159. {"/", OP_DIVIDE},
  160. {"%", OP_REMAINDER},
  161. {"+", OP_PLUS},
  162. {"-", OP_MINUS},
  163. {"<<", OP_SHL},
  164. {">>", OP_SHR},
  165. {"<", OP_LT},
  166. {"<=", OP_LE},
  167. {">", OP_GT},
  168. {">=", OP_GE},
  169. {"==", OP_EQ},
  170. {"!=", OP_NE},
  171. {"&", OP_BITWISE_AND},
  172. {"|", OP_BITWISE_OR},
  173. {"^", OP_BITWISE_XOR},
  174. {"&&", OP_LOGICAL_AND},
  175. {"||", OP_LOGICAL_OR},
  176. {"=", OP_ASSIGN},
  177. {",", OP_COMMA},
  178. /* These are used by lexer and must be ignored by parser, so we put
  179. them at the end */
  180. {"-", OP_UNARY_MINUS},
  181. {"!", OP_UNARY_LOGICAL_NOT},
  182. {"~", OP_UNARY_BITWISE_NOT},
  183. };
  184. static enum expr_type expr_op(const char *s, size_t len, int unary) {
  185. for (unsigned int i = 0; i < sizeof(OPS) / sizeof(OPS[0]); i++) {
  186. if (strlen(OPS[i].s) == len && strncmp(OPS[i].s, s, len) == 0 &&
  187. (unary == -1 || expr_is_unary(OPS[i].op) == unary)) {
  188. return OPS[i].op;
  189. }
  190. }
  191. return OP_UNKNOWN;
  192. }
  193. static double expr_parse_number(const char *s, size_t len) {
  194. double num = 0;
  195. char buf[32];
  196. char *sz = buf;
  197. char *end = NULL;
  198. if (len >= sizeof(buf)) {
  199. sz = (char *)calloc(1, len + 1);
  200. if (sz == NULL) {
  201. return NAN;
  202. }
  203. }
  204. strncpy(sz, s, len);
  205. sz[len] = '\0';
  206. num = strtod(sz, &end);
  207. if (sz != buf) {
  208. free(sz);
  209. }
  210. return (end == sz + len ? num : NAN);
  211. }
  212. /*
  213. * Functions
  214. */
  215. struct expr_func {
  216. const char *name;
  217. exprfn_t f;
  218. exprfn_cleanup_t cleanup;
  219. size_t ctxsz;
  220. };
  221. static struct expr_func *expr_get_func(struct expr_func *funcs, const char *s,
  222. size_t len) {
  223. for (struct expr_func *f = funcs; f->name; f++) {
  224. if (strlen(f->name) == len && strncmp(f->name, s, len) == 0) {
  225. return f;
  226. }
  227. }
  228. return NULL;
  229. }
  230. /*
  231. * Variables
  232. */
  233. struct expr_var {
  234. double value;
  235. struct expr_var *next;
  236. char name[];
  237. };
  238. struct expr_var_list {
  239. struct expr_var *head;
  240. };
  241. static struct expr_var *expr_get_var(struct expr_var_list *vars, const char *s,
  242. size_t len) {
  243. struct expr_var *v = NULL;
  244. if (len == 0 || !isfirstvarchr(*s)) {
  245. return NULL;
  246. }
  247. for (v = vars->head; v; v = v->next) {
  248. if (strlen(v->name) == len && strncmp(v->name, s, len) == 0) {
  249. return v;
  250. }
  251. }
  252. v = (struct expr_var *)calloc(1, sizeof(struct expr_var) + len + 1);
  253. if (v == NULL) {
  254. return NULL; /* allocation failed */
  255. }
  256. v->next = vars->head;
  257. v->value = 0;
  258. strncpy(v->name, s, len);
  259. v->name[len] = '\0';
  260. vars->head = v;
  261. return v;
  262. }
  263. static int64_t to_int(double x) {
  264. if (isnan(x)) {
  265. return 0;
  266. } else if (isinf(x) != 0) {
  267. return INT64_MAX * isinf(x);
  268. } else {
  269. return (int64_t)x;
  270. }
  271. }
  272. static const char *expr_get_str(struct expr *e) {
  273. if (e->type != OP_STRING)
  274. return NULL;
  275. return e->param.str.s;
  276. }
  277. static double expr_eval(struct expr *e) {
  278. double n;
  279. switch (e->type) {
  280. case OP_UNARY_MINUS:
  281. return -(expr_eval(&e->param.op.args.buf[0]));
  282. case OP_UNARY_LOGICAL_NOT:
  283. return !(expr_eval(&e->param.op.args.buf[0]));
  284. case OP_UNARY_BITWISE_NOT:
  285. return ~(to_int(expr_eval(&e->param.op.args.buf[0])));
  286. case OP_POWER:
  287. return pow(expr_eval(&e->param.op.args.buf[0]),
  288. expr_eval(&e->param.op.args.buf[1]));
  289. case OP_MULTIPLY:
  290. return expr_eval(&e->param.op.args.buf[0]) *
  291. expr_eval(&e->param.op.args.buf[1]);
  292. case OP_DIVIDE:
  293. return expr_eval(&e->param.op.args.buf[0]) /
  294. expr_eval(&e->param.op.args.buf[1]);
  295. case OP_REMAINDER:
  296. return fmod(expr_eval(&e->param.op.args.buf[0]),
  297. expr_eval(&e->param.op.args.buf[1]));
  298. case OP_PLUS:
  299. return expr_eval(&e->param.op.args.buf[0]) +
  300. expr_eval(&e->param.op.args.buf[1]);
  301. case OP_MINUS:
  302. return expr_eval(&e->param.op.args.buf[0]) -
  303. expr_eval(&e->param.op.args.buf[1]);
  304. case OP_SHL:
  305. return to_int(expr_eval(&e->param.op.args.buf[0]))
  306. << to_int(expr_eval(&e->param.op.args.buf[1]));
  307. case OP_SHR:
  308. return to_int(expr_eval(&e->param.op.args.buf[0])) >>
  309. to_int(expr_eval(&e->param.op.args.buf[1]));
  310. case OP_LT:
  311. return expr_eval(&e->param.op.args.buf[0]) <
  312. expr_eval(&e->param.op.args.buf[1]);
  313. case OP_LE:
  314. return expr_eval(&e->param.op.args.buf[0]) <=
  315. expr_eval(&e->param.op.args.buf[1]);
  316. case OP_GT:
  317. return expr_eval(&e->param.op.args.buf[0]) >
  318. expr_eval(&e->param.op.args.buf[1]);
  319. case OP_GE:
  320. return expr_eval(&e->param.op.args.buf[0]) >=
  321. expr_eval(&e->param.op.args.buf[1]);
  322. case OP_EQ:
  323. return expr_eval(&e->param.op.args.buf[0]) ==
  324. expr_eval(&e->param.op.args.buf[1]);
  325. case OP_NE:
  326. return expr_eval(&e->param.op.args.buf[0]) !=
  327. expr_eval(&e->param.op.args.buf[1]);
  328. case OP_BITWISE_AND:
  329. return to_int(expr_eval(&e->param.op.args.buf[0])) &
  330. to_int(expr_eval(&e->param.op.args.buf[1]));
  331. case OP_BITWISE_OR:
  332. return to_int(expr_eval(&e->param.op.args.buf[0])) |
  333. to_int(expr_eval(&e->param.op.args.buf[1]));
  334. case OP_BITWISE_XOR:
  335. return to_int(expr_eval(&e->param.op.args.buf[0])) ^
  336. to_int(expr_eval(&e->param.op.args.buf[1]));
  337. case OP_LOGICAL_AND:
  338. n = expr_eval(&e->param.op.args.buf[0]);
  339. if (n != 0) {
  340. n = expr_eval(&e->param.op.args.buf[1]);
  341. if (n != 0) {
  342. return n;
  343. }
  344. }
  345. return 0;
  346. case OP_LOGICAL_OR:
  347. n = expr_eval(&e->param.op.args.buf[0]);
  348. if (n != 0 && !isnan(n)) {
  349. return n;
  350. } else {
  351. n = expr_eval(&e->param.op.args.buf[1]);
  352. if (n != 0) {
  353. return n;
  354. }
  355. }
  356. return 0;
  357. case OP_ASSIGN:
  358. n = expr_eval(&e->param.op.args.buf[1]);
  359. if (vec_nth(&e->param.op.args, 0).type == OP_VAR) {
  360. *e->param.op.args.buf[0].param.var.value = n;
  361. }
  362. return n;
  363. case OP_COMMA:
  364. expr_eval(&e->param.op.args.buf[0]);
  365. return expr_eval(&e->param.op.args.buf[1]);
  366. case OP_CONST:
  367. return e->param.num.value;
  368. case OP_VAR:
  369. return *e->param.var.value;
  370. case OP_FUNC:
  371. return e->param.func.f->f(e->param.func.f, &e->param.func.args,
  372. e->param.func.context);
  373. default:
  374. return NAN;
  375. }
  376. }
  377. #define EXPR_TOP (1 << 0)
  378. #define EXPR_TOPEN (1 << 1)
  379. #define EXPR_TCLOSE (1 << 2)
  380. #define EXPR_TLITERAL (1 << 3)
  381. #define EXPR_TWORD (1 << 4)
  382. #define EXPR_TDEFAULT (EXPR_TOPEN | EXPR_TLITERAL | EXPR_TWORD)
  383. #define EXPR_UNARY (1 << 5)
  384. #define EXPR_COMMA (1 << 6)
  385. static int expr_next_token(const char *s, size_t len, int *flags) {
  386. unsigned int i = 0;
  387. if (len == 0) {
  388. return 0;
  389. }
  390. char c = s[0];
  391. if (c == '#') {
  392. for (; i < len && s[i] != '\n'; i++)
  393. ;
  394. return i;
  395. } else if (c == '\n') {
  396. for (; i < len && isspace(s[i]); i++)
  397. ;
  398. if (*flags & EXPR_TOP) {
  399. if (i == len || s[i] == ')') {
  400. *flags = *flags & (~EXPR_COMMA);
  401. } else {
  402. *flags = EXPR_TLITERAL | EXPR_TWORD | EXPR_TOPEN | EXPR_COMMA;
  403. }
  404. }
  405. return i;
  406. } else if (isspace(c)) {
  407. while (i < len && isspace(s[i]) && s[i] != '\n') {
  408. i++;
  409. }
  410. return i;
  411. } else if (isdigit(c)) {
  412. if ((*flags & EXPR_TLITERAL) == 0) {
  413. return -1; // unexpected number
  414. }
  415. *flags = EXPR_TOP | EXPR_TCLOSE;
  416. if (c == '0') {
  417. i++;
  418. if (i < len && (s[i] == 'x' || s[i] == 'X')) {
  419. i++;
  420. for (; i < len && isxdigit(s[i]); i++)
  421. ;
  422. return i;
  423. }
  424. }
  425. for (; i < len && (s[i] == '.' || isdigit(s[i])); i++)
  426. ;
  427. if (i < len && (s[i] == 'e' || s[i] == 'E')) {
  428. i++;
  429. if (i < len && (s[i] == '+' || s[i] == '-'))
  430. i++;
  431. for (; i < len && isdigit(s[i]); i++)
  432. ;
  433. }
  434. return i;
  435. } else if (c == '"') {
  436. if ((*flags & EXPR_TLITERAL) == 0) {
  437. return -6; // unexpected string
  438. }
  439. *flags = EXPR_TOP | EXPR_TCLOSE;
  440. i++;
  441. for (; i < len && s[i] != '"'; i++)
  442. ;
  443. if (i >= len) {
  444. return -7; // missing expected quote
  445. }
  446. i++;
  447. return i;
  448. } else if (isfirstvarchr(c)) {
  449. if ((*flags & EXPR_TWORD) == 0) {
  450. return -2; // unexpected word
  451. }
  452. *flags = EXPR_TOP | EXPR_TOPEN | EXPR_TCLOSE;
  453. while ((isvarchr(c)) && i < len) {
  454. i++;
  455. c = s[i];
  456. }
  457. return i;
  458. } else if (c == '(' || c == ')') {
  459. if (c == '(' && (*flags & EXPR_TOPEN) != 0) {
  460. *flags = EXPR_TLITERAL | EXPR_TWORD | EXPR_TOPEN | EXPR_TCLOSE;
  461. } else if (c == ')' && (*flags & EXPR_TCLOSE) != 0) {
  462. *flags = EXPR_TOP | EXPR_TCLOSE;
  463. } else {
  464. return -3; // unexpected parenthesis
  465. }
  466. return 1;
  467. } else {
  468. if ((*flags & EXPR_TOP) == 0) {
  469. if (expr_op(&c, 1, 1) == OP_UNKNOWN) {
  470. return -4; // missing expected operand
  471. }
  472. *flags = EXPR_TLITERAL | EXPR_TWORD | EXPR_TOPEN | EXPR_UNARY;
  473. return 1;
  474. } else {
  475. int found = 0;
  476. while (!isvarchr(c) && !isspace(c) && c != '(' && c != ')' && i < len) {
  477. if (expr_op(s, i + 1, 0) != OP_UNKNOWN) {
  478. found = 1;
  479. } else if (found) {
  480. break;
  481. }
  482. i++;
  483. c = s[i];
  484. }
  485. if (!found) {
  486. return -5; // unknown operator
  487. }
  488. *flags = EXPR_TLITERAL | EXPR_TWORD | EXPR_TOPEN;
  489. return i;
  490. }
  491. }
  492. }
  493. #define EXPR_PAREN_ALLOWED 0
  494. #define EXPR_PAREN_EXPECTED 1
  495. #define EXPR_PAREN_FORBIDDEN 2
  496. static int expr_bind(const char *s, size_t len, vec_expr_t *es) {
  497. enum expr_type op = expr_op(s, len, -1);
  498. if (op == OP_UNKNOWN) {
  499. return -1;
  500. }
  501. if (expr_is_unary(op)) {
  502. if (vec_len(es) < 1) {
  503. return -1;
  504. }
  505. struct expr arg = vec_pop(es);
  506. struct expr unary = expr_init();
  507. unary.type = op;
  508. vec_push(&unary.param.op.args, arg);
  509. vec_push(es, unary);
  510. } else {
  511. if (vec_len(es) < 2) {
  512. return -1;
  513. }
  514. struct expr b = vec_pop(es);
  515. struct expr a = vec_pop(es);
  516. struct expr binary = expr_init();
  517. binary.type = op;
  518. if (op == OP_ASSIGN && a.type != OP_VAR) {
  519. return -1; /* Bad assignment */
  520. }
  521. vec_push(&binary.param.op.args, a);
  522. vec_push(&binary.param.op.args, b);
  523. vec_push(es, binary);
  524. }
  525. return 0;
  526. }
  527. static struct expr expr_const(double value) {
  528. struct expr e = expr_init();
  529. e.type = OP_CONST;
  530. e.param.num.value = value;
  531. return e;
  532. }
  533. static struct expr expr_varref(struct expr_var *v) {
  534. struct expr e = expr_init();
  535. e.type = OP_VAR;
  536. e.param.var.value = &v->value;
  537. return e;
  538. }
  539. static struct expr expr_binary(enum expr_type type, struct expr a,
  540. struct expr b) {
  541. struct expr e = expr_init();
  542. e.type = type;
  543. vec_push(&e.param.op.args, a);
  544. vec_push(&e.param.op.args, b);
  545. return e;
  546. }
  547. static inline void expr_copy(struct expr *dst, struct expr *src) {
  548. int i;
  549. struct expr arg;
  550. dst->type = src->type;
  551. if (src->type == OP_FUNC) {
  552. dst->param.func.f = src->param.func.f;
  553. vec_foreach(&src->param.func.args, arg, i) {
  554. struct expr tmp = expr_init();
  555. expr_copy(&tmp, &arg);
  556. vec_push(&dst->param.func.args, tmp);
  557. }
  558. if (src->param.func.f->ctxsz > 0) {
  559. dst->param.func.context = calloc(1, src->param.func.f->ctxsz);
  560. }
  561. } else if (src->type == OP_CONST) {
  562. dst->param.num.value = src->param.num.value;
  563. } else if (src->type == OP_VAR) {
  564. dst->param.var.value = src->param.var.value;
  565. } else if (src->type == OP_STRING) {
  566. size_t len = strlen(src->param.str.s);
  567. dst->param.str.s = (char *)calloc(1, len + 1);
  568. if (dst->param.str.s != NULL) {
  569. strncpy(dst->param.str.s, src->param.str.s, len);
  570. }
  571. } else {
  572. vec_foreach(&src->param.op.args, arg, i) {
  573. struct expr tmp = expr_init();
  574. expr_copy(&tmp, &arg);
  575. vec_push(&dst->param.op.args, tmp);
  576. }
  577. }
  578. }
  579. static void expr_destroy_args(struct expr *e);
  580. static struct expr *expr_create(const char *s, size_t len,
  581. struct expr_var_list *vars,
  582. struct expr_func *funcs) {
  583. double num;
  584. const char *id = NULL;
  585. size_t idn = 0;
  586. struct expr *result = NULL;
  587. vec_expr_t es = vec_init();
  588. vec_str_t os = vec_init();
  589. vec_arg_t as = vec_init();
  590. struct macro {
  591. char *name;
  592. vec_expr_t body;
  593. };
  594. vec(struct macro) macros = vec_init();
  595. int flags = EXPR_TDEFAULT;
  596. int paren = EXPR_PAREN_ALLOWED;
  597. for (;;) {
  598. int n = expr_next_token(s, len, &flags);
  599. if (n == 0) {
  600. break;
  601. } else if (n < 0) {
  602. goto cleanup;
  603. }
  604. const char *tok = s;
  605. s = s + n;
  606. len = len - n;
  607. if (*tok == '#') {
  608. continue;
  609. }
  610. if (flags & EXPR_UNARY) {
  611. if (n == 1) {
  612. switch (*tok) {
  613. case '-':
  614. tok = "-u";
  615. break;
  616. case '~':
  617. tok = "~u";
  618. break;
  619. case '!':
  620. tok = "!u";
  621. break;
  622. default:
  623. goto cleanup;
  624. }
  625. n = 2;
  626. }
  627. }
  628. if (*tok == '\n' && (flags & EXPR_COMMA)) {
  629. flags = flags & (~EXPR_COMMA);
  630. n = 1;
  631. tok = ",";
  632. }
  633. if (isspace(*tok)) {
  634. continue;
  635. }
  636. int paren_next = EXPR_PAREN_ALLOWED;
  637. if (idn > 0) {
  638. struct expr_var *v;
  639. if (n == 1 && *tok == '(') {
  640. int i;
  641. int has_macro = 0;
  642. struct macro m;
  643. vec_foreach(&macros, m, i) {
  644. if (strlen(m.name) == idn && strncmp(m.name, id, idn) == 0) {
  645. has_macro = 1;
  646. break;
  647. }
  648. }
  649. if ((idn == 1 && id[0] == '$') || has_macro ||
  650. expr_get_func(funcs, id, idn) != NULL) {
  651. struct expr_string str = {id, (int)idn};
  652. vec_push(&os, str);
  653. paren = EXPR_PAREN_EXPECTED;
  654. } else {
  655. goto cleanup; /* invalid function name */
  656. }
  657. } else if ((v = expr_get_var(vars, id, idn)) != NULL) {
  658. vec_push(&es, expr_varref(v));
  659. paren = EXPR_PAREN_FORBIDDEN;
  660. }
  661. id = NULL;
  662. idn = 0;
  663. }
  664. if (n == 1 && *tok == '(') {
  665. if (paren == EXPR_PAREN_EXPECTED) {
  666. struct expr_string str = {"{", 1};
  667. vec_push(&os, str);
  668. struct expr_arg arg = {vec_len(&os), vec_len(&es), vec_init()};
  669. vec_push(&as, arg);
  670. } else if (paren == EXPR_PAREN_ALLOWED) {
  671. struct expr_string str = {"(", 1};
  672. vec_push(&os, str);
  673. } else {
  674. goto cleanup; // Bad call
  675. }
  676. } else if (paren == EXPR_PAREN_EXPECTED) {
  677. goto cleanup; // Bad call
  678. } else if (n == 1 && *tok == ')') {
  679. int minlen = (vec_len(&as) > 0 ? vec_peek(&as).oslen : 0);
  680. while (vec_len(&os) > minlen && *vec_peek(&os).s != '(' &&
  681. *vec_peek(&os).s != '{') {
  682. struct expr_string str = vec_pop(&os);
  683. if (expr_bind(str.s, str.n, &es) == -1) {
  684. goto cleanup;
  685. }
  686. }
  687. if (vec_len(&os) == 0) {
  688. goto cleanup; // Bad parens
  689. }
  690. struct expr_string str = vec_pop(&os);
  691. if (str.n == 1 && *str.s == '{') {
  692. str = vec_pop(&os);
  693. struct expr_arg arg = vec_pop(&as);
  694. if (vec_len(&es) > arg.eslen) {
  695. vec_push(&arg.args, vec_pop(&es));
  696. }
  697. if (str.n == 1 && str.s[0] == '$') {
  698. if (vec_len(&arg.args) < 1) {
  699. vec_free(&arg.args);
  700. goto cleanup; /* too few arguments for $() function */
  701. }
  702. struct expr *u = &vec_nth(&arg.args, 0);
  703. if (u->type != OP_VAR) {
  704. vec_free(&arg.args);
  705. goto cleanup; /* first argument is not a variable */
  706. }
  707. for (struct expr_var *v = vars->head; v; v = v->next) {
  708. if (&v->value == u->param.var.value) {
  709. struct macro m = {v->name, arg.args};
  710. vec_push(&macros, m);
  711. break;
  712. }
  713. }
  714. vec_push(&es, expr_const(0));
  715. } else {
  716. int i = 0;
  717. int found = -1;
  718. struct macro m;
  719. vec_foreach(&macros, m, i) {
  720. if (strlen(m.name) == (size_t)str.n &&
  721. strncmp(m.name, str.s, str.n) == 0) {
  722. found = i;
  723. }
  724. }
  725. if (found != -1) {
  726. m = vec_nth(&macros, found);
  727. struct expr root = expr_const(0);
  728. struct expr *p = &root;
  729. /* Assign macro parameters */
  730. for (int j = 0; j < vec_len(&arg.args); j++) {
  731. char varname[13];
  732. snprintf(varname, sizeof(varname), "$%d", (j + 1));
  733. struct expr_var *v = expr_get_var(vars, varname, strlen(varname));
  734. struct expr ev = expr_varref(v);
  735. struct expr assign =
  736. expr_binary(OP_ASSIGN, ev, vec_nth(&arg.args, j));
  737. *p = expr_binary(OP_COMMA, assign, expr_const(0));
  738. p = &vec_nth(&p->param.op.args, 1);
  739. }
  740. /* Expand macro body */
  741. for (int j = 1; j < vec_len(&m.body); j++) {
  742. if (j < vec_len(&m.body) - 1) {
  743. *p = expr_binary(OP_COMMA, expr_const(0), expr_const(0));
  744. expr_copy(&vec_nth(&p->param.op.args, 0), &vec_nth(&m.body, j));
  745. } else {
  746. expr_copy(p, &vec_nth(&m.body, j));
  747. }
  748. p = &vec_nth(&p->param.op.args, 1);
  749. }
  750. vec_push(&es, root);
  751. vec_free(&arg.args);
  752. } else {
  753. struct expr_func *f = expr_get_func(funcs, str.s, str.n);
  754. struct expr bound_func = expr_init();
  755. bound_func.type = OP_FUNC;
  756. bound_func.param.func.f = f;
  757. bound_func.param.func.args = arg.args;
  758. if (f->ctxsz > 0) {
  759. void *p = calloc(1, f->ctxsz);
  760. if (p == NULL) {
  761. goto cleanup; /* allocation failed */
  762. }
  763. bound_func.param.func.context = p;
  764. }
  765. vec_push(&es, bound_func);
  766. }
  767. }
  768. }
  769. paren_next = EXPR_PAREN_FORBIDDEN;
  770. } else if (!isnan(num = expr_parse_number(tok, n))) {
  771. vec_push(&es, expr_const(num));
  772. paren_next = EXPR_PAREN_FORBIDDEN;
  773. } else if (n > 1 && *tok == '"') {
  774. char *str = (char *)calloc(1, n - 1);
  775. if (str == NULL) {
  776. goto cleanup; /* allocation failed */
  777. }
  778. strncpy(str, tok + 1, n - 2);
  779. struct expr e = expr_init();
  780. e.type = OP_STRING;
  781. e.param.str.s = str;
  782. vec_push(&es, e);
  783. paren_next = EXPR_PAREN_FORBIDDEN;
  784. } else if (expr_op(tok, n, -1) != OP_UNKNOWN) {
  785. enum expr_type op = expr_op(tok, n, -1);
  786. struct expr_string o2 = {NULL, 0};
  787. if (vec_len(&os) > 0) {
  788. o2 = vec_peek(&os);
  789. }
  790. for (;;) {
  791. if (n == 1 && *tok == ',' && vec_len(&os) > 0) {
  792. struct expr_string str = vec_peek(&os);
  793. if (str.n == 1 && *str.s == '{') {
  794. struct expr e = vec_pop(&es);
  795. vec_push(&vec_peek(&as).args, e);
  796. break;
  797. }
  798. }
  799. enum expr_type type2 = expr_op(o2.s, o2.n, -1);
  800. if (!(type2 != OP_UNKNOWN && expr_prec(op, type2))) {
  801. struct expr_string str = {tok, n};
  802. vec_push(&os, str);
  803. break;
  804. }
  805. if (expr_bind(o2.s, o2.n, &es) == -1) {
  806. goto cleanup;
  807. }
  808. (void)vec_pop(&os);
  809. if (vec_len(&os) > 0) {
  810. o2 = vec_peek(&os);
  811. } else {
  812. o2.n = 0;
  813. }
  814. }
  815. } else {
  816. if (n > 0 && !isdigit(*tok)) {
  817. /* Valid identifier, a variable or a function */
  818. id = tok;
  819. idn = n;
  820. } else {
  821. goto cleanup; // Bad variable name, e.g. '2.3.4' or '4ever'
  822. }
  823. }
  824. paren = paren_next;
  825. }
  826. if (idn > 0) {
  827. vec_push(&es, expr_varref(expr_get_var(vars, id, idn)));
  828. }
  829. while (vec_len(&os) > 0) {
  830. struct expr_string rest = vec_pop(&os);
  831. if (rest.n == 1 && (*rest.s == '(' || *rest.s == ')')) {
  832. goto cleanup; // Bad paren
  833. }
  834. if (expr_bind(rest.s, rest.n, &es) == -1) {
  835. goto cleanup;
  836. }
  837. }
  838. result = (struct expr *)calloc(1, sizeof(struct expr));
  839. if (result != NULL) {
  840. if (vec_len(&es) == 0) {
  841. result->type = OP_CONST;
  842. } else {
  843. *result = vec_pop(&es);
  844. }
  845. }
  846. int i, j;
  847. struct macro m;
  848. struct expr e;
  849. struct expr_arg a;
  850. cleanup:
  851. vec_foreach(&macros, m, i) {
  852. struct expr e2;
  853. vec_foreach(&m.body, e2, j) { expr_destroy_args(&e2); }
  854. vec_free(&m.body);
  855. }
  856. vec_free(&macros);
  857. vec_foreach(&es, e, i) { expr_destroy_args(&e); }
  858. vec_free(&es);
  859. vec_foreach(&as, a, i) {
  860. vec_foreach(&a.args, e, j) { expr_destroy_args(&e); }
  861. vec_free(&a.args);
  862. }
  863. vec_free(&as);
  864. /*vec_foreach(&os, o, i) {vec_free(&m.body);}*/
  865. vec_free(&os);
  866. return result;
  867. }
  868. static void expr_destroy_args(struct expr *e) {
  869. int i;
  870. struct expr arg;
  871. if (e->type == OP_FUNC) {
  872. vec_foreach(&e->param.func.args, arg, i) { expr_destroy_args(&arg); }
  873. vec_free(&e->param.func.args);
  874. if (e->param.func.context != NULL) {
  875. if (e->param.func.f->cleanup != NULL) {
  876. e->param.func.f->cleanup(e->param.func.f, e->param.func.context);
  877. }
  878. free(e->param.func.context);
  879. }
  880. } else if (e->type == OP_STRING) {
  881. free(e->param.str.s);
  882. } else if (e->type != OP_CONST && e->type != OP_VAR) {
  883. vec_foreach(&e->param.op.args, arg, i) { expr_destroy_args(&arg); }
  884. vec_free(&e->param.op.args);
  885. }
  886. }
  887. static void expr_destroy(struct expr *e, struct expr_var_list *vars) {
  888. if (e != NULL) {
  889. expr_destroy_args(e);
  890. free(e);
  891. }
  892. if (vars != NULL) {
  893. for (struct expr_var *v = vars->head; v;) {
  894. struct expr_var *next = v->next;
  895. free(v);
  896. v = next;
  897. }
  898. }
  899. }
  900. #ifdef __cplusplus
  901. } /* extern "C" */
  902. #endif
  903. #ifdef _MSC_VER
  904. #pragma warning(pop)
  905. #endif
  906. #endif /* EXPR_H */