/* This file is part of exprparser, a lex/yacc based expression parser Copyright (C) 2002-6 Toby Thain, toby@telegraphics.com.au This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include #include #include "node.h" #include "y.tab.h" // example predefined constants double t=.123, u=.456, v=.789, s[8], pi = M_PI; // example predefined functions double fxy(double x,double y){ return x*y; } double fxyz(double x,double y,double z){ return x*y*z; } extern struct node *parseformula(char*); /* predefined symbols */ struct sym_rec predefs[]={ /* variables */ {0,TOK_VAR,"t", 0,0,0, &t}, {0,TOK_VAR,"u", 0,0,0, &u}, {0,TOK_VAR,"v", 0,0,0, &v}, {0,TOK_VAR,"s0", 0,0,0, &s[0]}, {0,TOK_VAR,"s1", 0,0,0, &s[1]}, {0,TOK_VAR,"s2", 0,0,0, &s[2]}, {0,TOK_VAR,"s3", 0,0,0, &s[3]}, {0,TOK_VAR,"s4", 0,0,0, &s[4]}, {0,TOK_VAR,"s5", 0,0,0, &s[5]}, {0,TOK_VAR,"s6", 0,0,0, &s[6]}, {0,TOK_VAR,"s7", 0,0,0, &s[7]}, /* constants */ {0,TOK_VAR,"PI", 0,0,0, &pi}, /* functions */ {0,TOK_FN1,"sin", &sin,0,0, 0}, // library functions... {0,TOK_FN1,"cos", &cos,0,0, 0}, {0,TOK_FN1,"tan", &tan,0,0, 0}, {0,TOK_FN1,"exp", &exp,0,0, 0}, {0,TOK_FN1,"log", &log,0,0, 0}, {0,TOK_FN1,"log10", &log10,0,0, 0}, {0,TOK_FN1,"sqrt", &sqrt,0,0, 0}, {0,TOK_FN2,"fxy", 0,&fxy,0, 0}, /* example 2-arg function */ {0,TOK_FN3,"fxyz", 0,0,&fxyz, 0}, /* example 3-arg function */ {NULL,0,NULL, NULL,NULL,NULL, NULL} }; int main(int argc,char *argv[]){ extern int tokpos; extern char *errstr; struct node *tree; char expr[0x100]; int varused[26],i,varcount; init_symtab(predefs); while( fgets(expr,sizeof(expr),stdin) ){ tokpos = 0; if( (tree = parseformula(expr)) ){ dumptree(tree,0); printf("= %g\n",eval(tree)); checkvars(tree,varused); printf("single character variables used: "); for(i=varcount=0;i<26;++i) if(varused[i]){ if(varcount) putchar(','); putchar(i+'a'); ++varcount; } if(!varcount) printf("(none)"); putchar('\n'); }else printf("%*s\n%s\n",tokpos,"^",errstr); freetree(tree); // we're done with the parse tree } return EXIT_SUCCESS; }