From 047b39789918495f55c401543372ee792ccc3107 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Thu, 12 Dec 2019 13:10:55 +0100
Subject: [PATCH] Simplify x+y-y in x
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Note that this actually corresponds to 4 different abstract syntax trees:
— (x+y)-y
— (y+x)-y
— (x-y)+y
— y+(x-y)
---
 src/DataTree.cc | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/src/DataTree.cc b/src/DataTree.cc
index 1887d627..5b50efbc 100644
--- a/src/DataTree.cc
+++ b/src/DataTree.cc
@@ -183,6 +183,16 @@ DataTree::AddPlus(expr_t iArg1, expr_t iArg2)
           uarg1 && uarg1->op_code == UnaryOpcode::uminus)
         return AddMinus(iArg2, uarg1->arg);
 
+      // Simplify (x-y)+y in x
+      if (auto barg1 = dynamic_cast<BinaryOpNode *>(iArg1);
+          barg1 && barg1->op_code == BinaryOpcode::minus && barg1->arg2 == iArg2)
+        return barg1->arg1;
+
+      // Simplify y+(x-y) in x
+      if (auto barg2 = dynamic_cast<BinaryOpNode *>(iArg2);
+          barg2 && barg2->op_code == BinaryOpcode::minus && barg2->arg2 == iArg1)
+        return barg2->arg1;
+
       // To treat commutativity of "+"
       // Nodes iArg1 and iArg2 are sorted by index
       if (iArg1->idx > iArg2->idx)
@@ -215,6 +225,16 @@ DataTree::AddMinus(expr_t iArg1, expr_t iArg2)
       uarg2 && uarg2->op_code == UnaryOpcode::uminus)
     return AddPlus(iArg1, uarg2->arg);
 
+  // Simplify (x+y)-y and (y+x)-y in x
+  if (auto barg1 = dynamic_cast<BinaryOpNode *>(iArg1);
+      barg1 && barg1->op_code == BinaryOpcode::plus)
+    {
+      if (barg1->arg2 == iArg2)
+        return barg1->arg1;
+      if (barg1->arg1 == iArg2)
+        return barg1->arg2;
+    }
+
   return AddBinaryOp(iArg1, BinaryOpcode::minus, iArg2);
 }
 
-- 
GitLab