Title: Tracker: protect macros expansions using `do { ... } while (0)` constructions or via `static inline` equivalents when possible · Issue #124044 · python/cpython · GitHub
Open Graph Title: Tracker: protect macros expansions using `do { ... } while (0)` constructions or via `static inline` equivalents when possible · Issue #124044 · python/cpython
X Title: Tracker: protect macros expansions using `do { ... } while (0)` constructions or via `static inline` equivalents when possible · Issue #124044 · python/cpython
Description: Fortifying Macros Expansion The Problem In C, using a macro allows to reduce code duplication. However, depending on the macro's body, the moment they are expanded by the C preprocessor, the obtained C code may not be syntactally correct...
Open Graph Description: Fortifying Macros Expansion The Problem In C, using a macro allows to reduce code duplication. However, depending on the macro's body, the moment they are expanded by the C preprocessor, the obtain...
X Description: Fortifying Macros Expansion The Problem In C, using a macro allows to reduce code duplication. However, depending on the macro's body, the moment they are expanded by the C preprocessor, the ob...
Opengraph URL: https://github.com/python/cpython/issues/124044
X: @github
Domain: github.com
IPv4 address: 140.82.113.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Tracker: protect macros expansions using `do { ... } while (0)` constructions or via `static inline` equivalents when possible","articleBody":"# Fortifying Macros Expansion\r\n\r\n## The Problem\r\n\r\nIn C, using a macro allows to reduce code duplication. However, depending on the macro's body, the moment they are expanded by the C preprocessor, the obtained C code may not be syntactally correct (or could have an unexpected execution flow).\r\n\r\nIn #123842, I saw that there are many files that have macros that could wrongly expand at compile time depending on how they are being used. Most of the time it's harmless but we never know how contributors use the macros themselves (they may not be aware of PEP-7 and could end up with dangling `else` in some cases). I will continue working on that draft PR but it's really hard to find a good regex for finding the macros to protect :') (well, I could do something with some analyzer but I'm too lazy).\r\n\r\nSince I'm tired of creating separate issues for each module and macro to protect, I will use this single issue to organize and track the progress.\r\n\r\n> [!IMPORTANT] \r\n> We only touch **source files** (`.c`). We do **NOT** change the macros in header files (`.h`). Those files can be included by anyone and the macros could be used by some downstream projects. Since we do not know how they actually use them, we don't want to break them (and there is no way we can notify them of the change except via commits). We will have dedicated issues to fix those macros as a wider discussion could be needed, but this specific issue only focuses on source files.\r\n\r\n## The Good News\r\n\r\nGood news is that we have not one but **two** approaches for fixing this. \r\n\r\n### Solution 1: converting the macro into a `static inline` function\r\n\r\nWhen possible, prefer converting macros into `static inline` functions. Similar work has been achieved in PEP-670 for the C API and the overhead is not that much. Smart compilers would anyway inline the function, making it (almost) assembly-equivalent to a macro.\r\n\r\nNot all macros can be converted into `static inline` functions. Macros that simply compute, say the addition of two `double` as `ADD_DOUBLE(x, y) (x) + (y)` should be rewritten as\r\n\r\n```C\r\nstatic inline double\r\nadd_double(double x, double y)\r\n{ \r\n return x + y;\r\n}\r\n```\r\n\r\nThere are various pitfalls when using macros (those pitfalls are explained in detail in PEP-670) so converting macros into `static inline` functions should be preferred. On the other hand, macros that have a `return` or a `goto` instruction cannot be easily converted into `static inline` functions. \r\n\r\n> [!IMPORTANT] \r\n> I'd advise to carefully read PEP-670 to see when to convert a macro into a `static inline` function.\r\n\r\n> [!NOTE]\r\n> When converting macros into `static inline` functions, the case of the name can be changed. Most macros have uppercase names, but functions are lowercased. I'd suggest having a different commit for the rename so that it could easily be reverted if needed.\r\n\r\n### Solution 2: using `do { ... } while (0)` constructions\r\n\r\nIn addition to the arguments exposed in https://www.quora.com/What-is-the-purpose-of-using-do-while-0-in-macros, the reason why we use `do { \u003cbody> } while (0)` is that the compiler is smart enough to optimize it as `{ \u003cbody> }` but after having expanded the macro (we can neither use `#define MACRO(...) if (1) { \u003cbody> }` nor `#define MACRO(...) { \u003cbody> }` because we could create dangling `else` if we were to use `MACRO();` instead of `MACRO()`). Now, I will lay down the convention I took for solving those issues.\r\n\r\nWhen possible, apply [PEP 7](https://peps.python.org/pep-0007/), namely, align line continuations and put `do` on a separate column. For instance, we change:\r\n\r\n```C\r\n#define MACRO(...) \\\r\n \u003cFIRST LINE> \\\r\n \u003cSECOND LINE> \\\r\n \u003cLAST LINE>\r\n// OR\r\n#define MACRO(...) { \\\r\n \u003cFIRST LINE> \\\r\n \u003cSECOND LINE> \\\r\n \u003cLAST LINE> \\\r\n}\r\n// OR\r\n#define MACRO(...) \\\r\n{ \\\r\n \u003cFIRST LINE> \\\r\n \u003cSECOND LINE> \\\r\n \u003cLAST LINE> \\\r\n}\r\n```\r\n\r\ninto\r\n\r\n```C\r\n#define MACRO(...) \\\r\n do { \\\r\n \u003cFIRST LINE> \\\r\n \u003cSECOND LINE> \\\r\n \u003cLAST LINE> \\\r\n } while (0)\r\n```\r\n\r\nBy convention, I put `do` on a separate line and indent it so that we don't have `} while (0)` stick to left margin. If other macros in the file are already using the `do { ... } while (0)` construction, either I keep the same style (which is probably preferred) or I change them if they are in minority (but using a separate commit so that I can easily revert it if a core-dev does not want this kind of cosmetic change).[^1]\r\n\r\n> [!TIP]\r\n> To align line continuations easily, take the longest line after adding the `do { ... } while (0)` construction and press TAB. Most of the time, this will align the `\\` on the next multiple of 4. Then either enter vertical mode to edit the line continuations or put tabs before every other `\\` until getting aligned line continuations.\r\n\r\nI personally avoid adding a semicolon after `while (0)`. One reason is that it convenes the intention for the usage to behave like a C statement. This is also in line with what PEP 7 suggests (but does not enforce). We could add it but then both `MACRO(...)` and `MACRO(...);` could be found in the code and I think it's better to have something uniform (ideally `MACRO(...);`).\r\n\r\n> [!NOTE]\r\n> The modules that will be touched may be very old and they could have their own coding style. I don't have a strong opinion on whether we should PEP-7-ize the macro body if the rest of the code is not PEP-7 compliant, but I think that aligning the line continuations should be preferred because it makes the macro easier to read.\r\n\r\n\u003c!---\r\n### The Even Better News \r\n\r\nAn even better news is that this task is a good introductory task for anyone interested in contributing to CPython (additional hands are always welcomed). Future contributors may inspect any commit in #123842 since each commit is dedicated to fix a single module (e.g., https://github.com/python/cpython/pull/123842/commits/5c90db8206a4dfeffdbdfdf5712df6d92995cad6) or a macro spread across multiple modules (e.g., https://github.com/python/cpython/pull/123842/commits/8fe006fc40e29a67e0ec9d2986612544185576e2). \r\n--->\r\n\r\n> [!IMPORTANT]\r\n> Avoid touching other places of the code. If we believe there is a bug in the macro, we open a separate issue. In addition, each fix should only focus on a **single** file (or a single macro that is duplicated across modules). Ideally, we should only make PRs one by one because this could create conflicts on other branches and our work usually has a lower priority. For that reason, we also don't backports the changes.\r\n\r\n[^1]: Consistency beats purity but sometimes consistency could be forced (if there are 50 macros for which we add `do { ... } while (0)` but there is only 1 macro that is putting the `do` at the same level as the `#define`, we simply change that single macro).\r\n\r\n\u003c!-- gh-linked-prs -->\r\n### Linked PRs\r\n* gh-124045\r\n\u003c!-- /gh-linked-prs -->\r\n","author":{"url":"https://github.com/picnixz","@type":"Person","name":"picnixz"},"datePublished":"2024-09-13T10:48:42Z","url":"https://github.com/python/cpython/issues/124044"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:b04751a1-35bf-9c10-d20c-e044b11e5751 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | DB44:17B76C:13CBB3E:1A2A1A6:6B066235 |
| html-safe-nonce | 5ea903268bd1271302cd6c336e255bfa8450ed18ffe7c331d97f89f7bd3911d1 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEQjQ0OjE3Qjc2QzoxM0NCQjNFOjFBMkExQTY6NkIwNjYyMzUiLCJ2aXNpdG9yX2lkIjoiNjQ5Nzg2MDU1NTEwNDQ3Nzc0OSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 2bd18137af42e290dc72247cc8f9b462d6a4a24b40fbdefb9aefbe1d2340b02b |
| hovercard-subject-tag | issue:2524530091 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/124044/issue_layout |
| twitter:image | https://opengraph.githubassets.com/85449e65491ca0715b18ba9fb1ebb7d7f74c3af48e207ff62bf37b660f761df2/python/cpython/issues/124044 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/85449e65491ca0715b18ba9fb1ebb7d7f74c3af48e207ff62bf37b660f761df2/python/cpython/issues/124044 |
| og:image:alt | Fortifying Macros Expansion The Problem In C, using a macro allows to reduce code duplication. However, depending on the macro's body, the moment they are expanded by the C preprocessor, the obtain... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | picnixz |
| hostname | github.com |
| expected-hostname | github.com |
| None | 6324e6ac990fb6befbec840cc0e102a1071c339bfe8f9826bb12de2e3ba1d297 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 7f0aa75f4141d440c6110dc31af7ea7797abb6c4 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width