lfortran icon indicating copy to clipboard operation
lfortran copied to clipboard

Pointer usage pattern with optional arguments

Open ivan-pi opened this issue 1 year ago • 1 comments

I was searching for an issue to suggest possible syntax warnings and hints. Feel free to link or copy this one there, if such an issue exists.

F2018, allows interfacing C routines which accept NULL arguments as a convention for an unused/absent argument.

For example in C:

void print_optional(int *a) 
{
   if (a != NULL) printf("a = %d\n", *a);
}

In Fortran, this would be called as

use, intrinsic :: iso_c_binding, only: c_int

interface
   subroutine print_optional(a) bind(c)
      import c_int
      integer(c_int), intent(in), optional :: a
   end subroutine
end interface

integer(c_int), allocatable :: b

call print_optional() ! do nothing
call print_optional(a=33) ! print 33

! ... allocate and initialize b ...

call print(a=b) ! does nothing or prints b, depending on the allocation status of b

Variables with the pointer attribute also have these semantics if I'm not mistaken.

The problem is that the Fortran processor cannot analyze the C code, so if optional is missing in the interface, it implies a non-null object will be passed. (Careful with arguments of type c_ptr.)

Maybe for the cases like,

integer(c_int), allocatable :: a
integer(c_int), pointer :: b => null()

call print_optional(a)
call print_optional(b)

it would be helpful to emit a warning, if optional is absent in the interface? The downside is that this will also lead to false positives. (Something like -Wsurprising in GCC.)

I'm confused what is supposed to happen in a case like:

integer(c_int), allocatable, target :: a
integer(c_int), pointer :: b

! a is not allocated

b => a
call print_optional(b) ! do nothing or segfault?

ivan-pi avatar Jun 17 '24 12:06 ivan-pi

Thanks. Just open up a new issue for every new warning or hint that we should do.

certik avatar Jun 17 '24 15:06 certik