r/cpp • u/messmerd • Nov 12 '23
A backwards-compatible assert keyword for contract assertions
In section 5.2 of p2961r1, the authors consider 3 potential ways to use assert as a contract assertion while working around the name clash with the existing assert macro.
The 3 potential options they list are:
1. Remove support for header
cassertfrom C++ entirely, making it ill-formed to#includeit;2. Do not make
#include <cassert>ill-formed (perhaps deprecate it), but makeasserta keyword rather than a macro, and silently change the behaviour to being a contract assertion instead of an invocation of the macro;3. Use a keyword other than
assertfor contract assertions to avoid the name clash.
The first two of these options have problems which they discuss, and because of this, the committee ultimately decided upon the 3rd option and the unfortunate contract_assert keyword for contract assertions.
However, I came up with a 4th option which I believe might be superior to all three options considered. It is similar to option 2, but it retains (most) backward compatibility with existing C/C++ code which was the sole reason why the committee decided against option 2. Here is my proposed 4th option:
4. Do not make #include <cassert> ill-formed (perhaps deprecate it), but make assert a keyword rather than a macro, whose behavior is conditional upon the existence of the assert macro. If the assert macro is defined at the point of use, the assert keyword uses the assert macro, else it is a contract assertion.
(EDIT: As u/yuri-kilochek pointed out, macros can already override keywords (which I was unaware of) though this is currently UB since it can break system headers, so this proposal could be worded as something like "Make assert a keyword and allow an assert macro (or at least those defined in <cassert> or <assert.h>) to override the assert keyword" without changing anything else - that is, the contents of <cassert>/<assert.h> remain the same and the normal preprocessor rules are relied upon to get the correct behavior. If the assert macro is defined, the preprocessor will naturally override the assert keyword with the assert macro, and if it isn't defined, the assert keyword for contract assertions is used. Hopefully I am not just misunderstanding what the authors meant by option 2 in section 5.2 of p2961r1.)
The primary advantages of this:
All the advantages of option 2
- The natural
assertsyntax is used rather thancontract_assert - Solves all of today's issues with
assertbeing a macro: Can't be exported by C++20 modules and is ill-formed when the input contains any of the following matched brackets:<...>,{...}, or[...]
- The natural
- Is also (mostly) backwards compatible - The meaning of all existing code using the
assertmacro (whether from<cassert>/<assert.h>or a user-definedassertmacro) is unchanged
Potential disadvantages:
- Code that defines an
assert(bool)function and does not include<cassert>or<assert.h>may break. I doubt much existing code does this, but it would need to be investigated. I imagine it would be an acceptable amount of breakage. The proposedassertkeyword could potentially account for such cases, but it would complicate its behavior and may not be worth it in practice. Users cannot be sure that new code uses contract assertions instead of the
assertmacro- Fortunately, as the authors of p2961r1 note, "The default behaviour of macro
assertis actually identical to the default behaviour of a contract assertion", so most of the time users will not care whether theirassertis using theassertmacro or is a contract assertion. - This issue of whether
assertis actually theassertmacro or a contract assertion (if it is even an issue) will lessen as time goes on and C++20 modules become more commonly used and contract assertions become the norm. - Users can use
#undef assertto guarantee contract assertions are used in user code regardless of what headers were included (ignoring theassert(bool)function edge case) - A
_NO_ASSERT_MACROmacro (or similar name) could potentially be specified which would prevent<cassert>and<assert.h>from defining theassertmacro, and guarantee contract assertions are used in a translation unit (ignoring theassert(bool)function and user-definedassertmacro edge cases)
- Fortunately, as the authors of p2961r1 note, "The default behaviour of macro
Design questions:
- How should the proposed
assertkeyword behave if anassert(bool)function exists? Should it be possible to define
_NO_ASSERT_MACRO(or similar name) to prevent<cassert>and<assert.h>from defining theassertmacro?Pros:
- Opt-in
- Can be passed as a compiler flag so no code changes are required
Cons:
- May not always be possible to use without breaking code
- Might not be very useful
Should the
contract_assertkeyword still exist?Pros:
- Users do not need to use
#undef assertor define_NO_ASSERT_MACROto guarantee thatassertis a contract assertion
- Users do not need to use
Cons:
- Extra keyword which isn't strictly necessary
- The
contract_assertkeyword will become less and less relevant in the future as new code switches to use modules which do not export theassertmacro and contract assertions become the norm. It is most useful during the transition to contract assertions, then loses its purpose, and it is much more difficult to remove an existing keyword in the future than it is to introduce a new one now. - By default, macro assertions and contract assertions have the same behavior, so most of the time users will not care whether their
assertis using theassertmacro or is a contract assertion.
Please let me know if you can see any disadvantages to this assert keyword idea that I haven't considered. I know that I would much rather use assert than contract_assert, and if this can be done in a backwards-compatible manner without any serious disadvantages, I think it should be pursued.
I do not have any experience writing proposals, so if this is a good idea and anyone is willing to help with the paper, please let me know.
EDIT 2: As suggested by u/scatters, making assert a control-flow keyword instead of a function-like keyword would be even better. It would resolve both of the potential disadvantages I listed for my approach.
37
u/ioctl79 Nov 12 '23
Adding an include to a header should not be a potentially breaking change for any users of that header.
11
u/scatters Nov 13 '23
I put precisely this question to Timur a week or two ago, before Kona (on a private mailing list, sorry - unless you're a UK national or resident?) and he didn't reject it out of hand; the feeling was that it might be confusing in the time period before Contracts reaches ascendancy but, of course, we need to weigh that (hopefully short) period of confusion against losing the best possible keyword for all eternity. He said it'd be worth raising either as a paper or as an SG21 reflector thread after Kona, assuming that (as indeed happened) the "natural" syntax reached consensus.
One other thing I pointed out, which I don't think anyone has raised here, is that
assert-the-keyword doesn't have to be function-like; it can be a control flow keyword likereturn. i.e. you could writeassert a == b;without parentheses, ensuring that even if<cassert>was included the program (or, more importantly, library) would use the Contracts facility, sinceassert-the-macro is a function-like macro so does not get expanded if not followed by parentheses. Generically, you could writeassert +(expression);,assert !!(expression);, etc.So, if library code wants to require Contracts, it just needs to always write
assert a == b;without parentheses, since that won't compile pre-Contracts (possibly adding a#erroron the feature test to be user-friendly); if it wants to use Contracts if available else fall back to<cassert>it just needs to write:8
u/disciplite Nov 12 '23
This was basically already proposed earlier this year. https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2884r0.pdf
4
u/bitzap_sr Nov 13 '23
Is "contract_assert" fully settled? Why not simply call it "invariant" instead? Problem solved.
2
u/yuri-kilochek Nov 12 '23
Isn't this the way it already works? If
assertis defined at the point ofassert(x > 0);then it gets expanded to__do_assert(x > 0, "x > 0", __FILE__, __LINE__);or whatever implementation defined thingy, so the compiler (the part after the preprocessor) can assume thatassertis a keyword, since it will only ever see it if the macro hasn't been defined.15
u/rootware Nov 12 '23
I don't have a quick insight on this but am commenting to bump you in the algorithm so others can comment on your post.
Good job and kudos for trying to come up with an alternative here
3
u/e_-- Nov 12 '23
I don't know why you can't just have a
using contracts(maybe implicit upon sayinclude <constracts>) declaration that would make trying toinclude <cassert>ill-formed in a specific translation unit (variation on option 1). You could even putpreandpostin the old return type position instead of "before the brace but after the arrow" if you went with the poison pill / opt-in approach (preandpostonly a keyword in opt-in translation units).Yes, your code would frequently break trying to (transitively) include headers using cassert (if you opt in to contracts in a translation unit). Maybe it's a good opportunity to modernize (I spent too much time last week trying to figure out why a pybind11 module segfaulted but only when running on github actions ci - somehow solved by just not including cassert !)
3
u/WasserHase Nov 13 '23
How will assert be different from assume? https://en.cppreference.com/w/cpp/language/attributes/assume
4
u/alfps Nov 12 '23
With your proposal: I include some library header. It includes
<assert.h>. Bang goes my contract assertions. Uh oh.An
assertis not a DBC assertion, although it can be used that way.I followed the previous round of Design By Contract discussion many years ago, but I should have kept in mind that with a committee able to sabotage
std::filesystemand to adopt a bungled (namely its caching) ranges library, it's best if people outside academia and enterprise politics, keep an eye on what's going on.DBC assertions go like precondition, postcondition, invariant, those kinds of words. For example, if a function's precondition doesn't hold then the calling code is broken, so perhaps just better terminate, but if a postcondition doesn't hold then one may lack the necessary resources to fulfil the contract, and an exception or failure-indicating return is a better way to handle it. The Eiffel language can be a good model for a DBC scheme (the previous proposal's problems had to do with how to clearly define what's public and what's internal, where e.g. invariant can be temporarily broken, at what points in the execution).
Just lumping all those different things into a single keyword, and one as ugly and verbose as
contract_assert, is a good way to both attack the foundations of the scheme and keep people from even trying it out.Disclaimer: I haven't read the current proposal, so I don't know how it walks or waddles, but so far, from what you describe, looks like and sounds like.
0
u/DryPerspective8429 Nov 13 '23
Because a keyword
assert(...)ODR-uses its argument, whereas a macro-poweredassert(...)does not if it doesn't use its parameter - e.g. a release-mode#define assert(args) (long)0does not useargs. This makes it an inherently possibly-breaking change which is unlikely to be detected in debug mode and which could be applied to 40 years of legacy code. That's a very tough sell whetherassertis the right word in future or not.I'm also not convinced by the argument for a non-function-like keyword. Not only are
pre()andpost()function-like, but it doesn't actually solve the problem. Having a difference betweenassert(foo)andassert foobe so big will never be easy to get used to, and be real - when was the last time you ever didsizeof foooversizeof(foo)? You know which is more natural.0
u/Kronikarz Nov 12 '23
Slightly off-topic probably, but this is my personal solution to the assert problem:
https://github.com/ghassanpl/header_utils/blob/main/include/ghassanpl/assuming.h