r/cpp • • 1d 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?

56 Upvotes

76 comments sorted by

5

u/Wurstinator 18h ago

"aliases will not make it better" -> then what would like to see instead, if not shorter names / less nesting?

0

u/CornedBee 14h ago

File-scoped statements. Make it possible to use a using directive or a namespace alias in a header without having it be visible outside the header.

I don't necessarily endorse this, but it would solve the issue, which I've also seen a few times.

Or just rewrite everything to use modules.

5

u/Wurstinator 8h ago

Modules are already a thing; so the C++ Standard already did it's job there, as much as you asked, didn't it?

You can't really expect the committee to design the language focused on people that aren't moving with the updates.

-4

u/grishavanika 17h ago

yeah, I just consider deep namespaces and or long namespace names a code smell. At most 2 levels deep, short names. Personally, I would go as far as saying that standard library should have std:: only, but that is already long gone.

7

u/Wurstinator 17h ago

Then why do you say that aliases won't make it better? Solving what you're asking for is the main point of them.

9

u/DuranteA 14h 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)

13

u/notadragon34 1d 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.

38

u/Wenir 1d ago

This is embarrassing 

14

u/Daniela-E Living on C++ trunk, WG21 |🇩🇪 NB 19h ago edited 19h 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: constexpr was even more controversial at its inception, but it was likely regarded as an expert-level feature.

-1

u/_a4z 18h 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 it

Is 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.

12

u/Daniela-E Living on C++ trunk, WG21 |🇩🇪 NB 17h ago • Bravo

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.

-4

u/_a4z 17h 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.

3

u/othellothewise 6h 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/13steinj 9h 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.

27

u/holyblackcat 18h 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."

9

u/spin0r committee member, wording enthusiast 12h 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.

-1

u/holyblackcat 10h ago

I wouldn't want custom namespacing rules, I just want a shorter name, e.g. std::contracts::enforced.

8

u/FriendlyRollOfSushi 17h 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 of requires statements.

2

u/James20k P2005R0 5h ago

Its also not ideal how last minute this is being done

20

u/El_RoviSoft 1d ago

it’s just a normal thing at this point

that’s why headers like fwd.h exist in almost every mature codebase

9

u/HommeMusical 17h ago

But those are bad for comprehension.

I see string in some code and #include "blah/fwd.h. Now, my guess is that string is probably std::string but I have to check fwd.h, and for all I know, there are two symbols called string and another one is being resolved. And it's even worse for less common symbols.

If I see std::string in some code, there is zero doubt to anyone what it is.

1

u/El_RoviSoft 8h 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

8

u/no-sig-available 17h 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.

4

u/almost_useless 16h 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 13h 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.

5

u/almost_useless 12h ago

If you build your code with proper compiler options

The whole point is to not make it an option

17

u/__christo4us 1d 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;
} 

18

u/ContraryConman 1d 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?

17

u/__christo4us 1d ago

Yeah, ignorability of attributes was a needless design choice. Unfortunately, it squanders the opportunity for nice concise syntax in situations like this.

3

u/13steinj 9h 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.

11

u/starguy69 1d ago

Attributes are ignorable so I don't think this would make the NBs happy

24

u/-dag- 1d ago

So why not

    [[enforced]]<std::attributes:: retention_policy::retained>

13

u/MarkSuckerZerg 19h ago

get this man on the committee now!

-1

u/CornedBee 14h ago

std::attributes::processing_policy::required

0

u/-dag- 12h ago

Now you're just bikeshedding. 

2

u/HommeMusical 17h ago

Attributes are ignorable

It's like we never learn from our mistakes.

6

u/Syracuss graphics engineer/games industry 14h 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.

3

u/no-sig-available 12h 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 12h 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.

2

u/13steinj 9h ago

Standard attributes should never be ignorable.

I don't care if compilers do or don't ignore compiler-specific attribute namespaces.

2

u/Syracuss graphics engineer/games industry 8h 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 8h 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.

3

u/Syracuss graphics engineer/games industry 8h 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 8h 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.

2

u/__christo4us 6h ago edited 6h 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 enforced was 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 with enforced present vs absent (enforced vs possibly ignored evaluations of the predicates of contract assertions and contract violations for certain program inputs).

You could say that enforced could 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.

-1

u/__christo4us 12h ago edited 5h 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 final and override which were originally proposed as attributes, and also could have been the case with the class property specifiers replaceable_if_eligible and trivially_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 11h 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.

0

u/__christo4us 6h ago

Sure, I just wanted to add to the discussion by pointing out some of the flaws of attributes.

2

u/drbazza 13h ago

I say this without sarcasm, C++ is the language that others learn from. Either there's a feature that demonstrably good, such as templates. Or there are mistakes that absolutely terrible and other languages go out of their way not to repeat.

2

u/mort96 1d 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?

9

u/__christo4us 1d ago

Not until C++29 with the proposed assertion-control objects: https://isocpp.org/files/papers/P3400R5.pdf

11

u/LiAuTraver 23h 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.

6

u/pjmlp 20h 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.

2

u/othellothewise 5h ago

Well, this is only if you want always-on contracts, which is not like assert. The assert-like syntax is just contract_assert(condition)

7

u/sephirostoy 1d ago

std::contracts::enforced probably would have been enough. 

3

u/FabioFracassi C++ Committee | Consultant 9h ago

but then using namespace std::contracts would draw in many more names and risk many more clashes.
the additional ::controls allows 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.

3

u/lally 11h 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/manni66 13h 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.

3

u/Challanger__ 1d ago
  1. please fix code formatting in post
  2. contracts may not even make it alive into the standard

5

u/Wonderful-Habit-139 1d ago

Could they make it dead into the standard?

7

u/-dag- 1d ago

They already are.

2

u/Tringi github.com/tringi 22h 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 21h 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

1

u/Tringi github.com/tringi 17h ago

Yes, certainly. And the error messages, oh boy. Still, I believe the simplicity gained would be worth it.

1

u/samadadi 22h 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 17h 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?

2

u/othellothewise 5h 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 ++ 16h ago

pre<std::contracts::controls::enforced>(x > 0)

Yeah, nobody's gonna bother with this

1

u/EmaerSeven 17h 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?

-1

u/mcencora 14h 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);`.

6

u/spin0r committee member, wording enthusiast 12h 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.

3

u/mcencora 12h 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:

  1. the current one - no contracts or 'ignored' semantic,
  2. 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".

-1

u/mcencora 10h 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 9h ago edited 9h 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.

0

u/UndefinedDefined 5h 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.

-2

u/def-pri-pub 11h ago

I haven’t written this much syntax for one feature since learning Java back in 2009.