3
0

math.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. /*
  2. * Arithmetic code ripped out of ash shell for code sharing.
  3. *
  4. * This code is derived from software contributed to Berkeley by
  5. * Kenneth Almquist.
  6. *
  7. * Original BSD copyright notice is retained at the end of this file.
  8. *
  9. * Copyright (c) 1989, 1991, 1993, 1994
  10. * The Regents of the University of California. All rights reserved.
  11. *
  12. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  13. * was re-ported from NetBSD and debianized.
  14. *
  15. * rewrite arith.y to micro stack based cryptic algorithm by
  16. * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  17. *
  18. * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
  19. * dynamic variables.
  20. *
  21. * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
  22. * used in busybox and size optimizations,
  23. * rewrote arith (see notes to this), added locale support,
  24. * rewrote dynamic variables.
  25. *
  26. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  27. */
  28. /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  29. *
  30. * Permission is hereby granted, free of charge, to any person obtaining
  31. * a copy of this software and associated documentation files (the
  32. * "Software"), to deal in the Software without restriction, including
  33. * without limitation the rights to use, copy, modify, merge, publish,
  34. * distribute, sublicense, and/or sell copies of the Software, and to
  35. * permit persons to whom the Software is furnished to do so, subject to
  36. * the following conditions:
  37. *
  38. * The above copyright notice and this permission notice shall be
  39. * included in all copies or substantial portions of the Software.
  40. *
  41. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  42. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  43. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  44. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  45. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  46. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  47. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  48. */
  49. /* This is my infix parser/evaluator. It is optimized for size, intended
  50. * as a replacement for yacc-based parsers. However, it may well be faster
  51. * than a comparable parser written in yacc. The supported operators are
  52. * listed in #defines below. Parens, order of operations, and error handling
  53. * are supported. This code is thread safe. The exact expression format should
  54. * be that which POSIX specifies for shells.
  55. *
  56. * The code uses a simple two-stack algorithm. See
  57. * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
  58. * for a detailed explanation of the infix-to-postfix algorithm on which
  59. * this is based (this code differs in that it applies operators immediately
  60. * to the stack instead of adding them to a queue to end up with an
  61. * expression).
  62. */
  63. /*
  64. * Aug 24, 2001 Manuel Novoa III
  65. *
  66. * Reduced the generated code size by about 30% (i386) and fixed several bugs.
  67. *
  68. * 1) In arith_apply():
  69. * a) Cached values of *numptr and &(numptr[-1]).
  70. * b) Removed redundant test for zero denominator.
  71. *
  72. * 2) In arith():
  73. * a) Eliminated redundant code for processing operator tokens by moving
  74. * to a table-based implementation. Also folded handling of parens
  75. * into the table.
  76. * b) Combined all 3 loops which called arith_apply to reduce generated
  77. * code size at the cost of speed.
  78. *
  79. * 3) The following expressions were treated as valid by the original code:
  80. * 1() , 0! , 1 ( *3 ) .
  81. * These bugs have been fixed by internally enclosing the expression in
  82. * parens and then checking that all binary ops and right parens are
  83. * preceded by a valid expression (NUM_TOKEN).
  84. *
  85. * Note: It may be desirable to replace Aaron's test for whitespace with
  86. * ctype's isspace() if it is used by another busybox applet or if additional
  87. * whitespace chars should be considered. Look below the "#include"s for a
  88. * precompiler test.
  89. */
  90. /*
  91. * Aug 26, 2001 Manuel Novoa III
  92. *
  93. * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
  94. *
  95. * Merge in Aaron's comments previously posted to the busybox list,
  96. * modified slightly to take account of my changes to the code.
  97. *
  98. */
  99. /*
  100. * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  101. *
  102. * - allow access to variable,
  103. * use recursive value indirection: c="2*2"; a="c"; echo $((a+=2)) produce 6
  104. * - implement assign syntax (VAR=expr, +=, *= etc)
  105. * - implement exponentiation (** operator)
  106. * - implement comma separated - expr, expr
  107. * - implement ++expr --expr expr++ expr--
  108. * - implement expr ? expr : expr (but second expr is always calculated)
  109. * - allow hexadecimal and octal numbers
  110. * - restore lost XOR operator
  111. * - protect $((num num)) as true zero expr (Manuel's error)
  112. * - always use special isspace(), see comment from bash ;-)
  113. */
  114. #include "libbb.h"
  115. #include "math.h"
  116. #define lookupvar (math_state->lookupvar)
  117. #define setvar (math_state->setvar )
  118. //#define endofname (math_state->endofname)
  119. typedef unsigned char operator;
  120. /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
  121. * precedence, and 3 high bits are an ID unique across operators of that
  122. * precedence. The ID portion is so that multiple operators can have the
  123. * same precedence, ensuring that the leftmost one is evaluated first.
  124. * Consider * and /
  125. */
  126. #define tok_decl(prec,id) (((id)<<5) | (prec))
  127. #define PREC(op) ((op) & 0x1F)
  128. #define TOK_LPAREN tok_decl(0,0)
  129. #define TOK_COMMA tok_decl(1,0)
  130. /* All assignments are right associative and have the same precedence,
  131. * but there are 11 of them, which doesn't fit into 3 bits for unique id.
  132. * Abusing another precedence level:
  133. */
  134. #define TOK_ASSIGN tok_decl(2,0)
  135. #define TOK_AND_ASSIGN tok_decl(2,1)
  136. #define TOK_OR_ASSIGN tok_decl(2,2)
  137. #define TOK_XOR_ASSIGN tok_decl(2,3)
  138. #define TOK_PLUS_ASSIGN tok_decl(2,4)
  139. #define TOK_MINUS_ASSIGN tok_decl(2,5)
  140. #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
  141. #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
  142. #define TOK_MUL_ASSIGN tok_decl(3,0)
  143. #define TOK_DIV_ASSIGN tok_decl(3,1)
  144. #define TOK_REM_ASSIGN tok_decl(3,2)
  145. #define fix_assignment_prec(prec) do { if (prec == 3) prec = 2; } while (0)
  146. /* Ternary conditional operator is right associative too */
  147. #define TOK_CONDITIONAL tok_decl(4,0)
  148. #define TOK_CONDITIONAL_SEP tok_decl(4,1)
  149. #define TOK_OR tok_decl(5,0)
  150. #define TOK_AND tok_decl(6,0)
  151. #define TOK_BOR tok_decl(7,0)
  152. #define TOK_BXOR tok_decl(8,0)
  153. #define TOK_BAND tok_decl(9,0)
  154. #define TOK_EQ tok_decl(10,0)
  155. #define TOK_NE tok_decl(10,1)
  156. #define TOK_LT tok_decl(11,0)
  157. #define TOK_GT tok_decl(11,1)
  158. #define TOK_GE tok_decl(11,2)
  159. #define TOK_LE tok_decl(11,3)
  160. #define TOK_LSHIFT tok_decl(12,0)
  161. #define TOK_RSHIFT tok_decl(12,1)
  162. #define TOK_ADD tok_decl(13,0)
  163. #define TOK_SUB tok_decl(13,1)
  164. #define TOK_MUL tok_decl(14,0)
  165. #define TOK_DIV tok_decl(14,1)
  166. #define TOK_REM tok_decl(14,2)
  167. /* Exponent is right associative */
  168. #define TOK_EXPONENT tok_decl(15,1)
  169. /* Unary operators */
  170. #define UNARYPREC 16
  171. #define TOK_BNOT tok_decl(UNARYPREC,0)
  172. #define TOK_NOT tok_decl(UNARYPREC,1)
  173. #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
  174. #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
  175. #define PREC_PRE (UNARYPREC+2)
  176. #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
  177. #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
  178. #define PREC_POST (UNARYPREC+3)
  179. #define TOK_POST_INC tok_decl(PREC_POST, 0)
  180. #define TOK_POST_DEC tok_decl(PREC_POST, 1)
  181. #define SPEC_PREC (UNARYPREC+4)
  182. #define TOK_NUM tok_decl(SPEC_PREC, 0)
  183. #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
  184. static int
  185. is_assign_op(operator op)
  186. {
  187. operator prec = PREC(op);
  188. fix_assignment_prec(prec);
  189. return prec == PREC(TOK_ASSIGN)
  190. || prec == PREC_PRE
  191. || prec == PREC_POST;
  192. }
  193. static int
  194. is_right_associative(operator prec)
  195. {
  196. return prec == PREC(TOK_ASSIGN)
  197. || prec == PREC(TOK_EXPONENT)
  198. || prec == PREC(TOK_CONDITIONAL);
  199. }
  200. typedef struct {
  201. arith_t val;
  202. /* We acquire second_val only when "expr1 : expr2" part
  203. * of ternary ?: op is evaluated.
  204. * We treat ?: as two binary ops: (expr ? (expr1 : expr2)).
  205. * ':' produces a new value which has two parts, val and second_val;
  206. * then '?' selects one of them based on its left side.
  207. */
  208. arith_t second_val;
  209. char second_val_present;
  210. /* If NULL then it's just a number, else it's a named variable */
  211. char *var;
  212. } var_or_num_t;
  213. typedef struct remembered_name {
  214. struct remembered_name *next;
  215. const char *var;
  216. } remembered_name;
  217. static arith_t FAST_FUNC
  218. evaluate_string(arith_state_t *math_state, const char *expr);
  219. static const char*
  220. arith_lookup_val(arith_state_t *math_state, var_or_num_t *t)
  221. {
  222. if (t->var) {
  223. const char *p = lookupvar(t->var);
  224. if (p) {
  225. remembered_name *cur;
  226. remembered_name cur_save;
  227. /* did we already see this name?
  228. * testcase: a=b; b=a; echo $((a))
  229. */
  230. for (cur = math_state->list_of_recursed_names; cur; cur = cur->next) {
  231. if (strcmp(cur->var, t->var) == 0) {
  232. /* Yes */
  233. return "expression recursion loop detected";
  234. }
  235. }
  236. /* push current var name */
  237. cur = math_state->list_of_recursed_names;
  238. cur_save.var = t->var;
  239. cur_save.next = cur;
  240. math_state->list_of_recursed_names = &cur_save;
  241. /* recursively evaluate p as expression */
  242. t->val = evaluate_string(math_state, p);
  243. /* pop current var name */
  244. math_state->list_of_recursed_names = cur;
  245. return math_state->errmsg;
  246. }
  247. /* treat undefined var as 0 */
  248. t->val = 0;
  249. }
  250. return 0;
  251. }
  252. /* "Applying" a token means performing it on the top elements on the integer
  253. * stack. For an unary operator it will only change the top element, but a
  254. * binary operator will pop two arguments and push the result */
  255. static NOINLINE const char*
  256. arith_apply(arith_state_t *math_state, operator op, var_or_num_t *numstack, var_or_num_t **numstackptr)
  257. {
  258. #define NUMPTR (*numstackptr)
  259. var_or_num_t *top_of_stack;
  260. arith_t rez;
  261. const char *err;
  262. /* There is no operator that can work without arguments */
  263. if (NUMPTR == numstack)
  264. goto err;
  265. top_of_stack = NUMPTR - 1;
  266. /* Resolve name to value, if needed */
  267. err = arith_lookup_val(math_state, top_of_stack);
  268. if (err)
  269. return err;
  270. rez = top_of_stack->val;
  271. if (op == TOK_UMINUS)
  272. rez = -rez;
  273. else if (op == TOK_NOT)
  274. rez = !rez;
  275. else if (op == TOK_BNOT)
  276. rez = ~rez;
  277. else if (op == TOK_POST_INC || op == TOK_PRE_INC)
  278. rez++;
  279. else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
  280. rez--;
  281. else if (op != TOK_UPLUS) {
  282. /* Binary operators */
  283. arith_t right_side_val;
  284. char bad_second_val;
  285. /* Binary operators need two arguments */
  286. if (top_of_stack == numstack)
  287. goto err;
  288. /* ...and they pop one */
  289. NUMPTR = top_of_stack; /* this decrements NUMPTR */
  290. bad_second_val = top_of_stack->second_val_present;
  291. if (op == TOK_CONDITIONAL) { /* ? operation */
  292. /* Make next if (...) protect against
  293. * $((expr1 ? expr2)) - that is, missing ": expr" */
  294. bad_second_val = !bad_second_val;
  295. }
  296. if (bad_second_val) {
  297. /* Protect against $((expr <not_?_op> expr1 : expr2)) */
  298. return "malformed ?: operator";
  299. }
  300. top_of_stack--; /* now points to left side */
  301. if (op != TOK_ASSIGN) {
  302. /* Resolve left side value (unless the op is '=') */
  303. err = arith_lookup_val(math_state, top_of_stack);
  304. if (err)
  305. return err;
  306. }
  307. right_side_val = rez;
  308. rez = top_of_stack->val;
  309. if (op == TOK_CONDITIONAL) /* ? operation */
  310. rez = (rez ? right_side_val : top_of_stack[1].second_val);
  311. else if (op == TOK_CONDITIONAL_SEP) { /* : operation */
  312. if (top_of_stack == numstack) {
  313. /* Protect against $((expr : expr)) */
  314. return "malformed ?: operator";
  315. }
  316. top_of_stack->second_val_present = op;
  317. top_of_stack->second_val = right_side_val;
  318. }
  319. else if (op == TOK_BOR || op == TOK_OR_ASSIGN)
  320. rez |= right_side_val;
  321. else if (op == TOK_OR)
  322. rez = right_side_val || rez;
  323. else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
  324. rez &= right_side_val;
  325. else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
  326. rez ^= right_side_val;
  327. else if (op == TOK_AND)
  328. rez = rez && right_side_val;
  329. else if (op == TOK_EQ)
  330. rez = (rez == right_side_val);
  331. else if (op == TOK_NE)
  332. rez = (rez != right_side_val);
  333. else if (op == TOK_GE)
  334. rez = (rez >= right_side_val);
  335. else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
  336. rez >>= right_side_val;
  337. else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
  338. rez <<= right_side_val;
  339. else if (op == TOK_GT)
  340. rez = (rez > right_side_val);
  341. else if (op == TOK_LT)
  342. rez = (rez < right_side_val);
  343. else if (op == TOK_LE)
  344. rez = (rez <= right_side_val);
  345. else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
  346. rez *= right_side_val;
  347. else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
  348. rez += right_side_val;
  349. else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
  350. rez -= right_side_val;
  351. else if (op == TOK_ASSIGN || op == TOK_COMMA)
  352. rez = right_side_val;
  353. else if (op == TOK_EXPONENT) {
  354. arith_t c;
  355. if (right_side_val < 0)
  356. return "exponent less than 0";
  357. c = 1;
  358. while (--right_side_val >= 0)
  359. c *= rez;
  360. rez = c;
  361. }
  362. else if (right_side_val == 0)
  363. return "divide by zero";
  364. else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
  365. rez /= right_side_val;
  366. else if (op == TOK_REM || op == TOK_REM_ASSIGN)
  367. rez %= right_side_val;
  368. }
  369. if (is_assign_op(op)) {
  370. char buf[sizeof(arith_t)*3 + 2];
  371. if (top_of_stack->var == NULL) {
  372. /* Hmm, 1=2 ? */
  373. //TODO: actually, bash allows ++7 but for some reason it evals to 7, not 8
  374. goto err;
  375. }
  376. /* Save to shell variable */
  377. sprintf(buf, ARITH_FMT, rez);
  378. setvar(top_of_stack->var, buf);
  379. /* After saving, make previous value for v++ or v-- */
  380. if (op == TOK_POST_INC)
  381. rez--;
  382. else if (op == TOK_POST_DEC)
  383. rez++;
  384. }
  385. top_of_stack->val = rez;
  386. /* Erase var name, it is just a number now */
  387. top_of_stack->var = NULL;
  388. return NULL;
  389. err:
  390. return "arithmetic syntax error";
  391. #undef NUMPTR
  392. }
  393. /* longest must be first */
  394. static const char op_tokens[] ALIGN1 = {
  395. '<','<','=',0, TOK_LSHIFT_ASSIGN,
  396. '>','>','=',0, TOK_RSHIFT_ASSIGN,
  397. '<','<', 0, TOK_LSHIFT,
  398. '>','>', 0, TOK_RSHIFT,
  399. '|','|', 0, TOK_OR,
  400. '&','&', 0, TOK_AND,
  401. '!','=', 0, TOK_NE,
  402. '<','=', 0, TOK_LE,
  403. '>','=', 0, TOK_GE,
  404. '=','=', 0, TOK_EQ,
  405. '|','=', 0, TOK_OR_ASSIGN,
  406. '&','=', 0, TOK_AND_ASSIGN,
  407. '*','=', 0, TOK_MUL_ASSIGN,
  408. '/','=', 0, TOK_DIV_ASSIGN,
  409. '%','=', 0, TOK_REM_ASSIGN,
  410. '+','=', 0, TOK_PLUS_ASSIGN,
  411. '-','=', 0, TOK_MINUS_ASSIGN,
  412. '-','-', 0, TOK_POST_DEC,
  413. '^','=', 0, TOK_XOR_ASSIGN,
  414. '+','+', 0, TOK_POST_INC,
  415. '*','*', 0, TOK_EXPONENT,
  416. '!', 0, TOK_NOT,
  417. '<', 0, TOK_LT,
  418. '>', 0, TOK_GT,
  419. '=', 0, TOK_ASSIGN,
  420. '|', 0, TOK_BOR,
  421. '&', 0, TOK_BAND,
  422. '*', 0, TOK_MUL,
  423. '/', 0, TOK_DIV,
  424. '%', 0, TOK_REM,
  425. '+', 0, TOK_ADD,
  426. '-', 0, TOK_SUB,
  427. '^', 0, TOK_BXOR,
  428. /* uniq */
  429. '~', 0, TOK_BNOT,
  430. ',', 0, TOK_COMMA,
  431. '?', 0, TOK_CONDITIONAL,
  432. ':', 0, TOK_CONDITIONAL_SEP,
  433. ')', 0, TOK_RPAREN,
  434. '(', 0, TOK_LPAREN,
  435. 0
  436. };
  437. #define ptr_to_rparen (&op_tokens[sizeof(op_tokens)-7])
  438. const char* FAST_FUNC
  439. endofname(const char *name)
  440. {
  441. if (!is_name(*name))
  442. return name;
  443. while (*++name) {
  444. if (!is_in_name(*name))
  445. break;
  446. }
  447. return name;
  448. }
  449. static arith_t FAST_FUNC
  450. evaluate_string(arith_state_t *math_state, const char *expr)
  451. {
  452. operator lasttok;
  453. const char *errmsg;
  454. const char *start_expr = expr = skip_whitespace(expr);
  455. unsigned expr_len = strlen(expr) + 2;
  456. /* Stack of integers */
  457. /* The proof that there can be no more than strlen(startbuf)/2+1
  458. * integers in any given correct or incorrect expression
  459. * is left as an exercise to the reader. */
  460. var_or_num_t *const numstack = alloca((expr_len / 2) * sizeof(numstack[0]));
  461. var_or_num_t *numstackptr = numstack;
  462. /* Stack of operator tokens */
  463. operator *const stack = alloca(expr_len * sizeof(stack[0]));
  464. operator *stackptr = stack;
  465. /* Start with a left paren */
  466. *stackptr++ = lasttok = TOK_LPAREN;
  467. errmsg = NULL;
  468. while (1) {
  469. const char *p;
  470. operator op;
  471. operator prec;
  472. char arithval;
  473. expr = skip_whitespace(expr);
  474. arithval = *expr;
  475. if (arithval == '\0') {
  476. if (expr == start_expr) {
  477. /* Null expression */
  478. numstack->val = 0;
  479. goto ret;
  480. }
  481. /* This is only reached after all tokens have been extracted from the
  482. * input stream. If there are still tokens on the operator stack, they
  483. * are to be applied in order. At the end, there should be a final
  484. * result on the integer stack */
  485. if (expr != ptr_to_rparen + 1) {
  486. /* If we haven't done so already,
  487. * append a closing right paren
  488. * and let the loop process it */
  489. expr = ptr_to_rparen;
  490. continue;
  491. }
  492. /* At this point, we're done with the expression */
  493. if (numstackptr != numstack + 1) {
  494. /* ...but if there isn't, it's bad */
  495. goto err;
  496. }
  497. if (numstack->var) {
  498. /* expression is $((var)) only, lookup now */
  499. errmsg = arith_lookup_val(math_state, numstack);
  500. }
  501. goto ret;
  502. }
  503. p = endofname(expr);
  504. if (p != expr) {
  505. /* Name */
  506. size_t var_name_size = (p-expr) + 1; /* +1 for NUL */
  507. numstackptr->var = alloca(var_name_size);
  508. safe_strncpy(numstackptr->var, expr, var_name_size);
  509. expr = p;
  510. num:
  511. numstackptr->second_val_present = 0;
  512. numstackptr++;
  513. lasttok = TOK_NUM;
  514. continue;
  515. }
  516. if (isdigit(arithval)) {
  517. /* Number */
  518. numstackptr->var = NULL;
  519. errno = 0;
  520. numstackptr->val = strto_arith_t(expr, (char**) &expr, 0);
  521. if (errno)
  522. numstackptr->val = 0; /* bash compat */
  523. goto num;
  524. }
  525. /* Should be an operator */
  526. p = op_tokens;
  527. while (1) {
  528. // TODO: bash allows 7+++v, treats it as 7 + ++v
  529. // we treat it as 7++ + v and reject
  530. /* Compare expr to current op_tokens[] element */
  531. const char *e = expr;
  532. while (1) {
  533. if (*p == '\0') {
  534. /* Match: operator is found */
  535. expr = e;
  536. goto tok_found;
  537. }
  538. if (*p != *e)
  539. break;
  540. p++;
  541. e++;
  542. }
  543. /* No match, go to next element of op_tokens[] */
  544. while (*p)
  545. p++;
  546. p += 2; /* skip NUL and TOK_foo bytes */
  547. if (*p == '\0') {
  548. /* No next element, operator not found */
  549. //math_state->syntax_error_at = expr;
  550. goto err;
  551. }
  552. }
  553. tok_found:
  554. op = p[1]; /* fetch TOK_foo value */
  555. /* NB: expr now points past the operator */
  556. /* post grammar: a++ reduce to num */
  557. if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
  558. lasttok = TOK_NUM;
  559. /* Plus and minus are binary (not unary) _only_ if the last
  560. * token was a number, or a right paren (which pretends to be
  561. * a number, since it evaluates to one). Think about it.
  562. * It makes sense. */
  563. if (lasttok != TOK_NUM) {
  564. switch (op) {
  565. case TOK_ADD:
  566. op = TOK_UPLUS;
  567. break;
  568. case TOK_SUB:
  569. op = TOK_UMINUS;
  570. break;
  571. case TOK_POST_INC:
  572. op = TOK_PRE_INC;
  573. break;
  574. case TOK_POST_DEC:
  575. op = TOK_PRE_DEC;
  576. break;
  577. }
  578. }
  579. /* We don't want an unary operator to cause recursive descent on the
  580. * stack, because there can be many in a row and it could cause an
  581. * operator to be evaluated before its argument is pushed onto the
  582. * integer stack.
  583. * But for binary operators, "apply" everything on the operator
  584. * stack until we find an operator with a lesser priority than the
  585. * one we have just extracted. If op is right-associative,
  586. * then stop "applying" on the equal priority too.
  587. * Left paren is given the lowest priority so it will never be
  588. * "applied" in this way.
  589. */
  590. prec = PREC(op);
  591. if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
  592. /* not left paren or unary */
  593. if (lasttok != TOK_NUM) {
  594. /* binary op must be preceded by a num */
  595. goto err;
  596. }
  597. while (stackptr != stack) {
  598. operator prev_op = *--stackptr;
  599. if (op == TOK_RPAREN) {
  600. /* The algorithm employed here is simple: while we don't
  601. * hit an open paren nor the bottom of the stack, pop
  602. * tokens and apply them */
  603. if (prev_op == TOK_LPAREN) {
  604. /* Any operator directly after a
  605. * close paren should consider itself binary */
  606. lasttok = TOK_NUM;
  607. goto next;
  608. }
  609. } else {
  610. operator prev_prec = PREC(prev_op);
  611. fix_assignment_prec(prec);
  612. fix_assignment_prec(prev_prec);
  613. if (prev_prec < prec
  614. || (prev_prec == prec && is_right_associative(prec))
  615. ) {
  616. stackptr++;
  617. break;
  618. }
  619. }
  620. errmsg = arith_apply(math_state, prev_op, numstack, &numstackptr);
  621. if (errmsg)
  622. goto err_with_custom_msg;
  623. }
  624. if (op == TOK_RPAREN)
  625. goto err;
  626. }
  627. /* Push this operator to the stack and remember it */
  628. *stackptr++ = lasttok = op;
  629. next: ;
  630. } /* while (1) */
  631. err:
  632. errmsg = "arithmetic syntax error";
  633. err_with_custom_msg:
  634. numstack->val = -1;
  635. ret:
  636. math_state->errmsg = errmsg;
  637. return numstack->val;
  638. }
  639. arith_t FAST_FUNC
  640. arith(arith_state_t *math_state, const char *expr)
  641. {
  642. math_state->errmsg = NULL;
  643. math_state->list_of_recursed_names = NULL;
  644. return evaluate_string(math_state, expr);
  645. }
  646. /*
  647. * Copyright (c) 1989, 1991, 1993, 1994
  648. * The Regents of the University of California. All rights reserved.
  649. *
  650. * This code is derived from software contributed to Berkeley by
  651. * Kenneth Almquist.
  652. *
  653. * Redistribution and use in source and binary forms, with or without
  654. * modification, are permitted provided that the following conditions
  655. * are met:
  656. * 1. Redistributions of source code must retain the above copyright
  657. * notice, this list of conditions and the following disclaimer.
  658. * 2. Redistributions in binary form must reproduce the above copyright
  659. * notice, this list of conditions and the following disclaimer in the
  660. * documentation and/or other materials provided with the distribution.
  661. * 3. Neither the name of the University nor the names of its contributors
  662. * may be used to endorse or promote products derived from this software
  663. * without specific prior written permission.
  664. *
  665. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  666. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  667. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  668. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  669. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  670. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  671. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  672. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  673. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  674. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  675. * SUCH DAMAGE.
  676. */