You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.8 KiB

  1. /*
  2. This file is part of libeval, a simple math expression evaluator
  3. Copyright (C) 2017 Michael Geselbracht, mgeselbracht3@gmail.com
  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 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. %token_type { numEval::TokenType }
  16. %extra_argument { NUMERIC_EVALUATOR* pEval }
  17. %nonassoc VAR ASSIGN SEMCOL.
  18. %left PLUS MINUS.
  19. %right UNIT.
  20. %left DIVIDE MULT.
  21. %include {
  22. #include <assert.h>
  23. #include <libeval/numeric_evaluator.h>
  24. }
  25. %syntax_error {
  26. pEval->parseError("Syntax error");
  27. }
  28. %parse_accept {
  29. pEval->parseOk();
  30. }
  31. main ::= in.
  32. /* Allow multiple statements in input string: x=1; y=2 */
  33. in ::= stmt.
  34. in ::= in stmt.
  35. /* A statement can be empty, an expr or an expr followed by ';' */
  36. stmt ::= ENDS.
  37. stmt ::= expr(A) ENDS. { pEval->parseSetResult(A.valid ? A.dValue : NAN); }
  38. stmt ::= expr SEMCOL. { pEval->parseSetResult(NAN); }
  39. expr(A) ::= VALUE(B). { A.dValue = B.dValue; A.valid=true; }
  40. expr(A) ::= expr(B) UNIT(C). { A.dValue = B.dValue * C.dValue; A.valid=B.valid; }
  41. expr(A) ::= MINUS expr(B). { A.dValue = -B.dValue; A.valid=B.valid; }
  42. expr(A) ::= PLUS expr(B). { A.dValue = B.dValue; A.valid=B.valid; }
  43. expr(A) ::= VAR(B). { A.dValue = pEval->GetVar(B.text); A.valid=true; }
  44. expr(A) ::= VAR(B) ASSIGN expr(C). { pEval->SetVar(B.text, C.dValue); A.dValue = C.dValue; A.valid=false; }
  45. expr(A) ::= expr(B) PLUS expr(C). { A.dValue = B.dValue + C.dValue; A.valid=C.valid; }
  46. expr(A) ::= expr(B) MINUS expr(C). { A.dValue = B.dValue - C.dValue; A.valid=C.valid; }
  47. expr(A) ::= expr(B) MULT expr(C). { A.dValue = B.dValue * C.dValue; A.valid=C.valid; }
  48. expr(A) ::= expr(B) DIVIDE expr(C). {
  49. if( C.dValue != 0.0 )
  50. A.dValue = B.dValue / C.dValue;
  51. else
  52. pEval->parseError( "Divide by zero" );
  53. A.valid = C.valid;
  54. }
  55. expr(A) ::= PARENL expr(B) PARENR. { A.dValue = B.dValue; A.valid = B.valid; }