New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use static asserts in C code #69744
Comments
Proposed patch converts some dynamic assert to static asserts (Py_BUILD_ASSERT_EXPR). This allows to check static invariants at compile time. |
+ (void)Py_BUILD_ASSERT_EXPR(INT_MAX <= _PyTime_MAX / SEC_TO_NS); Hum, maybe the existing macro should be renamed to Py_BUILD_ASSERT_EXPR and a new Py_BUILD_ASSERT_EXPR macro should add the (void) to ignore the result? It would avoid to have to repeat (void) everywhere. What do you think? |
This is a public name and can be used in third-party code. |
Do you mean that a library can really rely on the result!? It would be insane :-) |
Hum, maybe I wasn't clear: I propose attached macro.patch. |
A library can follow the example in the comment. #define foo_to_char(foo) \
((char *)(foo) \
+ Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0)) |
Serhiy, could you please not change stuff that I maintain? I know |
OK, I'll exclude Modules/_decimal/_decimal.c. |
Thank you! |
New changeset ad44d551c13c by Serhiy Storchaka in branch '3.5': New changeset 51f3547da99c by Serhiy Storchaka in branch 'default': |
Wrong issue. The correct one is bpo-24726. |
Oh, no, the correct one is bpo-25410. |
use_Py_BUILD_ASSERT_EXPR.patch looks good to me. But you should revert the change on decimal, as asked by Stefan, and I suggested to move an assertion inside the related function (see my comment on Rietveld). """ #define foo_to_char(foo) \
((char *)(foo) \
+ Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))
""" Hum ok, I know understand the "_EXPR" suffix of the macro name. Maybe it's worth to add a new #define Py_BUILD_ASSERT(expr) (void)Py_BUILD_ASSERT_EXPR(expr)" macro? By the way, I don't know what happens if you pass a variable to Py_BUILD_ASSERT_EXPR() rather than a constant. Maybe we could use __builtin_constant_p() on GCC? Maybe it's overcomplexicated :-) |
New changeset 45a404d33c2d by Serhiy Storchaka in branch 'default': |
If the compiler can't calculate it at compile time (e.g. int_var <= INT_MAX), your are out of luck.
Don't know if it will help. |
This issue can now be closed, no? (I don't think that it's worth to add a new macro and make the existing macro more strict.) |
If the compiler supports variable-length arrays(VLA) then it is unspecified whether or not the size expression is evaluated and no assertion can be checked at compile time. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: