stan-dev / math

The Stan Math Library is a C++ template library for automatic differentiation of any order using forward, reverse, and mixed modes. It includes a range of built-in functions for probabilistic modeling, linear algebra, and equation solving.
https://mc-stan.org
BSD 3-Clause "New" or "Revised" License
723 stars 183 forks source link

Add a custom `eigen_assert` macro #3080

Open WardBrian opened 4 weeks ago

WardBrian commented 4 weeks ago

Description

Eigen assertions from Stan code are always indicative of a bug (see #3075, most recently) but they lack any contextual information about where the assertion occurs. We can inject this ourselves using the Boost.Stacktrace library, which would make reports much easier to debug.

For example, this code seems to work on Linux:

#define BOOST_STACKTRACE_USE_ADDR2LINE 1

#include <stdexcept>
#include <iostream>
#include <boost/stacktrace.hpp>
#undef eigen_assert
#define eigen_assert(x) \
  if (!(x)) { std::cerr << boost::stacktrace::stacktrace() << std::endl;\
               throw (std::runtime_error("Eigen assertion failed! Please report a bug to Stan")); }

This will report both the C++ traceback, and because it is a normal exception, the location in the Stan source file which triggered it.

Boost.Stacktrace does require some extra libraries, which are pre-installed on *Nix-like, but may not be on Windows, so we may want to add the above behind a STAN_DEBUG flag or similar.

Current Version:

v4.9.0