Contracts for C

gustedt.wordpress.com

107 points by joexbayer 9 days ago


AlotOfReading - 5 days ago

There's a bit of an impedence mismatch with Contracts in C because C++ contracts exist partially to rectify the fact that <cassert> is broken in C++.

Let's say you have a header lib.h:

    inline int foo(int i) {
        assert(i > 0);
        //...
    }
In C, this function is unspecified behavior that will probably work if the compiler is remotely sane.

In C++, including this in two C++ translation units that set the NDEBUG flag differently creates an ODR violation. The C++ solution to this problem was a system where each translation unit enforces its own pre- and post- conditions (potentially 4x evaluations), and contracts act as carefully crafted exceptions to the vast number of complicated rules added on top. An example is how observable behavior is a workaround for C++ refusing to adopt C's fix for time-traveling UB. Lisa Lippincott did a great talk on this last year: https://youtu.be/yhhSW-FSWkE

There's not much left of Contracts once you strip away the stuff that doesn't make sense in C. I don't think you'd miss anything by simply adding hygenic macros to assert.h as the author here does, except for the 4x caller/callee verification overhead that they enforce manually. I don't think that should be enforced in the standard though. I find hidden, multiple evaluation wildly unintuitive, especially if some silly programmer accidentally writes an effectful condition.

tpoacher - 5 days ago

One of the biggest problems I find with contracts whenever contracts are mentioned is that nobody seems to have a really clear definition of what exactly a contract 'is' or 'should be' (with the exception of languages where contracts are a formal part of the language, that is).

I find the general concept incredibly useful, and apply it in the more general sense to my own code, but there's always a bit of "what do I actually want contracts to mean / do here" back-and-forth before they're useful.

PS: I do like how D does contracts; though I admit I haven't used D much yet, to my great regret, so I can't offer my experience of how well contracts actually work in D.

WalterBright - 5 days ago

Digital Mars C++ has had contracts since, oh, the early 1990s?

https://www.digitalmars.com/ctg/contract.html

guerrilla - 4 days ago

I don't know what C++ is trying to do, but does everyone know about frama-c[1]?

1. https://frama-c.com/

__d - 5 days ago

I like Eiffel.

But if I want to use Eiffel, I’ll use Eiffel (or Sather).

I’d rather C remained C.

Maybe that’s just me?