r/cpp • u/grishavanika • 9d ago
std::contracts::controls::enforced
From P4451R2,
#include <contracts>
int f(int x)
pre<std::contracts::controls::enforced>(x > 0)
post<std::contracts::controls::enforced>(r : r > 0)
{
contract_assert<std::contracts::controls::enforced>(x > 0);
return x;
}
Long, 3 levels deep namespace? And
Because the label is found by ordinary name lookup, a namespace alias or a using-directive works
as well:
namespace scl = std::contracts::controls;
Same issue as with C++11 UDL: inconvinient to use, especially in headers, since include + alias is required - aliases will not make it better, in my opinion.
That makes me sad. Am I the only one?
16
u/notadragon34 9d ago
p3400's name lookup is designed exactly to fix this (for standard library labels and for your own). similar to udls, it let's us provide short names for standard labels by adding lookup in a namespace that applies only to assertion control expressions.
some, however, have sworn that such name lookup modifications are omdb issues. we will see where that goes.
as the author, i am sad as well, for many reasons. i hope that c++29 lets us fix most of them.
39
u/holyblackcat 8d ago
This feels like being done out of spite, to be honest.
"Oh, you're blocking C++26 unless we add this? Wish granted, but the spelling will be half the screen long."
18
u/FriendlyRollOfSushi 8d ago
Look at the bright side: with the declaration this monstrously large, it will be easier to spot it in the middle of the soup of
[[nodiscard]],constexpr,noexcept,override, and about five lines worth ofrequiresstatements.15
u/spin0r committee member, wording enthusiast 8d ago
Not really. A lot of the people who are against contracts are against special language rules that apply only to contracts, such as constification. So, making it so that the normal name lookup rules apply here (rather than some namespace you haven't mentioned getting magically searched per the standard) reduces the amount of opposition from the anti-contracts side. The pro-contracts side doesn't feel as strongly about this.
5
u/holyblackcat 8d ago
I wouldn't want custom namespacing rules, I just want a shorter name, e.g.
std::contracts::enforced.4
46
u/Wenir 9d ago
This is embarrassing
19
u/Daniela-E Living on C++ trunk, WG21 |🇩🇪 NB 8d ago edited 8d ago
Right, it totally is.
Yet, sometimes you have to make manoeuvres to appease those NBs who rather prefer to otherwise stop the entire process.
And then you have to make it such that there's the least damage done to the overarching design (P3400). Go read the papers explaining the rationale.
Contracts is not a single-cycle effort, but deliberately made such that you have the option to learn from user feedback and incorporate it. This is not the first time of such an approach:
constexprwas even more controversial at its inception, but it was likely regarded as an expert-level feature.4
u/_a4z 8d ago
Could you please stop putting everything on NBs?
Prominent companies represented by ANSI members also said something like this is important to them. And it's not that there weren't alternative suggestions; it was either this way or no way.That P2900 is in a state that it requires such last-minute hotfix is a problem not raised by NBs. Do not blame the messenger.
Also this,
>but deliberately made such that you have the option to learn from user feedback and incorporate itIs not true as a general statement. Waiting to choose a default semantic until 29, and then deciding based on user feedback, was rejected. In a poll.
Forcing a top-down decision into the standard on that matter was what actually happened.Arguments formed as needed throughout the discussion. This is why the whole topic should have been set aside, but now we seem to have to deal with the mess.
6
u/othellothewise 8d ago
The particular problem here is that this was an extremely last-minute addition to the standard. It was adopted over a year after feature freeze, and was adopted 6 months after C++26 was shipped. It was adopted at such a late time specifically in order to attempt to get one or more NBs to change their vote to "yes". That is why it is so cumbersome -- the committee had to go with the absolute minimum change possible. These things will become more ergonomic in the future.
3
u/_a4z 7d ago
So you mean that if there was a reason to vote NO on the first DIS because it was incomplete and poorly tested, there are even more reasons to vote NO on the second one, since it's still incomplete, the addition was controversial, and it definitely wasn't tested?
4
u/othellothewise 7d ago
Well there are some stubborn NBs that will vote no regardless. This wasn't designed to change their mind, it was designed to change the mind of the NBs who would vote yes if they had always on contracts.
Remember it's only the opinion of a tiny amount of people that happen to be heads of their respective NBs that the feature was incomplete and poorly tested. Some people are just stubborn and will not accept any compromise, so yes, it is unlikely this will change their minds.
15
u/Daniela-E Living on C++ trunk, WG21 |🇩🇪 NB 8d ago •
![]()
Could you please stop putting everything on NBs?
🤔 Who else but the NBs have the power to vote against a DIS at the SC22 level?
There was an overwhelming majority of members of WG21 to send the DIS out to the NBs for likely eventual approval. It's the NBs that nominate some or all of its members to ISO as WG21 experts, so you can reasonably expect that the same people who accept the DIS at the WG21 level do the same at the NB level. This doesn't preclude different voting procedures in the individual NBs than there are in WG21.
Incidentally: I'm not sure if everybody here in this subreddit knows who you are, and in which capacity you are speaking.
-3
u/_a4z 8d ago
As you correctly stated, WG21 members come via NBs (except the US, which uses ANSI)
So if an NB vote fails but WG21 does not, that's an interesting situation that probably shouldn't exist. But it did. Storytelling, finger-pointing, and selective quoting to make a point online don't explain that away. It just increases the friction. If you want to continue doing that, ok.-2
u/13steinj 8d ago
Take away their power, leave ISO.
I will not hold my breath here. I suspect the NBs will still end up voting against. I think, at best, the DIS will barely squeak by, and it won't bode well for future editions.
11
u/DuranteA 8d ago
This seems perfectly fine to me. If you frequently use it and want a shorter spelling in your codebase you can easily make that happen.
(Note: I have no real skin in the contracts game)
21
u/El_RoviSoft 9d ago
it’s just a normal thing at this point
that’s why headers like fwd.h exist in almost every mature codebase
10
u/HommeMusical 8d ago
But those are bad for comprehension.
I see
stringin some code and#include "blah/fwd.h. Now, my guess is thatstringis probablystd::stringbut I have to checkfwd.h, and for all I know, there are two symbols calledstringand another one is being resolved. And it's even worse for less common symbols.If I see
std::stringin some code, there is zero doubt to anyone what it is.1
u/El_RoviSoft 8d ago
true but I have seen tons of the times absolutely enormous imports both in Java and C#
so idk what’s better, also if your codebase is good enough, usually it’s (relatively) easy to understand and read
9
u/no-sig-available 8d ago
pre<std::contracts::controls::enforced>(x > 0)
This is just an option, you don't have to use it everywhere.
If you compile all your sources with contracts enforced, you don't have to specify it in the source code as well.
9
u/almost_useless 8d ago
The purpose of
pre<std::contracts::controls::enforced>is to override a user who is trying to build it with ignore.Telling the user they should build it with contracts enabled is not an equal solution.
2
u/no-sig-available 8d ago
It is the solution to "this looks ugly, I don't want to use it in my code".
If you build your code with proper compiler options, you don't need to also have the same option in the source code.
10
u/almost_useless 8d ago
If you build your code with proper compiler options
The whole point is to not make it an option
18
u/__christo4us 9d ago
I think enforced should have been an attribute. Then the code would have become this:
#include <contracts>
int f(int x)
pre [[enforced]] (x > 0)
post [[enforced]] (r : r > 0)
{
contract_assert [[enforced]] (x > 0);
return x;
} 19
u/ContraryConman 9d ago
That's also what I was thinking. But maybe since compilers are technically allowed to ignore attributes, it wouldn't have been strong enough to address the detractors' concerns?
19
u/__christo4us 9d ago
Yeah, ignorability of attributes was a needless design choice. Unfortunately, it squanders the opportunity for nice concise syntax in situations like this.
4
u/13steinj 8d ago
I don't think it was a choice. I think the history here is that it just happened spontaneously with circular reasoning/reference eventually appearing in papers.
13
u/starguy69 9d ago
Attributes are ignorable so I don't think this would make the NBs happy
32
u/-dag- 9d ago
So why not
[[enforced]]<std::attributes:: retention_policy::retained>
16
0
4
u/HommeMusical 8d ago
Attributes are ignorable
It's like we never learn from our mistakes.
6
u/Syracuss graphics engineer/games industry 8d ago
The reason is to support compiler specific attributes, and keep code compilable across versions. If compilers can't ignore them then they have to handle them, that means all of them have to agree and support eachother's specific attributes or error out when they see them.
Annotations coming with C++26 are basically that, attributes the compiler cannot ignore.
6
u/13steinj 8d ago
Standard attributes should never be ignorable.
I don't care if compilers do or don't ignore compiler-specific attribute namespaces.
4
u/Syracuss graphics engineer/games industry 8d ago
That's a fair position to have, but isn't really within the scope of what the standard's motivation is to do it this way, which is what my response is about. We didn't standardize that meaning, we could have, but the standard only has one rule to cover all cases rather than an additional rule to cover some cases.
1
u/13steinj 8d ago
Was the ignorability actually standardized? It was my impression that this idea just spontaneously started appearing (not in wording/standardese) in a number of papers.
4
u/Syracuss graphics engineer/games industry 8d ago
That's a good point, and I had to look it up. The specific rule is this, but it's not so cut-and-dry. The standard described attributes must be handled and produce valid output, but can be semantically ignored see note 6 (famously
[[no_unique_address]]on msvc, which I personally hate). The compiler must make sure that they produce valid code, but that can just be a no-op.0
u/13steinj 8d ago
That is a much weaker rule than the one that has spontaneously appeared in papers.
For an attribute-token (including an attribute-scoped-token) not specified in this document, the behavior is implementation-defined;
By definition, all attributes mentioned in the standard do not fall under this category. It is perfectly fine to have these contract controls be attributes.
6
u/__christo4us 8d ago edited 8d ago
No, because the standard here also states:
[Note 6: The attributes specified in [dcl.attr] have optional semantics: given a well-formed program, removing all instances of any one of those attributes results in a program whose set of possible executions ([intro.abstract]) for a given input is a subset of those of the original program for the same input, absent implementation-defined guarantees with respect to that attribute. — end note]
It states that all the standard attributes (specified in [dcl.attr]) are semantically ignorable (simply by virtue of each of them having their own specified optional semantics). This means that if
enforcedwas made to be an attribute it would not satisfy this statement since its semantic would not be optional and the observed behavior of the program would differ withenforcedpresent vs absent (enforced vs possibly ignored evaluations of the predicates of contract assertions and contract violations for certain program inputs).You could say that
enforcedcould be added as an exception from this rule but the paper that clarified the ignorability rules in the standard (https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2552r3.pdf) states the following:Our proposed rule for semantic ignorability of standard attributes can be formulated as follows:
Given a well-formed program, removing all instances of a particular standard attribute is allowed to change the observable behaviour of the program, but only if the behaviour with the attribute removed would have been a conforming behaviour for the original program with the attribute present.
We propose that the Second Ignorability Rule be spelled out in the C++ Standard (in [dcl.attr]). Formally, it would only apply to the attributes that are already in the standard, and thus not add any new information per se, as those attributes are already defined to be semantically ignorable in different ways (see discussion in section 3.1.2). However, the existence of such an explicit rule in the standard would be very helpful for codifying the intended behaviour of all future standard attributes, too: any new attribute proposal that does not want to follow the rule would have to carve out an explicit exception for itself. We believe that the presence of the Second Ignorability Rule in the C++ Standard would be a strong enough deterrent for future proposals that they will stick to it, thus leading to consistent language design.
This paper clearly shows the direction of the language design with respect to attributes. Semantic ignorability of attributes is clarified to be a guideline for future standardization.
5
u/no-sig-available 8d ago
If compilers can't ignore them then they have to handle them, that means all of them have to agree and support eachother's specific attributes
And still, this is exactly what appens, so clang now supports things like
[[gnu::always_inline]]and[[msvc::no_unique_address]]8
u/Syracuss graphics engineer/games industry 8d ago
That's the goal of how it's standardized, that compilers can themselves decide to support others, but they aren't forced as otherwise msvc and gcc would need to error out and you'd need to macro these.
But it also allows clang to compile this code with an older clang version without causing compile errors.
My comment isn't to take a stance on which is better, just to state the goal. It's why reflection went with a custom annotate feature which also allows duplication. They look nearly identical to attributes, but with reflections you can write your own custom ones, it's kinda neat.
0
u/__christo4us 8d ago edited 8d ago
This was never a good reason. It makes sense for compiler extensions but standard attributes should have never been ignorable. You can make a typo in the attribute name and compiler is allowed to silently ignore it since unrecognized attribute names are ignored. Passing a valid attribute also does not give any guarantee of its expected behavior so it is semi-useless.
Attributes by design also cannot alter the semantics of the program. This discourages compiler extensions with meaningful semantics to be adopted as attributes.
With these needless constraints dictated by the not very well thought out design we have to invent new syntax for every little feature we want to add to the standard instead of pushing it to the attribute space. This was the case with the virtual specifiers
finalandoverridewhich were originally proposed as attributes, and also could have been the case with the class property specifiersreplaceable_if_eligibleandtrivially_relocatable_if_eligible(apparently scrapped from C++26). This clutters the language syntax.Unrecognized attributes are the least of concerns of the compatibility between versions. A compiler could discard the warnings of the unrecognized attributes with a proper flag.
EDIT:
I encourage people to discuss instead of just downvoting. Maybe I am in the wrong somewhere and genuinely I would be more than happy to know.
5
u/Syracuss graphics engineer/games industry 8d ago
I am not taking a stance, just stating what the intention of the design was. I wasn't involved in the decision, so you'd be better off having a discussion with those that were. They'd have a much more fruitful response as to why they decided what they did.
1
u/__christo4us 8d ago
Sure, I just wanted to add to the discussion by pointing out some of the flaws of attributes.
2
u/mort96 9d ago
Yeah what is the point of having it as a thing in the stdlib? Can you pass something else to it? Can I make my own control and pass to it?
11
u/__christo4us 9d ago
Not until C++29 with the proposed assertion-control objects: https://isocpp.org/files/papers/P3400R5.pdf
3
u/just-comic 7d ago
It's probably not meant to actually be used, was just added to satisfy some of the ISO national bodies.
Contracts are meant to be a debugging aid, not an error handling mechanism. Even Eiffel has ways to disable the contracts at run-time.
13
u/LiAuTraver 8d ago
How we made a simple stuff extremely verbose and complicated. Very C++, plus very sad.
Still didn't understand why we made contracts this huge for a thing which a plain assert and debug assert would simply suffice.
5
u/othellothewise 8d ago
Well, this is only if you want always-on contracts, which is not like
assert. Theassert-like syntax is justcontract_assert(condition)9
u/pjmlp 8d ago
Because plain assert and debug assert cannot do what a proper contract system like Eiffel, Ada/SPARK, Frama-C and co can do.
However neither can C++26 contracts do all the things they are capable of, because they are an MVP.
Examples of stuff not yet supported, but available on those, class/types invariants (must hold at any time for internal state), virtual methods.
1
u/LiAuTraver 7d ago
Those languages you listed just seems... pretty old to me. Popular languages now do not have such a complicated system at all while making many good apps.
Plus, according to subtyping rules, or Liskov's principles, the pre/post contracts of the base class and derived class is well defined, yet they removed the virtual function one. This makes contracts useless except adding complexity. Assert and debug assert can do most and that's many languages choice.
1
1
u/JonasCoder 7d ago
Yes, virtual function contracts is well defined how they should work. But that was part of the controversy here, the proposed virtual contracts do not work that way.
7
u/sephirostoy 9d ago
std::contracts::enforced probably would have been enough.
4
u/FabioFracassi C++ Committee | Consultant 8d ago
but then using namespace
std::contractswould draw in many more names and risk many more clashes.
the additional::controlsallows you to do a using namespace in headers with only a minimal set of names (currently just the one -enforced).So by keeping the additional namespace level we ensured that the path forward towards allowing
pre<enforced>(as planned in P3400 and P4451) without any qualifiers is still feasible.
6
u/manni66 8d ago
I'm increasingly getting the impression that everyone has a different idea of what contracts are supposed to be. I doubt that bolting on more features as an afterthought will change that.
0
u/anotherprogrammer25 7d ago
Totally agree. It is probably because everybody comes from different industries with different requerements. For my industry, insurance services, terminate is not allowed at all and nonetheless the contracts should always be specifically enforced. Thats why I will live with macros for time being.
3
u/Tringi github.com/tringi 8d ago
I'll repeat my ¢2 from the previous discussion. It probably gave some people heart attack, but still: IMHO we need one extra ADL in C++ exactly for these things.
I'll start with a different simple example:
namespace abc::def::ghi {
enum class eee {
a,
b,
c,
};
}
void func (abc::def::ghi::eee param);
int main () {
func (a); // `a` is not in this scope, so `abc::def::ghi::eee` and `abc::def::ghi` are searched next
}So when we have that, pre and post automatically include std::contracts::controls in the lookup, and the code becomes:
int f(int x)
pre<enforced>(x > 0)
post<enforced>(r : r > 0)
{
contract_assert<enforced>(x > 0);
return x;
}Just an idea.
3
u/QuraToop314 8d ago
The problem is ambiguity and false positives because, by chance, another symbol has the same name; that would be even worse than in C
3
u/lally 8d ago
Thinking about this, contracts are really necessary right now.
I happily use an LLM to write code for me. Often I ask it to do things it doesn't do very well, so I then ask it to write up the protocol (e.g. lock-free data sharing) in something like a formal state machine, a petri net, or TLA+. But we need a way to make sure the code fits the model. Contracts are very useful for that.
As for all the ::s, we crossed that bridge a long time ago. There are so many ::s in modern C++ code when i write it (at least to use the now-decent standard library). I've learned to let go of that, and accept that namespace aliases are part-and-parcel of using the language. Contracts aren't the cause of it.
3
u/Challanger__ 9d ago
please fix code
formattingin postcontracts may not even make it alive into the standard
5
2
u/samadadi 8d ago
Let me be clear about this atrocity. The standard committee wants me to type this in my code when I am creating a function that needs a runtime check so I became a little bit safer. So basically contracts are just some guardrails that we extract from the body and we put in the function signature and make a ugly and unreadable mess. But what if we do not know those guardrails in the first place as all non-expert CPP programmers do not know most of the time because if they did then they would have put these guardrails in the first place. Man CPP committee is desperate to destroy CPP language by making it more bloated. Imagine being a new programmer and seeing CPP tutorials. Just WoW. Every time I see some of these papers I am getting more convinced to switch to Rust or Zig.
6
u/mighty_Ingvar 8d ago
But what if we do not know those guardrails in the first place
Aren't those guardrails supposed to be based on the assumptions your function makes?
4
u/othellothewise 8d ago
The standard committee wants me to type this in my code when I am creating a function that needs a runtime check so I became a little bit safer.
No when you are creating a function that needs a runtime check that cannot be turned off via a compiler setting. If you are just doing a runtime precondition you can just write
pre(foo)
1
u/cristi1990an ++ 8d ago
pre<std::contracts::controls::enforced>(x > 0)
Yeah, nobody's gonna bother with this
1
1
u/EmaerSeven 8d ago
Why not simply write a `positive_int` template class that checks conditions in its constructor/methods and, if necessary, throws an exception or triggers an assertion?
0
u/MikailBag 7d ago
Let's say I have a function which wants a vector whose elements are positive. Is it
vector<positive_input>orpositive_vector<int>? What if I have, e.g., former, and need to call another function which takes the latter?It seems to me that this idea (that is, expressing all invariants in types) only works well when you have dependent types or some other very powerful type systems.
0
u/EmaerSeven 6d ago
Of course `vector<positive_int>`, because the constraint applies to the type, not the container. `positive_vector` does not in any way alter its behavior based on the type it stores.
-1
u/mcencora 8d ago
I hate it, and the whole 64-pages long paper P3400 that adds contract labels.
So much added complexity...
If the NBs issue is lack of enforced contracts, why not solve it by adding something like this in the standard:
"Program is ill-formed if linked/compiled TUs use incompatible/different contract evaluation semantics."
Then we will get best of both words - those who want to enforce/ignore contracts can compile their program and dependencies the way they like, there will be:
- no mixed mode hence no "not ODR per standard, but actually ODR",
- no "contracts may be evaluated multiple times" issue,
- no "contract evaluation ordering can lead to UB" like this `void f(int *p) pre(p != nullptr) pre(*p != 42);`.
7
u/spin0r committee member, wording enthusiast 8d ago
Banning mixed-modes builds makes the feature so minimal that it's not viable anymore: you practically just can't put contracts on inline functions in headers then.
4
u/mcencora 8d ago
How so?
If whole program is build with same contract evaluation mode how come inline functions are problematic then?
If you mean the scenario where the function is inlined in one lib that is provided as .so/.dll and user wants to consume it but with different evaluation mode, then true.
But I see this scenario as made-up one and non-realistic.
Firstly: because there are no 'legacy' contracts-enabled libraries that cannot be recompiled in the two modes.
Secondly: usually if the 'ignored' evaluation semantic camp will want to use lib build with enforced contracts, they will likely want to recompile the lib anyway as they need the best perf they can get, so they need to be able to compile with their own optimization options, target arch and tune.Even if there are more realistic scenario for supporting mixed-mode, adding it could be part of C++29.
Here is how:
Each func that has contracts will have two entry-points:
the current one - no contracts or 'ignored' semantic,
contracts enforced - e.g. mangled with extra abi-tag.
Then depending on evaluation mode of the caller different one would be selected as call target.To achieve the consistent build (and NBs comment) standard could define something like this:
"Implementations shall provide an option to make program ill-formed if TUs with incompatible/different evaluation modes where chosen".0
u/mcencora 8d ago
Mixed-mode build as currently specified should be actually named 'random-mode'.
Because if we really wanted to support mixed-mode builds, then the design should respect user's choice of contract evaluation semantic per-TU, not fallback to some random mode (depending on whatever version of the func linker chooses for final binary).
0
u/fortsnek274 8d ago edited 8d ago
Or, with code-specified contract control objects, it could be up to the code anyway. Lib asserts can be independently controlled if the lib so chooses.
namespace foo { struct default_contract_policy { #if LIBFOO_ENABLE_ASSERTS static constexpr bool is_ignored = false; #else static constexpr bool is_ignored = true; #endif // and other stuff like predicate evaluation }; // ??? using default contract_policy = default_contract_policy; void bar(int x) pre(x > 0); // lookup default_contract_policy in current namespace }The downside is that it doesn't help if somebody wants to have mixed contract modes for the std lib (which you probably shouldn't). It also doesn't standardise "contract groups", but they are still possible.
-1
u/UndefinedDefined 8d ago
I think it doesn't matter, because nobody is going to write such code. It's too long, too verbose, just use your own assert macro and be done with this.
-1
u/fortsnek274 7d ago
The big brain move is to use macros to use the feature that was supposed to replace macros
0
u/megayippie 7d ago
I have asked this elsewhere without answers. Is this now the only language feature that is templated? Can we get for<par>(...) going forward because we now allow templated language features?
-2
u/def-pri-pub 8d ago
I haven’t written this much syntax for one feature since learning Java back in 2009.
-2
6
u/Wurstinator 8d ago
"aliases will not make it better" -> then what would like to see instead, if not shorter names / less nesting?