From 38425dc15d3fc6f72f3b50ba41fa45ddeda36b8d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Fri, 19 Feb 2021 20:11:33 +0100
Subject: [PATCH] Fix bugs introduced in
 d3e115194b551f318c0c036b5a115086c0891dd8

Ref. #65

(cherry picked from commit 825b9ee8ef6e09860e2495dca944df28fc8c1688)
---
 src/ExprNode.cc  | 11 ++++++-----
 src/ModelTree.cc |  2 ++
 2 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/src/ExprNode.cc b/src/ExprNode.cc
index 4c76b537..ef78d878 100644
--- a/src/ExprNode.cc
+++ b/src/ExprNode.cc
@@ -1740,9 +1740,9 @@ VariableNode::decreaseLeadsLags(int n) const
 expr_t
 VariableNode::decreaseLeadsLagsPredeterminedVariables() const
 {
-  if (get_type() == SymbolType::modelLocalVariable)
-    return datatree.getLocalVariable(symb_id)->decreaseLeadsLagsPredeterminedVariables();
-
+  /* Do not recurse into model-local variables definitions, since MLVs are
+     already handled by DynamicModel::transformPredeterminedVariables().
+     This is also necessary because of #65. */
   if (datatree.symbol_table.isPredetermined(symb_id))
     return decreaseLeadsLags(1);
   else
@@ -2118,8 +2118,9 @@ VariableNode::findConstantEquations(map<VariableNode *, NumConstNode *> &table)
 expr_t
 VariableNode::replaceVarsInEquation(map<VariableNode *, NumConstNode *> &table) const
 {
-  /* Do not recurse into model-local variables definition, because otherwise
-     this would substitute MLV in the original model (see #65). */
+  /* Do not recurse into model-local variables definitions, since MLVs are
+     already handled by ModelTree::simplifyEquations().
+     This is also necessary because of #65. */
   for (auto &it : table)
     if (it.first->symb_id == symb_id)
       return it.second;
diff --git a/src/ModelTree.cc b/src/ModelTree.cc
index f9c757a1..bedc4104 100644
--- a/src/ModelTree.cc
+++ b/src/ModelTree.cc
@@ -2027,6 +2027,8 @@ ModelTree::simplifyEquations()
   while (subst_table.size() != last_subst_table_size)
     {
       last_subst_table_size = subst_table.size();
+      for (auto &[id, definition] : local_variables_table)
+        definition = definition->replaceVarsInEquation(subst_table);
       for (auto &equation : equations)
         equation = dynamic_cast<BinaryOpNode *>(equation->replaceVarsInEquation(subst_table));
       subst_table.clear();
-- 
GitLab