Преглед изворни кода

Fixed parenthesis with new negation method in line generator.

Taddeus Kroes пре 14 година
родитељ
комит
da0af4033a
2 измењених фајлова са 24 додато и 6 уклоњено
  1. 9 6
      line.py
  2. 15 0
      tests/test_line.py

+ 9 - 6
line.py

@@ -255,13 +255,18 @@ def generate_line(root):
         for i, child in enumerate(node):
             exp = content[child]
 
+            #if i and op == '+' and exp[:2] == '-(':
+            #    exp = '-' + exp[2:-1]
+            #    print 'exp:', exp
+
             # Check if there is a precedence conflict
             # If so, add parentheses
             child_pred = pred(child)
 
-            if child_pred < node_pred or \
-                    (i and child_pred == node_pred \
-                        and op != child.title()):
+            if not child.negated and (child_pred < node_pred \
+                    or (i and child_pred == node_pred \
+                        and (op != child.title() \
+                             or (op == '+' and child[1].negated)))):
                 exp = '(' + exp + ')'
 
             e.append(exp)
@@ -290,9 +295,7 @@ def generate_line(root):
 
         exp = sep.join(e)
 
-        #if node.negated:
-        # FIXME: Keep it this way?
-        if node.negated and op != '*':
+        if node.negated and op not in ('*', '/'):
             exp = '(' + exp + ')'
 
         return exp

+ 15 - 0
tests/test_line.py

@@ -162,12 +162,21 @@ class TestLine(unittest.TestCase):
         neg = -N('-', L(1), L(2))
         self.assertEquals(generate_line(neg), '-(1 - 2)')
 
+        neg = N('+', L(1), N('+', L(1), L(2)))
+        self.assertEquals(generate_line(neg), '1 + 1 + 2')
+
         neg = N('+', L(1), -N('+', L(1), L(2)))
         self.assertEquals(generate_line(neg), '1 - (1 + 2)')
 
+        neg = N('+', L(1), N('+', L(1), -L(2)))
+        self.assertEquals(generate_line(neg), '1 + (1 - 2)')
+
         neg = -N('*', L(4), L('a'))
         self.assertEquals(generate_line(neg), '-4a')
 
+        neg = N('*', L(4), -L('a'))
+        self.assertEquals(generate_line(neg), '4 * -a')
+
         neg = -N('*', L(4), L(5))
         self.assertEquals(generate_line(neg), '-4 * 5')
 
@@ -177,6 +186,12 @@ class TestLine(unittest.TestCase):
         plus = N('+', L(1), -L(4))
         self.assertEquals(generate_line(plus), '1 - 4')
 
+        plus = N('+', N('/', L('a'), L('b')), -N('/', L('c'), L('d')))
+        self.assertEquals(generate_line(plus), 'a / b - c / d')
+
+        mul = N('*', N('+', L('a'), L('b')), -N('+', L('c'), L('d')))
+        self.assertEquals(generate_line(mul), '(a + b) * -(c + d)')
+
     def test_double_negation(self):
         neg = --L(1)
         self.assertEquals(generate_line(neg), '--1')