math.c 21 KB

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