haskell / c2hs

c2hs is a pre-processor for Haskell FFI bindings to C libraries
http://hackage.haskell.org/package/c2hs
Other
198 stars 50 forks source link

No error when declaring too few arguments in {#fun ... #} #149

Closed kolmodin closed 8 years ago

kolmodin commented 9 years ago

Declaring a function that takes one argument, and then trying different {#fun ... #} declarations.

// c.c
void test(void *arg) {
  // do something
}
// c.h
void test(void *arg);

Here's the issue; If we declare too few arguments there is no c2hs error.

-- test.chs
#include "c.h"

{#fun unsafe test as ^
  {} -> `()' #}

c2hs test.chs compiles without a problem, and generates this code (shortened);

test :: IO ()
test =
  test'_ >>
  return ()
foreign import ccall unsafe "test.chs.h test"
  test'_ :: (IO ())

But, there is no such function void test(). test takes an argument. GHC happily compiles the code, and it leads to runtime issues.

It'd be much better if c2hs complained when too few arguments have been declared. c2hs does complain when you declare too many arguments in the {#fun ... #} declaration.

-- test.chs
{#fun unsafe test as ^
  { `Ptr ()',
    `Ptr ()' } -> `()' #}

Yields this error;

test.chs:7: (column 5) [ERROR]  >>> Function arity mismatch!
  This parameter is in excess of the C arguments.

The feature of complaining when you give too many, too few, or arguments of the wrong type is one of the major strengths of c2hs, IMHO. It's one of the biggest advantages to using c2hs instead of hand writing the foreign import declarations. c2hs has been extremely useful in my project where I bind to a C library that keeps changing its API, but I did get bitten when they added new arguments and my {#fun ... #} declarations were not updated and didn't result in errors.

ian-ross commented 9 years ago

@kolmodin OK, that's a terrible error. It definitely shouldn't be like that! It's not impossible that this used to work and I introduced this when I was working on variadic function hooks a while ago. In any case, I'll fix it soon!

kolmodin commented 9 years ago

Thanks for looking into it!

kolmodin commented 8 years ago

Thanks @ian-ross!

ian-ross commented 8 years ago

@kolmodin No problem. I'm only sorry it took so long -- I started a new job recently, and it's left little time for open source work!

kolmodin commented 8 years ago

I know what you mean, no worries :) I've hardly had time to work on my project (that uses c2hs) anyway, similar reasons :)