From f223af91afaaec5fdaa9224c2386d25d5428eee3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Mon, 5 Nov 2018 12:30:42 +0100
Subject: [PATCH] Improve the fix in 366701c094c

Now both x+(-y) and (-x)+y are simplified using a minus operator.

Also simplify some code using std::swap().
---
 src/DataTree.cc | 27 ++++++++++++---------------
 1 file changed, 12 insertions(+), 15 deletions(-)

diff --git a/src/DataTree.cc b/src/DataTree.cc
index ae2231e6..463fa073 100644
--- a/src/DataTree.cc
+++ b/src/DataTree.cc
@@ -172,20 +172,21 @@ DataTree::AddPlus(expr_t iArg1, expr_t iArg2)
 {
   if (iArg1 != Zero && iArg2 != Zero)
     {
-      // To treat commutativity of "+"
-      // Nodes iArg1 and iArg2 are sorted by index
-      if (iArg1->idx > iArg2->idx)
-        {
-          expr_t tmp = iArg1;
-          iArg1 = iArg2;
-          iArg2 = tmp;
-        }
-
       // Simplify x+(-y) in x-y
-      auto *uarg2 = dynamic_cast<UnaryOpNode *>(iArg2);
+      auto uarg2 = dynamic_cast<UnaryOpNode *>(iArg2);
       if (uarg2 != nullptr && uarg2->get_op_code() == UnaryOpcode::uminus)
         return AddMinus(iArg1, uarg2->get_arg());
 
+      // Simplify (-x)+y in y-x
+      auto uarg1 = dynamic_cast<UnaryOpNode *>(iArg1);
+      if (uarg1 != nullptr && uarg1->get_op_code() == UnaryOpcode::uminus)
+        return AddMinus(iArg2, uarg1->get_arg());
+
+      // To treat commutativity of "+"
+      // Nodes iArg1 and iArg2 are sorted by index
+      if (iArg1->idx > iArg2->idx)
+        swap(iArg1, iArg2);
+
       return AddBinaryOp(iArg1, BinaryOpcode::plus, iArg2);
     }
   else if (iArg1 != Zero)
@@ -239,11 +240,7 @@ DataTree::AddTimes(expr_t iArg1, expr_t iArg2)
       // To treat commutativity of "*"
       // Nodes iArg1 and iArg2 are sorted by index
       if (iArg1->idx > iArg2->idx)
-        {
-          expr_t tmp = iArg1;
-          iArg1 = iArg2;
-          iArg2 = tmp;
-        }
+        swap(iArg1, iArg2);
       return AddBinaryOp(iArg1, BinaryOpcode::times, iArg2);
     }
   else if (iArg1 != Zero && iArg1 != One && iArg2 == One)
-- 
GitLab