Assertion utility for Fortran 2018

A small fpm package from @rouson at Sourcery Institute:

8 Likes

Nice project, did not know about it. However it did strike me as weird how limited the use of preprocessor was. In my mind assert statements should not be compiled if not in debugging, from what I could tell the package just uses an if (debug) then ... construct.

A quick junky solution I could think of looks like this (It uses abort which is not in the standard, but something more elegant including handling MPI should be relatively simple to write)

module assert
   implicit none
#ifdef DEBUG
#  define ASSERT(X) \
   if (.not. X) then; \
      write(0,*) "Assertion failed: ",__FILE__,":", __LINE__; \
      call abort; \
   end if
#else
#  define ASSERT(X)
#endif
#define assert ASSERT
end module assert

program test
   use assert
   implicit none
   integer :: a(3) = [1, 2, 3], b(3) = [1, 2, 4]
   assert(10==2)        ! scalar assertion
   assert(all(a==b))    ! array assertion
end program test

That will not work correctly: the preprocessor definition is not taken over by the Fortran compiler unless the whole module appears in the same source file.

True, I used module as a surrogate to having a separate header file and #includeing it, without giving it too much thought. Using #include "fassert.h" should do the trick.

A compiler performing any optimizations at all should easily be able to at least eliminate the code inside the procedure, if not eliminate the call all together if debug is .false.. Or at least that’s the assumption.

1 Like