[gnome-calculator] parser: Fixed percentage evaluation error (fixes #237)



commit 23831a8a3c2336bc96b955709f582a0b74c75356
Author: Robert Roth <robert roth off gmail com>
Date:   Sun Nov 21 03:45:45 2021 +0200

    parser: Fixed percentage evaluation error (fixes #237)

 lib/equation-parser.vala | 20 ++++++++++++++++++++
 tests/test-equation.vala |  7 +++++++
 2 files changed, 27 insertions(+)
---
diff --git a/lib/equation-parser.vala b/lib/equation-parser.vala
index 07b94e70..c98f31fa 100644
--- a/lib/equation-parser.vala
+++ b/lib/equation-parser.vala
@@ -1879,6 +1879,16 @@ public class Parser
                 //FIXME: This condition needs to be verified for all cases.. :(
                 if (node.right.precedence > Precedence.PERCENTAGE)
                 {
+                    var next_token  = lexer.get_next_token ();
+                    lexer.roll_back ();
+
+                    if (next_token.text != "" && get_precedence (next_token.type) < Precedence.PERCENTAGE)
+                    {
+                        lexer.roll_back ();
+                        if (!expression_2 ())
+                            return true;
+                    }
+
                     node.precedence = Precedence.PERCENTAGE;
                     node.do_percentage = true;
                     return true;
@@ -1912,6 +1922,16 @@ public class Parser
                 //FIXME: This condition needs to be verified for all cases.. :(
                 if (node.right.precedence > Precedence.PERCENTAGE)
                 {
+                    var next_token  = lexer.get_next_token ();
+                    lexer.roll_back ();
+
+                    if (next_token.text != "" && get_precedence (next_token.type) < Precedence.PERCENTAGE)
+                    {
+                        lexer.roll_back ();
+                        if (!expression_2 ())
+                            return true;
+                    }
+
                     node.precedence = Precedence.PERCENTAGE;
                     node.do_percentage = true;
                     return true;
diff --git a/tests/test-equation.vala b/tests/test-equation.vala
index e9b415f9..cee344dc 100644
--- a/tests/test-equation.vala
+++ b/tests/test-equation.vala
@@ -763,6 +763,13 @@ private void test_precedence ()
     test ("3! ^ 3", "216", 0);
     test ("3 ^ 3!", "729", 0);
     test ("(−√3)^2", "3", 0);
+    test ("100 - 20%", "80", 0);
+    test ("100 - 20% * 100", "80", 0);
+    test ("100 - 100 * 20%", "80", 0);
+    test ("100 + 20%", "120", 0);
+    test ("100 + 20% * 100", "120", 0);
+    test ("100 + 100 * 20%", "120", 0);
+
 }
 
 private void test_custom_functions ()


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]