double EvalSubStatement (char *status, char *look, struct Variable *Vars) { #ifdef DEBUG printf ("EvalSubStatement in; status: %i, look: %c;\n", *status, *look); #endif char oldstatus = *status; *status = -1; // pass on substatement status struct TokenStruct tmp; // tmp.Token = malloc (sizeof (char) * 2); tmp.Token = "+"; tmp.type = TokenType ('+'); tmp.priority = OpPriority ('+'); double ret = Evaluate (0, tmp, status, look, Vars); if (!*status) { *status = oldstatus; } // if no error occured during substatement evaluation, reset status return ret; }
void CParser::ParseExpression() { Clear(); SkipSpaces(); ProceedUnary(); while (pos < sz) { SkipSpaces(); char curChar = src[pos]; if (IsControl(curChar)) { break; } else if (IsDigit(curChar)) { ParseNumber(); } else if (curChar == '(') { ops.push_front(0); // 0 instead '(' ++pos; ProceedUnary(); } else if (curChar == ')') { while (!ops.empty() && ops.front()!=0) { Simplify(); } ops.pop_front(); ++pos; } else if (OpPriority(curChar) >= 0) { ProceedOperator(); } else { ParseName(); } } // !while (pos < lim) while(st.size() > 1 || !ops.empty()) { Simplify(); } // if (st.size() != 1 || !ops.empty()) { Clear(); throw AST::ASTException("Miss parameters"); } _pProgram->AddExpression(st.front()); st.pop_front(); }
struct TokenStruct NextToken (char *c) { *c = FindToken (*c); struct TokenStruct ret;// = malloc (sizeof (struct TokenStruct)); ret.Token = malloc (sizeof (char) * 2); ret.Token[0] = *c; ret.type = TokenType (*c); ret.priority = OpPriority (*c); ret.index = line_index; int length = 1; if (!ret.type) { if (*c == '+' || *c == '-' || *c == '*' || *c == '/' || *c == '%' || *c == '^' || *c == '=' || *c == ')' || *c == '(' || *c == ',') { // Grab next character if we have a valid token *c = FindToken (0); } ret.Token[1] = '\0'; #ifdef DEBUG if (ret.Token[0] != '\n') { printf (" Op/Invalid Token %i: '%s';\n", ret.index, ret.Token); } else { printf (" Op/Invalid Token %i: '\\n';\n", ret.index); } sleep (1); #endif return ret; } *c = getchar (); AddSpace (*c); while (TokenType (*c) == ret.type) { ret.Token[length++] = *c; if (ECHO) { putchar (*c); } ret.Token = realloc (ret.Token, sizeof (char) * (length+1)); *c = getchar (); AddSpace (*c); } if (ECHO) { putchar (*c); } //line_index += length; ret.Token[length] = '\0'; *c = FindToken (*c); #ifdef DEBUG printf (" Var/Num Token %i: %s;\n", ret.index, ret.Token); sleep (1); #endif return ret; }
double EvalFunction (struct TokenStruct val, char *status, char *look, struct Variable *Vars) { #ifdef DEBUG printf ("EvalFunction in; Val: %s, status: %i, look: %c;\n", val.Token, *status, *look); #endif // parse args double *Args = 0; int nargs = 0; char oldstatus = *status; struct TokenStruct tmp; //tmp.Token = malloc (sizeof (char) * 2); tmp.Token = "+"; tmp.type = TokenType ('+'); tmp.priority = OpPriority ('+'); // tmp.index = 0; *status = -2; // set status to indicate argument evaluation if (*look != ')') { // make sure there are more than zero arguments while (*status == -2) { Args = realloc (Args, sizeof (double) * ++nargs); // make room for the next argument Args[nargs-1] = Evaluate (0.0, tmp, status, look, Vars); // and add it to the argument vector } if (*status) { // argument(s) invalid; return. Error in Evaluate, let it handle the error free (Args); return; } } else { NextToken (look); } *status = oldstatus; // resolve function double ret = GetFunction (val, Args, nargs, status); if (Args) { free (Args); } // if (*status > 0) { HandleError (val, *status, look); } // Let Evaluate or Parse handle errors return ret; }
char Parse (struct Variable *Vars) { // grabs first two tokens to see if they are an assign statment // Symbol-specified functions: // = (Assign), + (Add), - (Subtract), * (Multiply), / (Divide), % (Modulus), ^ (Power) // Future symbols: ! (Factorial / Gamma function), // Unused symbols: ~, `, @, #, $, &, [, ], {, }, |, \, ;, :, ', ", ?, ,, <, >, line_index = 0; char look = 0, status = 0; printf ("> "); fflush (0); struct TokenStruct /*Oper*/and = NextToken (&look); // check for calculator commands if (!strcmp (and.Token, "DISPLAY")) { // display variable tree char *disp = 0; DisplayVars (Vars, disp, 0); HandleError (and, 0, &look); return 0; } else if (!strcmp (and.Token, "ECHO")) { // toggle input echo mode ECHO = 1 - ECHO; if (ECHO) { puts ("Input echo on"); } else { puts ("Input echo off"); } HandleError (and, 0, &look); return 0; } else if (!strcmp (and.Token, "HELP")) { // display help screen puts ("Basic Calculator V 0.9"); puts ("--------------------------------------------------------------------------------"); puts ("This program is meant to be used as a general purpose calculator, akin to bc. Users can input arithmitic expressions of arbitrary length, assign and retrieve variables, and calculate common math functions. If the expression input isn't valid, the program displays an error message, indicates where in the line the problem occured, clears the input and resumes operation. In addition, users can work in interactive mode or redirect input scripts to execute a list of operations."); puts ("--------------------------------------------------------------------------------"); puts ("COMMANDS: (case sensitive)"); puts (" DISPLAY : Display defined variables and their associated values."); puts (" ECHO : Echo user input on next line. Useful when using an input script."); puts (" HELP : Display this help screen."); puts (" QUIT : Quit this calculator program."); puts ("--------------------------------------------------------------------------------"); puts ("MATH FUNCTIONS: (not case sensitive)\n"); puts ("ABS / ABSOLUTE :\n return the absolute value of the argument. Accepts one argument."); puts ("ASIN / ARCSINE :\n return the arc sine (inverse sine function) of the argument. Accepts one argument."); puts ("ACOS / ARCCOSINE :\n return the arc cosine (inverse cosine function) of the argument. Accepts one argument."); puts ("ATAN / ARCTANGENT :\n return the arc tangent (inverse tangent function) of the argument. Accepts one argument."); puts ("COS / COSINE :\n return the cosine of the argument. Accepts one argument."); puts ("DIST / DISTANCE / HYPOTENUSE :\n return the pythangorian distance (hypotenuse) between two values. Accepts two arguments."); puts ("E :\n return the value of e. Accepts no arguments."); puts ("EXP :\n return the exponent of the argument (e ^ arg). Accepts one argument."); puts ("LN / NATURAL_LOG :\n return the natural log of the argument (arg = e ^ x). Accepts one argument."); puts ("LOG / LOGARITHM :\n return the natural log of an argument OR the log of one argument in terms of another (log A / log b). Accepts one or two arguments."); puts ("MOD / MODULUS :\n return the remainder of one argument divided by another. Accepts two arguments."); puts ("PI :\n return the value of pi. Accepts no arguments."); puts ("POW / POWER :\n return the value of one argument raised to the power of the other. Accepts two arguments."); puts ("PROD / PRODUCT :\n return the product of the arguments. Accepts one or more arguments."); puts ("SIN / SINE :\n return the sine of the argument. Accepts one argument."); puts ("SQRT / SQUARE_ROOT :\n return the square root of the argument. Accepts one argument."); puts ("SUM / SUMMATION :\n return the sum of the arguments. Accepts one or more arguments."); puts ("TAN / TANGENT :\n return the tangent of the argument. Accepts one argument."); HandleError (and, 0, &look); return 0; } else if (!strcmp (and.Token, "QUIT")) { // quit calculator HandleError (and, 0, &look); return 1; } struct TokenStruct /*Oper*/ator; struct TokenStruct tmp; tmp.Token = malloc (sizeof (char) * 2); tmp.Token = "+"; tmp.type = TokenType ('+'); tmp.priority = OpPriority ('+'); if (!and.priority) { return 0; } // no operand; blank line double result = 0.0; double sign = 1.0; if (and.Token[0] == '-') { // negative value sign = -1.0; and = NextToken (&look); } if (and.Token[0] == '(') { result = sign * EvalSubStatement (&status, &look, Vars); } // substatement if (status) { return 0; } ator = NextToken (&look); // must be determined *after* substatement, and *before* function, assignment, or variable // function, assignment, or variable; need operator to decide if (ator.Token[0] == '(') { // function result = sign * EvalFunction (and, &status, &look, Vars); if (status) { if (status == 5 || status == 9) { HandleError (and, status, &look); } return 0; } ator = NextToken (&look); result = Evaluate (result, ator, &status, &look, Vars); } else if (and.type == 1 && ator.Token[0] == '=') { result = Evaluate (0.0, tmp, &status, &look, Vars); } // assignment; don't need to check status here since it will be checked as soon as this statement is finished else { // variable, number, substatement, or invalid if (and.Token[0] != '(') { result = sign * Resolve (and, &status, Vars); if (status) { HandleError (and, status, &look); return 0; } } result = Evaluate (result, ator, &status, &look, Vars); } if (status) { return 0; } else if (ator.Token[0] == '=') { AssignValue (and.Token, result, Vars); printf ("%s ", and.Token); } printf ("= %f;\n", result); return 0; }