Bläddra i källkod

Parentheses around the left child are now left out when children of binary operators have equal precedences.

Taddeus Kroes 14 år sedan
förälder
incheckning
591a3e65e0
2 ändrade filer med 8 tillägg och 3 borttagningar
  1. 2 2
      line.py
  2. 6 1
      tests/test_line.py

+ 2 - 2
line.py

@@ -90,7 +90,7 @@ def generate_line(root):
                 sep = ' ' + op + ' '
                 e = []
 
-                for child in node:
+                for i, child in enumerate(node):
                     exp = traverse(child)
 
                     # Check if there is a precedence conflict
@@ -98,7 +98,7 @@ def generate_line(root):
                     child_pred = pred(child)
 
                     if child_pred < node_pred or \
-                            (child_pred == node_pred and op != child.title()):
+                            (i and child_pred == node_pred and op != child.title()):
                         exp = '(' + exp + ')'
 
                     e.append(exp)

+ 6 - 1
tests/test_line.py

@@ -20,12 +20,17 @@ class TestLine(unittest.TestCase):
         times = N('*', plus, plus)
         self.assertEquals(generate_line(times), '(1 + 2) * (1 + 2)')
 
-    def test_parentheses_equal_precedence(self):
+    def test_parentheses_equal_precedence_right(self):
         l0, l1, l2 = L(1), L(2), L(3)
         plus = N('+', l1, l2)
         minus = N('-', l0, plus)
         self.assertEquals(generate_line(minus), '1 - (2 + 3)')
 
+    def test_parentheses_equal_precedence_left(self):
+        a, b, c, d = L('a'), L('b'), L('c'), L('d')
+        exp = N('*', N('/', N('*', a, b), c), d)
+        self.assertEquals(generate_line(exp), 'ab / c * d')
+
     def test_parentheses_nary(self):
         l0, l1, l2 = L(1), L(2), L(3)
         plus = N('+', N('+', l0, l1), l2)