Logo Search packages:      
Sourcecode: mathomatic version File versions

parse.c

/*
 * Algebraic manipulator help command and parsing routines.
 *
 * Copyright (c) 1996 George Gesslein II.
 */

#include "am.h"
#include "externs.h"

/* The Mathomatic command list follows.  It must be in alphabetical order. */
com_type    com_list[] = {
      "calculate",      calculate,  "[variable number-of-iterations]",        "Temporarily plug values into the RHS and display.  Option to iterate.",
      "clear",    clear,            "[equation-number-range]",                "Delete equations so equation space can be reused.",
      "code",           list_code,  "[\"c\" or \"java\" or \"integer\"] [equation-number-range]",     "Output C or Java code for the specified equations.",
      "compare",  compare,    "equation-number [\"with\" equation-number]",   "Compare two equations to see if they are the same.",
      "copy",           copy_cmd,   "[equation-number-range]",                "Duplicate the specified equations.",
      "derivative",     derivative, "variable or \"all\" [order]",                  "Differentiate the RHS of the current equation, order times.",
      "divide",   divide_cmd, "[variable]",                             "Prompt for 2 polynomials/numbers and divide.  Display result and GCD.",
#if   (UNIX || CYGWIN) && !SECURE
      "edit",           edit,       "[file-name]",                            "Edit your equations or an input file.",
#endif
      "eliminate",      eliminate,  "variables or \"all\" [\"using\" equation-number]",   "Substitute the specified variables with solved equations.",
      "extrema",  extrema_cmd,      "variable",                         "Find the minimums and maximums of the current equation.",
      "factor",   factor,           "[\"number\" [integers]] or [equation-number-range] [variables]", "Factor integers or equations.  For polynomial factoring, use \"simplify\".",
      "group",    group_cmd,  "[\"factor\"] [equation-number-range]",         "Display equations in fraction format.  Option to factor integers.",
      "help",           help,       "[topic or command-name]",                "Short, built-in help.",
      "imaginary",      imaginary,  "[equation-number]",                      "Copy the imaginary part of an equation (see the \"real\" command).",
      "integrate",      integrate_cmd,    "variable [order]",                       "Integrate the RHS of the current equation, order times.",
      "laplace",  laplace_cmd,      "[\"inverse\"] variable",                 "Compute the Laplace or inverse Laplace transform of the RHS.",
      "limit",    limit_cmd,  "variable expression",                    "Take the limit of the current equation as variable goes to expression.",
      "list",           list_cmd,   "[\"export\"] [equation-number-range]",         "Display equations in single line format.  Option for exportable format.",
      "optimize", optimize_cmd,     "[equation-number]",                      "Split up an equation into smaller multiple equations.",
      "pause",    pause_cmd,  "",                                 "Wait for user to press the Enter key.",
      "product",  product_cmd,      "variable low high",                      "Compute the product of the RHS of the current equation.",
      "quit",           quit,       "",                                 "Terminate this program.  All equations in memory are lost.",
#if   !SECURE
      "read",           read_in,    "file-name",                              "Read in a text file as if it was typed in.",
#endif
      "real",           real,       "[equation-number]",                      "Copy the real part of an equation (see the \"imaginary\" command).",
      "replace",  replace,    "[variables [\"with\" expression]]",            "Substitute variables in both sides of an equation with expressions.",
      "roots",    roots,            "",                                 "Display all the roots of a complex number.",
#if   !SECURE
      "save",           save,       "file-name",                              "Save all equations in a text file (restore with the \"read\" command).",
#endif
      "sensitivity",    sensitivity,      "variables",                              "Compute the exact sensitivity equation.",
      "set",            set_cmd,    "[\"no\"] [option]",                      "Set various session options.",
      "simplify", simplify,   "[\"symbolic\" or \"quick\" or \"poly\"] [equation-number-range]",      "Completely simplify equations.",
      "sum",            sum_cmd,    "variable low high",                      "Compute the summation of the RHS of the current equation.",
      "tally",    tally,            "",                                 "Prompt for and add numerical entries.  Show running total.",
      "taylor",   taylor,           "variable",                         "Compute the Taylor series expansion of the RHS, with respect to variable.",
      "unfactor", unfactor,   "[\"fully\"] [equation-number-range]",          "Expand equations."
};

int   point_flag; /* point to error if true */

/*
 * Process a line of input to Mathomatic.
 * It may be a command, an equation, etc.
 * Return true if successful.
 */
int
process(cp)
char  *cp;
{
      char  *cp1, *cp2;
      char  *cp_start;
      int   i, j;
      int   n;
      int   simp_flag;
      int   rv;
      char  buf2[MAX_CMD_LEN];
      int   i1;
      char  *filename;
      FILE  *fp;
      int   append_flag;

      set_sign_array();
      cp_start = cp;
      simp_flag = true;
      set_error_level(cp);
      cp = skip_space(cp);
      if (*cp == '#') {
            cp++;
            if (isascii(*cp) && isdigit(*cp)) {
                  i = atoi(cp) - 1;
                  if (i < 0 || i >= n_equations) {
                        put_up_arrow((int) (cp - cp_start));
                        printf(_("Equation number out of range.\n"));
                        return false;
                  }
                  cp = skip_num(cp);
                  if (*cp == ':') {
                        simp_flag = false;
                        cp++;
                  }
                  cp = skip_space(cp);
                  if (*cp) {
                        n = i;
                        goto e_parse;
                  }
                  cur_equation = i;
                  list_sub(cur_equation);
            }
            return true;
      }
#if   !SECURE
      if (*cp == '!') {
            cp++;
            cp = skip_space(cp);
            if (*cp) {
                  return(!shell_out(cp));
            }
            cp1 = getenv("SHELL");
            if (cp1) {
                  return(!shell_out(cp1));
            }
            return false;
      }
#endif
/* See if the string pointed to by "cp" is a command. */
/* If so, execute it. */
      cp1 = cp;
      while (*cp1 && isascii(*cp1) && isalpha(*cp1))
            cp1++;
      for (i = 0; i < ARR_CNT(com_list); i++) {
            if (strlen(com_list[i].name) < 4) {
                  if ((cp1 - cp) != strlen(com_list[i].name))
                        continue;
            } else {
                  if ((cp1 - cp) < 4)
                        continue;
            }
            if (strncasecmp(cp, com_list[i].name, cp1 - cp) == 0) {
                  cp1 = skip_space(cp1);
                  input_column += (cp1 - cp_start);
                  for (cp2 = cp1, j = 0; *cp2; cp2++, j++) {
                        if (j >= (sizeof(buf2) - 1)) {
                              printf(_("Error: Command line too long.\n"));
                              return false;
                        }
                        buf2[j] = *cp2;
                  }
                  buf2[j] = '\0';
                  cp2 = buf2;
                  fp = NULL;
#if   !SECURE
                  append_flag = false;
                  filename = NULL;
                  for (i1 = strlen(cp2) - 1; i1 >= 0; i1--) {
                        if (cp2[i1] == '>') {
                              filename = skip_space(&cp2[i1+1]);
                              if (i1 && cp2[i1-1] == '>') {
                                    i1--;
                                    append_flag = true;
                              }
                              cp2[i1] = '\0';
                              break;
                        }
                  }
                  if (filename) {
                        if (append_flag) {
                              fp = fopen(filename, "a");
                        } else {
                              fp = fopen(filename, "w");
                        }
                        if (fp == NULL) {
                              printf(_("Can't open '%s' for writing.\n"), filename);
                              return false;
                        }
                        gfp = fp;
                  }
#endif
/* remove trailing spaces from the command line */
                    i1 = strlen(cp2) - 1;
                    while (i1 >= 0 && isascii(cp2[i1]) && isspace(cp2[i1])) {
                          cp2[i1] = '\0';
                        i1--;
                  }
/* execute the command */
                  rv = (*com_list[i].func)(cp2);
#if   !SECURE
                  if (fp) {   /* if output redirected, close file */
                        if (gfp != stdout)
                              fclose(gfp);
                        else
                              fclose(fp);
                        gfp = stdout;
                  }
#endif
#if   false
                  if (!rv) {
                        printf(_("Usage: %s %s\n"), com_list[i].name, com_list[i].usage);
                  }
#endif
                  return rv;
            }
      }
/* "cp" is not a command, so parse the expression or equation. */
      n = next_espace();
e_parse:
      if (!case_sensitive_flag) {
            str_tolower(cp);
      }
      input_column += (cp - cp_start);
      cp_start = cp;
      if ((cp = parse_section(lhs[n], &n_lhs[n], cp)) != NULL) {
            input_column += (cp - cp_start);
            if ((cp = parse_section(rhs[n], &n_rhs[n], cp)) != NULL) {
                  if (n_lhs[n] == 0 && n_rhs[n] == 0)
                        return true;
                  if (n_lhs[n] == 0 || n_rhs[n] == 0) {
                        if ((n_lhs[n] == 1 && (lhs[n][0].kind != CONSTANT || lhs[n][0].token.constant == 0.0)
                            && !(lhs[n][0].kind == VARIABLE && lhs[n][0].token.variable < IMAGINARY))
                            || (n_rhs[n] == 1 && (rhs[n][0].kind != CONSTANT || rhs[n][0].token.constant == 0.0)
                            && !(rhs[n][0].kind == VARIABLE && rhs[n][0].token.variable < IMAGINARY))) {
                              if (solve(n, cur_equation)) {
                                    list_sub(cur_equation);
                                    return true;
                              }
                              return false;
                        }
                        if (n_lhs[n]) {
                              blt(rhs[n], lhs[n], n_lhs[n] * sizeof(token_type));
                              n_rhs[n] = n_lhs[n];
                        }
                        lhs[n][0].level = 1;
                        lhs[n][0].kind = VARIABLE;
                        lhs[n][0].token.variable = SPECIAL;
                        n_lhs[n] = 1;
                        for (i = 0; i < n_rhs[n]; i += 2) {
                              if (rhs[n][i].kind == VARIABLE
                                  && (rhs[n][i].token.variable & VAR_MASK) > SIGN) {
                                    printf(_("You may enter a numerical expression, or an algebraic equation,\n"));
                                    printf(_("or a variable to solve for, or a command (like \"help\" or \"quit\").\n"));
                                    n_lhs[n] = 0;
                                    return false;
                              }
                        }
                        i = cur_equation;
                        cur_equation = n;
                        calculate("");
                        cur_equation = i;
                        n_lhs[n] = 0;
                        return true;
                  }
                  cur_equation = n;
                  if (simp_flag) {
                        simp_sub(n);
                  } else {
                        organize(lhs[n], &n_lhs[n]);
                        organize(rhs[n], &n_rhs[n]);
                  }
                  list_sub(cur_equation);
                  return true;
            }
      }
      n_lhs[n] = 0;
      return false;
}

#if   !SECURE
/*
 * Execute a system command.
 * Returns exit value of command (0 if no error).
 */
int
shell_out(cp)
char  *cp;
{
      int   rv;

      reset_attr();
      rv = system(cp);
      default_color();
      return rv;
}
#endif

#include "parse.h"

char  *
parse_var2(vp, cp)
long  *vp;
char  *cp;
{
      char  *cp1;

      cp = skip_space(cp);
      cp = parse_var(vp, cp);
      if (cp == NULL) {
            printf(_("Invalid variable.\n"));
            return NULL;
      }
      if (*cp) {
            cp1 = skip_space(cp);
            if (cp == cp1) {
                  printf(_("Please separate variables with spaces.\n"));
                  return NULL;
            }
            return cp1;
      }
      return cp;
}

set_error_level(cp)
char  *cp;
{
      char  *cp1;

      point_flag = true;
/* remove trailing newlines */
      cp1 = &cp[strlen(cp)];
      while (cp1 != cp) {
            cp1--;
            if (*cp1 == '\n' || *cp1 == '\r') {
                  *cp1 = '\0';
            } else
                  break;
      }
/* don't point to error if input contains tabs */
      for (cp1 = cp; *cp1; cp1++) {
            if (isspace(*cp1) && *cp1 != ' ') {
                  point_flag = false;
                  break;
            }
      }
/* handle comments */
      for (cp1 = cp; *cp1; cp1++) {
            if (*cp1 == ';') {
                  *cp1 = '\0';
                  break;
            }
      }
}

/*
 * Display an up arrow pointing to the error under the input string.
 */
put_up_arrow(cnt)
int   cnt;  /* position of error, relative to "input_column" */
{
      int    i;

      if (piping_in_flag)
            return;
      if (!point_flag)
            return;
      for (i = 0; i < (input_column + cnt); i++) {
            printf(" ");
      }
      printf("^ ");
}

/*
 * Return true if the first word in the passed string is "all".
 */
int
is_all(cp)
char  *cp;
{
      return(strcmp_tospace(cp, "all") == 0);
}

/*
 * Process an equation number range.
 * Return true if successful,
 * with the starting equation number in "*ip"
 * and ending equation number in "*jp".
 */
int
get_range(cpp, ip, jp)
char  **cpp;
int   *ip, *jp;
{
      int   i;

      if (is_all(*cpp)) {
            *cpp = skip_param(*cpp);
            *ip = 0;
            *jp = n_equations - 1;
            goto test_range;
      }
      if (isascii(**cpp) && isdigit(**cpp)) {
            *ip = atoi(*cpp) - 1;
      } else {
            *ip = cur_equation;
      }
      if (*ip < 0 || *ip >= n_equations) {
            printf(_("Invalid equation number.\n"));
            return false;
      }
      *cpp = skip_num(*cpp);
      if (**cpp != '-') {
            if (notdefined(*ip)) {
                  return false;
            }
            *jp = *ip;
            return true;
      }
      (*cpp)++;
      *cpp = skip_space(*cpp);
      if (isascii(**cpp) && isdigit(**cpp)) {
            *jp = atoi(*cpp) - 1;
      } else {
            *jp = cur_equation;
      }
      if (*jp < 0 || *jp >= n_equations) {
            printf(_("Invalid equation number.\n"));
            return false;
      }
      if (*jp < *ip) {
            i = *ip;
            *ip = *jp;
            *jp = i;
      }
      *cpp = skip_num(*cpp);
test_range:
      for (i = *ip; i <= *jp; i++) {
            if (n_lhs[i] > 0) {
                  return true;
            }
      }
      printf(_("No equations defined in specified range.\n"));
      return false;
}

/*
 * This function is provided to make sure there is nothing else
 * on a command line.
 */
int
extra_garbage(cp)
char  *cp;
{
      cp = skip_space(cp);
      if (*cp) {
            printf(_("ERROR: Extra characters on command line.\n"));
            return true;
      }
      return false;
}

/*
 * Skip over digits and any spaces that follow.
 */
char  *
skip_num(cp)
char  *cp;
{
      while (*cp && isascii(*cp) && isdigit(*cp))
            cp++;
      return skip_space(cp);
}

/*
 * Skip over space characters.
 */
char  *
skip_space(cp)
char  *cp;
{
      while (*cp && isascii(*cp) && isspace(*cp))
            cp++;
      return cp;
}

/*
 * Skip over a parameter (command line argument).
 */
char  *
skip_param(cp)
char  *cp;
{
      while (*cp && (!isascii(*cp) || (!isspace(*cp) && *cp != '='))) {
            cp++;
      }
      cp = skip_space(cp);
      if (*cp == '=') {
            cp++;
            cp = skip_space(cp);
      }
      return(cp);
}

/*
 * Compare strings up to the first space.
 * Must be an exact match.
 * Compare is alphabetic case insensitive.
 */
int
strcmp_tospace(cp1, cp2)
char  *cp1, *cp2;
{
      char  *cp1a, *cp2a;

      for (cp1a = cp1; *cp1a && (!isascii(*cp1a) || !isspace(*cp1a)); cp1a++)
            ;
      for (cp2a = cp2; *cp2a && (!isascii(*cp2a) || !isspace(*cp2a)); cp2a++)
            ;
      return strncasecmp(cp1, cp2, max(cp1a - cp1, cp2a - cp2));
}

#define P(A)      fprintf(gfp, "%s\n", A)

/*
 * The help command.
 */
help(cp)
char  *cp;
{
      int   i, j;
      char  *cp1;
      int   flag;
      int   row;

      cp1 = cp;
      while (*cp1 && !(isascii(*cp1) && isspace(*cp1)))
            cp1++;
      if (cp1 != cp) {
            flag = false;
            for (i = 0; i < ARR_CNT(com_list); i++) {
                  if (strncasecmp(cp, com_list[i].name, cp1 - cp) == 0) {
                        fprintf(gfp, "%s - %s\n", com_list[i].name, com_list[i].info);
                        fprintf(gfp, "Usage: %s %s\n\n", com_list[i].name, com_list[i].usage);
                        flag = true;
                  }
            }
            if (flag)
                  return true;
            if (strncasecmp(cp, "usage", cp1 - cp) == 0) {
                  for (i = 0; i < ARR_CNT(com_list); i++) {
                        fprintf(gfp, "%s %s\n", com_list[i].name, com_list[i].usage);
                  }
                  return true;
            }
            if (strncasecmp(cp, "geometry", cp1 - cp) == 0) {
                  P("Commonly Used Geometric Formulas");
                  P("--------------------------------\n");
                  P("Triangle of base 'b' and height 'h':");
                  P("    Area = b*h/2\n");
                  P("Rectangle of length 'l' and width 'w':");
                  P("    Area = l*w               Perimeter = 2*l + 2*w\n");
                  P("Trapezoid of height 'h' and parallel sides 'a' and 'b':");
                  P("    Area = h*(a+b)/2\n");
                  P("Circle of radius 'r':");
                  P("    Area = pi*r^2            Perimeter = 2*pi*r\n");
                  P("Rectangular solid of length 'l', width 'w', and height 'h':");
                  P("    Volume = l*w*h           Surface area = 2*l*w + 2*l*h + 2*w*h\n");
                  P("Sphere of radius 'r':");
                  P("    Volume = 4/3*pi*r^3      Surface area = 4*pi*r^2\n");
                  P("Right circular cylinder of radius 'r' and height 'h':");
                  P("    Volume = pi*r^2*h        Surface area = 2*pi*r*(h+r)");
                  return true;
            }
            if (strncasecmp(cp, "equations", cp1 - cp) == 0) {
                  P("To enter an equation, simply type it in at the prompt.");
                  P("Operators have precedence decreasing as indicated:\n");
                  P("    - negate");
                  P("    ! factorial");
                  P("    ^ power");
                  P("    * multiply          / divide            % modulus");
                  P("    + add               - subtract\n");
                  P("Operators in the same precedence level are evaluated left to right.\n");
                  P("Variables consist of any combination of letters, numbers,");
                  P("and underscores (_).  Variables always start with a letter.");
                  P("Predefined constants and variables:\n");
                  P("    e# - The universal constant e (2.718281828...).");
                  P("    p# or pi - The universal constant pi (3.1415926...).");
                  P("    i# - Imaginary Number (square root of -1).");
                  P("    sign, sign1, sign2, sign3, ... - may be +1 or -1.");
                  P("    integer - may be any integer.\n");
                  P("Each equation must have one, and only one, equals sign (=).");
                  P("Absolute value notation (|x|) and \"+/-\" are understood.");
                  return true;
            }
            if (is_all(cp)) {
                  for (i = 0, row = 1;; i++) {
                        if (screen_rows && row >= (screen_rows - 3)) {
                              row = 1;
                              if (!pause_cmd(""))
                                    return false;
                              printf("\n");
                        }
                        if (i >= ARR_CNT(com_list))
                              break;
                        fprintf(gfp, "%s - %s\n", com_list[i].name, com_list[i].info);
                        fprintf(gfp, "Usage: %s %s\n\n", com_list[i].name, com_list[i].usage);
                        row += 3;
                  }
                  P("End of command list.");
                  return true;
            }
      }
      P("This \"help\" command is provided as a quick reference.");
      P("Type \"help all\" for a summary of the all commands.");
      P("Type \"help usage\" for syntax of all commands.");
      P("Type \"help equations\" for help with entering equations.");
      P("Type \"help geometry\" for some commonly used geometric formulas.");
      P("\"help\" followed by a command name will give info on a command.\n");
      P("The following is a list of available commands:\n");
      for (i = 0; i < ARR_CNT(com_list); i++) {
            if (i && (i % 4) == 0)
                  fprintf(gfp, "\n");
            fprintf(gfp, "%s", com_list[i].name);
            j = 19 - strlen(com_list[i].name);
            for (; j > 0; j--)
                  fprintf(gfp, " ");
      }
      P("\n\nTo select an equation in memory, enter \"#\" followed by the equation number.");
      P("For example, to select equation number 2, enter \"#2\" at the prompt.");
      P("\nTo solve an equation, simply type the variable name at the prompt.");
      return true;
}

Generated by  Doxygen 1.6.0   Back to index