From fe6d4e9bca478e8c2f73c8711ffdaa17390b0ef0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Wed, 5 Dec 2018 12:38:46 +0100
Subject: [PATCH] Modify semantics of ExprNode::countDiffs()

Previously, this function was counting the total number of diff() operators in
an expression. But this is not very useful, and is potentially misleading,
because in practice we use this function to compute the maximum lag on
variables in levels.

This function now returns the maximum number of nested diffs.

For example, on diff(x)+diff(diff(y)), this function was returning 3, and it
now returns 2.
---
 src/ExprNode.cc | 6 +++---
 src/ExprNode.hh | 2 +-
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/ExprNode.cc b/src/ExprNode.cc
index 78627414..31c3bbef 100644
--- a/src/ExprNode.cc
+++ b/src/ExprNode.cc
@@ -5323,7 +5323,7 @@ BinaryOpNode::substituteUnaryOpNodes(DataTree &static_datatree, diff_table_t &no
 int
 BinaryOpNode::countDiffs() const
 {
-  return arg1->countDiffs() + arg2->countDiffs();
+  return max(arg1->countDiffs(), arg2->countDiffs());
 }
 
 expr_t
@@ -6585,7 +6585,7 @@ TrinaryOpNode::substituteUnaryOpNodes(DataTree &static_datatree, diff_table_t &n
 int
 TrinaryOpNode::countDiffs() const
 {
-  return arg1->countDiffs() + arg2->countDiffs() + arg3->countDiffs();
+  return max(arg1->countDiffs(), max(arg2->countDiffs(), arg3->countDiffs()));
 }
 
 expr_t
@@ -7069,7 +7069,7 @@ AbstractExternalFunctionNode::countDiffs() const
 {
   int ndiffs = 0;
   for (auto argument : arguments)
-    ndiffs += argument->countDiffs();
+    ndiffs = max(ndiffs, argument->countDiffs());
   return ndiffs;
 }
 
diff --git a/src/ExprNode.hh b/src/ExprNode.hh
index f44f9d06..d65b3d27 100644
--- a/src/ExprNode.hh
+++ b/src/ExprNode.hh
@@ -518,7 +518,7 @@ class ExprNode
       //! Returns true if the expression contains one or several exogenous variable
       virtual bool containsExogenous() const = 0;
 
-      //! Returns the number of diffs present
+      //! Returns the maximum number of nested diffs in the expression
       virtual int countDiffs() const = 0;
 
       //! Return true if the nodeID is a variable withe a type equal to type_arg, a specific variable id aqual to varfiable_id and a lag equal to lag_arg and false otherwise
-- 
GitLab