From e31f0a8d0f55d75bc4e36e1c2e5413f5d45d894e Mon Sep 17 00:00:00 2001
From: Houtan Bastani <houtan@dynare.org>
Date: Mon, 5 Sep 2016 17:19:09 +0200
Subject: [PATCH] macroprocessor: stop with error when division by zero is
 encountered. closes #1278

---
 doc/dynare.texi                  | 7 +++++--
 preprocessor/macro/MacroBison.yy | 9 +++++++--
 preprocessor/macro/MacroValue.hh | 3 ++-
 3 files changed, 14 insertions(+), 5 deletions(-)

diff --git a/doc/dynare.texi b/doc/dynare.texi
index f825a357f8..40aba5129b 100644
--- a/doc/dynare.texi
+++ b/doc/dynare.texi
@@ -9699,8 +9699,11 @@ String literals have to be enclosed between @strong{double} quotes
 elements are separated by commas (like @code{[1,2,3]} or @code{["US",
 "EA"]}).
 
-Note that there is no boolean type: @emph{false} is
-represented by integer zero and @emph{true} is any non-null integer.
+Note that there is no boolean type: @emph{false} is represented by integer zero
+and @emph{true} is any non-null integer. Further note that, as the
+macro-processor cannot handle non-integer real numbers, integer division
+results in the quotient with the fractional part truncated (hence,
+@math{5/3=3/3=1}).
 
 The following operators can be used on integers:
 @itemize
diff --git a/preprocessor/macro/MacroBison.yy b/preprocessor/macro/MacroBison.yy
index 2bd8072a4c..27c0e4b28c 100644
--- a/preprocessor/macro/MacroBison.yy
+++ b/preprocessor/macro/MacroBison.yy
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2014 Dynare Team
+ * Copyright (C) 2008-2016 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -150,7 +150,12 @@ expr : INTEGER
      | expr TIMES expr
        { TYPERR_CATCH($$ = *$1 * *$3, @$); }
      | expr DIVIDE expr
-       { TYPERR_CATCH($$ = *$1 / *$3, @$); }
+       {
+         if (dynamic_cast<const IntMV *>($3) != NULL
+             && ((IntMV *)$3)->get_int_value() == 0)
+           driver.error(@$, "Division by zero");
+         TYPERR_CATCH($$ = *$1 / *$3, @$);
+       }
      | expr LESS expr
        { TYPERR_CATCH($$ = *$1 < *$3, @$); }
      | expr GREATER expr
diff --git a/preprocessor/macro/MacroValue.hh b/preprocessor/macro/MacroValue.hh
index 2501647812..c9da9c3ddf 100644
--- a/preprocessor/macro/MacroValue.hh
+++ b/preprocessor/macro/MacroValue.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2013 Dynare Team
+ * Copyright (C) 2008-2016 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -158,6 +158,7 @@ public:
     If mv2 < mv1, returns an empty range (for consistency with MATLAB).
   */
   static const MacroValue *new_range(MacroDriver &driver, const MacroValue *mv1, const MacroValue *mv2) throw (TypeError);
+  inline int get_int_value() const { return value; };
 };
 
 //! Represents a string value in macro language
-- 
GitLab