math.c 21 KB

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