swig-fortran / swig

This fork of SWIG creates Fortran wrapper code from C++ headers.
http://www.swig.org
Other
42 stars 11 forks source link

Change exception/error handling to be more fortran-ish #137

Closed sethrj closed 4 years ago

sethrj commented 4 years ago

At present, C++ exception handling via SWIG uses a module variable ierr and procedure get_serr that must be manually checked after every call that potentially raises an exception:

call do_something(3)
if (ierr /= 0) then
  write(*,*) "failed:", get_serr()
  stop 1
end if

(This ierr variable was chosen to look like MPI's F77 interface but in newer versions it's an optional ierror argument.)

In contrast, Fortran 90 and newer has read and write commands with optional iostat (and in 2003, a string iomsg) arguments that are set if an error occurs; if iostat are absent, the program aborts on error. Similarly, the deallocate and allocate statements in Fortran 2003 have optional arguments stat (an integer: nonzero value means error) and errmsg (in 2003+, an intent(out) string with the error message). Similarly, Fortran 2008 adds stat and errmsg to their "coarrays" statements/intrinsics.

We could make exception handling safer and more standard-like by doing the following:

  1. Any procedure with the %exception feature applied gets two optional Fortran keyword parameters in the proxy function wrapper.
  2. Using if present(stat), set the error code; and also if present(errmsg) set the exception string. [As with Fortran, do not change errmsg if no error occurs.]
  3. If stat was not present, and an exception occurs, terminate with the error code and message.

Besides being more Fortran-ish, this would also remove the need for an <extern_exception.i> and the associated complications. It could also make exception handling thread-safe.

Drawbacks I can think of:

sethrj commented 4 years ago

Or maybe analogous to iostat we use reserved swigstat and swigerrmsg.

sethrj commented 4 years ago

Closing for now due to technical hurdles and lack of interest.