From f039b41cb9ce5567cd582bca46a2af68aa757755 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Fri, 19 Feb 2021 17:45:02 +0100
Subject: [PATCH] Fix output write_latex_original_model for model-local
 variables

Those variables were substituted out by early substitution methods (which are
also called on the original model, for an unknown reason).

Closes: #65

(manually cherry picked from commit d3e115194b551f318c0c036b5a115086c0891dd8)
---
 src/DynamicModel.cc |  7 +++++++
 src/ExprNode.cc     | 12 +++++-------
 2 files changed, 12 insertions(+), 7 deletions(-)

diff --git a/src/DynamicModel.cc b/src/DynamicModel.cc
index 2b9e3efa..d5284fe7 100644
--- a/src/DynamicModel.cc
+++ b/src/DynamicModel.cc
@@ -6446,6 +6446,13 @@ DynamicModel::substituteLeadLagInternal(AuxVarType type, bool deterministic_mode
 void
 DynamicModel::substituteAdl()
 {
+  /* Contrary to other substitution methods, we do the substitution in MLV
+     definitions here, instead of doing it at the ExprNode method level,
+     because otherwise this would substitute MLV in the original model (see
+     #65). */
+  for (auto &[id, definition] : local_variables_table)
+    definition = definition->substituteAdl();
+
   for (auto &equation : equations)
     equation = dynamic_cast<BinaryOpNode *>(equation->substituteAdl());
 }
diff --git a/src/ExprNode.cc b/src/ExprNode.cc
index 3358e73a..b01bd5ba 100644
--- a/src/ExprNode.cc
+++ b/src/ExprNode.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright © 2007-2020 Dynare Team
+ * Copyright © 2007-2021 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -1654,9 +1654,8 @@ VariableNode::getPacTargetSymbId(int lhs_symb_id, int undiff_lhs_symb_id) const
 expr_t
 VariableNode::substituteAdl() const
 {
-  if (get_type() == SymbolType::modelLocalVariable)
-    return datatree.getLocalVariable(symb_id)->substituteAdl();
-
+  /* Do not recurse into model-local variables definition, rather do it at the
+     DynamicModel method level (see the comment there) */
   return const_cast<VariableNode *>(this);
 }
 
@@ -2119,9 +2118,8 @@ VariableNode::findConstantEquations(map<VariableNode *, NumConstNode *> &table)
 expr_t
 VariableNode::replaceVarsInEquation(map<VariableNode *, NumConstNode *> &table) const
 {
-  if (get_type() == SymbolType::modelLocalVariable)
-    return datatree.getLocalVariable(symb_id)->replaceVarsInEquation(table);
-
+  /* Do not recurse into model-local variables definition, because otherwise
+     this would substitute MLV in the original model (see #65). */
   for (auto &it : table)
     if (it.first->symb_id == symb_id)
       return it.second;
-- 
GitLab