in/out contracts on prototypes

Manu turkeyman at gmail.com
Wed May 16 19:16:11 UTC 2018


So, in/out contracts are cool. They can be used to assert valid value
ranges for arguments and return values.
This is useful for proving correctness, and also, this limiting of
value ranges is information that the optimiser can take and use in
various optimisations.

I often call to extern C/C++ code, or even to D code built in a static
lib with a .di as interface.
Sadly, in/out contracts can not be used and offer no advantage in
these cases, because calls are  made via function prototypes.

I'm wondering if it should also be possible to apply in/out contracts
to function prototypes?
They are usually evaluated in the entry/exit blocks when compiling
functions, but when applied to prototypes, they would rather need to
be evaluated immediately before/after the function call in the calling
code.

Some advantages of this are:
  - Attributing C/C++ functions with contracts to prove that they're
called correctly, where calling from C code would otherwise just rely
on documentation to inform correct arguments.
  - The optimiser is able to gain value from known valid value ranges,
even when inlining is not possible (ie, opaque binary interface/libs).

This is kinda neat; we are able to offer a superior experience wrt
perf and correctness, even when calling C api's! (assuming the author
of the C binding takes the time to translate the documented argument
validity to contracts, which feels worth the effort!)


More information about the Digitalmars-d mailing list