home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / sh-utils-1.12-src.tgz / tar.out / fsf / sh-utils / src / expr.c < prev    next >
C/C++ Source or Header  |  1996-09-28  |  14KB  |  766 lines

  1. /* expr -- evaluate expressions.
  2.    Copyright (C) 1986, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Author: Mike Parker.
  19.  
  20.    This program evaluates expressions.  Each token (operator, operand,
  21.    parenthesis) of the expression must be a seperate argument.  The
  22.    parser used is a reasonably general one, though any incarnation of
  23.    it is language-specific.  It is especially nice for expressions.
  24.  
  25.    No parse tree is needed; a new node is evaluated immediately.
  26.    One function can handle multiple operators all of equal precedence,
  27.    provided they all associate ((x op x) op x).
  28.  
  29.    Define EVAL_TRACE to print an evaluation trace.  */
  30.  
  31. #include <config.h>
  32. #include <stdio.h>
  33. #include <sys/types.h>
  34. #include <regex.h>
  35.  
  36. #include "system.h"
  37. #include "version.h"
  38. #include "long-options.h"
  39.  
  40. #define NEW(type) ((type *) xmalloc (sizeof (type)))
  41. #define OLD(x) free ((char *) x)
  42.  
  43. /* The kinds of value we can have.  */
  44. enum valtype
  45. {
  46.   integer,
  47.   string
  48. };
  49. typedef enum valtype TYPE;
  50.  
  51. /* A value is.... */
  52. struct valinfo
  53. {
  54.   TYPE type;            /* Which kind. */
  55.   union
  56.   {                /* The value itself. */
  57.     int i;
  58.     char *s;
  59.   } u;
  60. };
  61. typedef struct valinfo VALUE;
  62.  
  63. /* The arguments given to the program, minus the program name.  */
  64. static char **args;
  65.  
  66. /* The name this program was run with. */
  67. char *program_name;
  68.  
  69. void error ();
  70. char *xstrdup ();
  71. char *strstr ();
  72. char *xmalloc ();
  73.  
  74. static VALUE *docolon ();
  75. static VALUE *eval ();
  76. static VALUE *int_value ();
  77. static VALUE *str_value ();
  78. static int isstring ();
  79. static int nextarg ();
  80. static int nomoreargs ();
  81. static int null ();
  82. static int toarith ();
  83. static void freev ();
  84. static void printv ();
  85. static void tostring ();
  86.  
  87. #ifdef EVAL_TRACE
  88. static void trace ();
  89. #endif
  90.  
  91. static void
  92. usage (status)
  93.      int status;
  94. {
  95.   if (status != 0)
  96.     fprintf (stderr, "Try `%s --help' for more information.\n",
  97.          program_name);
  98.   else
  99.     {
  100.       printf ("\
  101. Usage: %s EXPRESSION\n\
  102.   or:  %s OPTION\n\
  103. ",
  104.           program_name, program_name);
  105.       printf ("\
  106. \n\
  107.   --help      display this help and exit\n\
  108.   --version   output version information and exit\n\
  109. \n\
  110. ");
  111.       printf ("\
  112. EXPRESSION value is written on standard output.  A white line\n\
  113. separates increasing precedence groups.  EXPRESSION may be:\n\
  114. \n\
  115.   ARG1 | ARG2       ARG1 if it is neither null nor 0, otherwise ARG2\n\
  116. \n\
  117.   ARG1 & ARG2       ARG1 if neither argument is null or 0, otherwise 0\n\
  118. \n\
  119.   ARG1 < ARG2       ARG1 is less than ARG2\n\
  120.   ARG1 <= ARG2      ARG1 is less than or equal to ARG2\n\
  121.   ARG1 = ARG2       ARG1 is equal to ARG2\n\
  122.   ARG1 != ARG2      ARG1 is unequal to ARG2\n\
  123.   ARG1 >= ARG2      ARG1 is greater than or equal to ARG2\n\
  124.   ARG1 > ARG2       ARG1 is greater than ARG2\n\
  125. \n\
  126.   ARG1 + ARG2       arithmetic sum of ARG1 and ARG2\n\
  127.   ARG1 - ARG2       arithmetic difference of ARG1 and ARG2\n\
  128. \n\
  129.   ARG1 * ARG2       arithmetic product of ARG1 and ARG2\n\
  130.   ARG1 / ARG2       arithmetic quotient of ARG1 divided by ARG2\n\
  131.   ARG1 %% ARG2       arithmetic remainder of ARG1 divided by ARG2\n\
  132. \n\
  133.   STRING : REGEXP   anchored pattern match of REGEXP in STRING\n\
  134. \n\
  135.   match STRING REGEXP        same as STRING : REGEXP\n\
  136.   substr STRING POS LENGTH   substring of STRING, POS counted from 1\n\
  137.   index STRING CHARS         index in STRING where any CHARS is found, or 0\n\
  138.   length STRING              length of STRING\n\
  139. \n\
  140.   ( EXPRESSION )             value of EXPRESSION\n\
  141. ");
  142.       printf ("\
  143. \n\
  144. Beware that some operators need to be escaped by backslashes for shells.\n\
  145. Comparisons are arithmetic if both ARGs are numbers, else lexicographical.\n\
  146. Pattern matches return the string matched between \\( and \\) or null; if\n\
  147. \\( and \\) are not used, they return the number of characters matched or 0.\n\
  148. ");
  149.     }
  150.   exit (status);
  151. }
  152.  
  153. main (argc, argv)
  154.      int argc;
  155.      char **argv;
  156. {
  157.   VALUE *v;
  158.  
  159.   program_name = argv[0];
  160.  
  161.   parse_long_options (argc, argv, "expr", version_string, usage);
  162.  
  163.   if (argc == 1)
  164.     {
  165.       error (0, 0, "too few arguments");
  166.       usage (1);
  167.     }
  168.  
  169.   args = argv + 1;
  170.  
  171.   v = eval ();
  172.   if (!nomoreargs ())
  173.     error (2, 0, "syntax error");
  174.   printv (v);
  175.  
  176.   exit (null (v));
  177. }
  178.  
  179. /* Return a VALUE for I.  */
  180.  
  181. static VALUE *
  182. int_value (i)
  183.      int i;
  184. {
  185.   VALUE *v;
  186.  
  187.   v = NEW (VALUE);
  188.   v->type = integer;
  189.   v->u.i = i;
  190.   return v;
  191. }
  192.  
  193. /* Return a VALUE for S.  */
  194.  
  195. static VALUE *
  196. str_value (s)
  197.      char *s;
  198. {
  199.   VALUE *v;
  200.  
  201.   v = NEW (VALUE);
  202.   v->type = string;
  203.   v->u.s = xstrdup (s);
  204.   return v;
  205. }
  206.  
  207. /* Free VALUE V, including structure components.  */
  208.  
  209. static void
  210. freev (v)
  211.      VALUE *v;
  212. {
  213.   if (v->type == string)
  214.     free (v->u.s);
  215.   OLD (v);
  216. }
  217.  
  218. /* Print VALUE V.  */
  219.  
  220. static void
  221. printv (v)
  222.      VALUE *v;
  223. {
  224.   switch (v->type)
  225.     {
  226.     case integer:
  227.       printf ("%d\n", v->u.i);
  228.       break;
  229.     case string:
  230.       printf ("%s\n", v->u.s);
  231.       break;
  232.     default:
  233.       abort ();
  234.     }
  235. }
  236.  
  237. /* Return nonzero if V is a null-string or zero-number.  */
  238.  
  239. static int
  240. null (v)
  241.      VALUE *v;
  242. {
  243.   switch (v->type)
  244.     {
  245.     case integer:
  246.       return v->u.i == 0;
  247.     case string:
  248.       return v->u.s[0] == '\0' || strcmp(v->u.s, "0") == 0;
  249.     default:
  250.       abort ();
  251.     }
  252. }
  253.  
  254. /* Return nonzero if V is a string value.  */
  255.  
  256. static int
  257. isstring (v)
  258.      VALUE *v;
  259. {
  260.   return v->type == string;
  261. }
  262.  
  263. /* Coerce V to a string value (can't fail).  */
  264.  
  265. static void
  266. tostring (v)
  267.      VALUE *v;
  268. {
  269.   char *temp;
  270.  
  271.   switch (v->type)
  272.     {
  273.     case integer:
  274.       temp = xmalloc (4 * (sizeof (int) / sizeof (char)));
  275.       sprintf (temp, "%d", v->u.i);
  276.       v->u.s = temp;
  277.       v->type = string;
  278.       break;
  279.     case string:
  280.       break;
  281.     default:
  282.       abort ();
  283.     }
  284. }
  285.  
  286. /* Coerce V to an integer value.  Return 1 on success, 0 on failure.  */
  287.  
  288. static int
  289. toarith (v)
  290.      VALUE *v;
  291. {
  292.   int i;
  293.   int neg;
  294.   char *cp;
  295.  
  296.   switch (v->type)
  297.     {
  298.     case integer:
  299.       return 1;
  300.     case string:
  301.       i = 0;
  302.       cp = v->u.s;
  303.       /* Don't interpret the empty string as an integer.  */
  304.       if (*cp == 0)
  305.     return 0;
  306.       neg = (*cp == '-');
  307.       if (neg)
  308.     cp++;
  309.       for (; *cp; cp++)
  310.     {
  311.       if (ISDIGIT (*cp))
  312.         i = i * 10 + *cp - '0';
  313.       else
  314.         return 0;
  315.     }
  316.       free (v->u.s);
  317.       v->u.i = i * (neg ? -1 : 1);
  318.       v->type = integer;
  319.       return 1;
  320.     default:
  321.       abort ();
  322.     }
  323. }
  324.  
  325. /* Return nonzero if the next token matches STR exactly.
  326.    STR must not be NULL.  */
  327.  
  328. static int
  329. nextarg (str)
  330.      char *str;
  331. {
  332.   if (*args == NULL)
  333.     return 0;
  334.   return strcmp (*args, str) == 0;
  335. }
  336.  
  337. /* Return nonzero if there no more tokens.  */
  338.  
  339. static int
  340. nomoreargs ()
  341. {
  342.   return *args == 0;
  343. }
  344.  
  345. /* The comparison operator handling functions.  */
  346.  
  347. #define cmpf(name, rel)                \
  348. static                        \
  349. int name (l, r) VALUE *l; VALUE *r;        \
  350. {                        \
  351.   if (isstring (l) || isstring (r))        \
  352.     {                        \
  353.        tostring (l);                \
  354.        tostring (r);                \
  355.        return strcmp (l->u.s, r->u.s) rel 0;    \
  356.     }                        \
  357.  else                        \
  358.    return l->u.i rel r->u.i;            \
  359. }
  360. cmpf (less_than, <)
  361. cmpf (less_equal, <=)
  362. cmpf (equal, ==)
  363. cmpf (not_equal, !=)
  364. cmpf (greater_equal, >=)
  365. cmpf (greater_than, >)
  366.  
  367. #undef cmpf
  368.  
  369. /* The arithmetic operator handling functions.  */
  370.  
  371. #define arithf(name, op)            \
  372. static                        \
  373. int name (l, r) VALUE *l; VALUE *r;        \
  374. {                        \
  375.   if (!toarith (l) || !toarith (r))        \
  376.     error (2, 0, "non-numeric argument");    \
  377.   return l->u.i op r->u.i;            \
  378. }
  379.  
  380. #define arithdivf(name, op)            \
  381. int name (l, r) VALUE *l; VALUE *r;        \
  382. {                        \
  383.   if (!toarith (l) || !toarith (r))        \
  384.     error (2, 0, "non-numeric argument");    \
  385.   if (r->u.i == 0)                \
  386.     error (2, 0, "division by zero");        \
  387.   return l->u.i op r->u.i;            \
  388. }
  389.  
  390. arithf (plus, +)
  391. arithf (minus, -)
  392. arithf (multiply, *)
  393. arithdivf (divide, /)
  394. arithdivf (mod, %)
  395.  
  396. #undef arithf
  397. #undef arithdivf
  398.  
  399. #ifdef EVAL_TRACE
  400. /* Print evaluation trace and args remaining.  */
  401.  
  402. static void
  403. trace (fxn)
  404.      char *fxn;
  405. {
  406.   char **a;
  407.  
  408.   printf ("%s:", fxn);
  409.   for (a = args; *a; a++)
  410.     printf (" %s", *a);
  411.   putchar ('\n');
  412. }
  413. #endif
  414.  
  415. /* Do the : operator.
  416.    SV is the VALUE for the lhs (the string),
  417.    PV is the VALUE for the rhs (the pattern).  */
  418.  
  419. static VALUE *
  420. docolon (sv, pv)
  421.      VALUE *sv;
  422.      VALUE *pv;
  423. {
  424.   VALUE *v;
  425.   const char *errmsg;
  426.   struct re_pattern_buffer re_buffer;
  427.   struct re_registers re_regs;
  428.   int len;
  429.  
  430.   tostring (sv);
  431.   tostring (pv);
  432.  
  433.   len = strlen (pv->u.s);
  434.   re_buffer.allocated = 2 * len;
  435.   re_buffer.buffer = (unsigned char *) xmalloc (re_buffer.allocated);
  436.   re_buffer.translate = 0;
  437.   errmsg = re_compile_pattern (pv->u.s, len, &re_buffer);
  438.   if (errmsg)
  439.     error (2, 0, "%s", errmsg);
  440.  
  441.   len = re_match (&re_buffer, sv->u.s, strlen (sv->u.s), 0, &re_regs);
  442.   if (len >= 0)
  443.     {
  444.       /* Were \(...\) used? */
  445.       if (re_buffer.re_nsub > 0)/* was (re_regs.start[1] >= 0) */
  446.     {
  447.       sv->u.s[re_regs.end[1]] = '\0';
  448.       v = str_value (sv->u.s + re_regs.start[1]);
  449.     }
  450.       else
  451.     v = int_value (len);
  452.     }
  453.   else
  454.     {
  455.       /* Match failed -- return the right kind of null.  */
  456.       if (strstr (pv->u.s, "\\("))
  457.     v = str_value ("");
  458.       else
  459.     v = int_value (0);
  460.     }
  461.   free (re_buffer.buffer);
  462.   return v;
  463. }
  464.  
  465. /* Handle bare operands and ( expr ) syntax.  */
  466.  
  467. static VALUE *
  468. eval7 ()
  469. {
  470.   VALUE *v;
  471.  
  472. #ifdef EVAL_TRACE
  473.   trace ("eval7");
  474. #endif
  475.   if (nomoreargs ())
  476.     error (2, 0, "syntax error");
  477.  
  478.   if (nextarg ("("))
  479.     {
  480.       args++;
  481.       v = eval ();
  482.       if (!nextarg (")"))
  483.     error (2, 0, "syntax error");
  484.       args++;
  485.       return v;
  486.     }
  487.  
  488.   if (nextarg (")"))
  489.     error (2, 0, "syntax error");
  490.  
  491.   return str_value (*args++);
  492. }
  493.  
  494. /* Handle match, substr, index, and length keywords.  */
  495.  
  496. static VALUE *
  497. eval6 ()
  498. {
  499.   VALUE *l;
  500.   VALUE *r;
  501.   VALUE *v;
  502.   VALUE *i1;
  503.   VALUE *i2;
  504.  
  505. #ifdef EVAL_TRACE
  506.   trace ("eval6");
  507. #endif
  508.   if (nextarg ("length"))
  509.     {
  510.       args++;
  511.       r = eval6 ();
  512.       tostring (r);
  513.       v = int_value (strlen (r->u.s));
  514.       freev (r);
  515.       return v;
  516.     }
  517.   else if (nextarg ("match"))
  518.     {
  519.       args++;
  520.       l = eval6 ();
  521.       r = eval6 ();
  522.       v = docolon (l, r);
  523.       freev (l);
  524.       freev (r);
  525.       return v;
  526.     }
  527.   else if (nextarg ("index"))
  528.     {
  529.       args++;
  530.       l = eval6 ();
  531.       r = eval6 ();
  532.       tostring (l);
  533.       tostring (r);
  534.       v = int_value (strcspn (l->u.s, r->u.s) + 1);
  535.       if (v->u.i == strlen (l->u.s) + 1)
  536.     v->u.i = 0;
  537.       freev (l);
  538.       freev (r);
  539.       return v;
  540.     }
  541.   else if (nextarg ("substr"))
  542.     {
  543.       args++;
  544.       l = eval6 ();
  545.       i1 = eval6 ();
  546.       i2 = eval6 ();
  547.       tostring (l);
  548.       if (!toarith (i1) || !toarith (i2)
  549.       || i1->u.i > strlen (l->u.s)
  550.       || i1->u.i <= 0 || i2->u.i <= 0)
  551.     v = str_value ("");
  552.       else
  553.     {
  554.       v = NEW (VALUE);
  555.       v->type = string;
  556.       v->u.s = strncpy ((char *) xmalloc (i2->u.i + 1),
  557.                 l->u.s + i1->u.i - 1, i2->u.i);
  558.       v->u.s[i2->u.i] = 0;
  559.     }
  560.       freev (l);
  561.       freev (i1);
  562.       freev (i2);
  563.       return v;
  564.     }
  565.   else
  566.     return eval7 ();
  567. }
  568.  
  569. /* Handle : operator (pattern matching).
  570.    Calls docolon to do the real work.  */
  571.  
  572. static VALUE *
  573. eval5 ()
  574. {
  575.   VALUE *l;
  576.   VALUE *r;
  577.   VALUE *v;
  578.  
  579. #ifdef EVAL_TRACE
  580.   trace ("eval5");
  581. #endif
  582.   l = eval6 ();
  583.   while (1)
  584.     {
  585.       if (nextarg (":"))
  586.     {
  587.       args++;
  588.       r = eval6 ();
  589.       v = docolon (l, r);
  590.       freev (l);
  591.       freev (r);
  592.       l = v;
  593.     }
  594.       else
  595.     return l;
  596.     }
  597. }
  598.  
  599. /* Handle *, /, % operators.  */
  600.  
  601. static VALUE *
  602. eval4 ()
  603. {
  604.   VALUE *l;
  605.   VALUE *r;
  606.   int (*fxn) ();
  607.   int val;
  608.  
  609. #ifdef EVAL_TRACE
  610.   trace ("eval4");
  611. #endif
  612.   l = eval5 ();
  613.   while (1)
  614.     {
  615.       if (nextarg ("*"))
  616.     fxn = multiply;
  617.       else if (nextarg ("/"))
  618.     fxn = divide;
  619.       else if (nextarg ("%"))
  620.     fxn = mod;
  621.       else
  622.     return l;
  623.       args++;
  624.       r = eval5 ();
  625.       val = (*fxn) (l, r);
  626.       freev (l);
  627.       freev (r);
  628.       l = int_value (val);
  629.     }
  630. }
  631.  
  632. /* Handle +, - operators.  */
  633.  
  634. static VALUE *
  635. eval3 ()
  636. {
  637.   VALUE *l;
  638.   VALUE *r;
  639.   int (*fxn) ();
  640.   int val;
  641.  
  642. #ifdef EVAL_TRACE
  643.   trace ("eval3");
  644. #endif
  645.   l = eval4 ();
  646.   while (1)
  647.     {
  648.       if (nextarg ("+"))
  649.     fxn = plus;
  650.       else if (nextarg ("-"))
  651.     fxn = minus;
  652.       else
  653.     return l;
  654.       args++;
  655.       r = eval4 ();
  656.       val = (*fxn) (l, r);
  657.       freev (l);
  658.       freev (r);
  659.       l = int_value (val);
  660.     }
  661. }
  662.  
  663. /* Handle comparisons.  */
  664.  
  665. static VALUE *
  666. eval2 ()
  667. {
  668.   VALUE *l;
  669.   VALUE *r;
  670.   int (*fxn) ();
  671.   int val;
  672.  
  673. #ifdef EVAL_TRACE
  674.   trace ("eval2");
  675. #endif
  676.   l = eval3 ();
  677.   while (1)
  678.     {
  679.       if (nextarg ("<"))
  680.     fxn = less_than;
  681.       else if (nextarg ("<="))
  682.     fxn = less_equal;
  683.       else if (nextarg ("=") || nextarg ("=="))
  684.     fxn = equal;
  685.       else if (nextarg ("!="))
  686.     fxn = not_equal;
  687.       else if (nextarg (">="))
  688.     fxn = greater_equal;
  689.       else if (nextarg (">"))
  690.     fxn = greater_than;
  691.       else
  692.     return l;
  693.       args++;
  694.       r = eval3 ();
  695.       toarith (l);
  696.       toarith (r);
  697.       val = (*fxn) (l, r);
  698.       freev (l);
  699.       freev (r);
  700.       l = int_value (val);
  701.     }
  702. }
  703.  
  704. /* Handle &.  */
  705.  
  706. static VALUE *
  707. eval1 ()
  708. {
  709.   VALUE *l;
  710.   VALUE *r;
  711.  
  712. #ifdef EVAL_TRACE
  713.   trace ("eval1");
  714. #endif
  715.   l = eval2 ();
  716.   while (1)
  717.     {
  718.       if (nextarg ("&"))
  719.     {
  720.       args++;
  721.       r = eval2 ();
  722.       if (null (l) || null (r))
  723.         {
  724.           freev (l);
  725.           freev (r);
  726.           l = int_value (0);
  727.         }
  728.       else
  729.         freev (r);
  730.     }
  731.       else
  732.     return l;
  733.     }
  734. }
  735.  
  736. /* Handle |.  */
  737.  
  738. static VALUE *
  739. eval ()
  740. {
  741.   VALUE *l;
  742.   VALUE *r;
  743.  
  744. #ifdef EVAL_TRACE
  745.   trace ("eval");
  746. #endif
  747.   l = eval1 ();
  748.   while (1)
  749.     {
  750.       if (nextarg ("|"))
  751.     {
  752.       args++;
  753.       r = eval1 ();
  754.       if (null (l))
  755.         {
  756.           freev (l);
  757.           l = r;
  758.         }
  759.       else
  760.         freev (r);
  761.     }
  762.       else
  763.     return l;
  764.     }
  765. }
  766.