René's URL Explorer Experiment


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

direct link

Domain: github.com

IPv4 address: 140.82.113.3


Hey, it has json ld scripts:
{"@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-profiling0
react-import-mapreact,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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:b04751a1-35bf-9c10-d20c-e044b11e5751
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idDB44:17B76C:13CBB3E:1A2A1A6:6B066235
html-safe-nonce5ea903268bd1271302cd6c336e255bfa8450ed18ffe7c331d97f89f7bd3911d1
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEQjQ0OjE3Qjc2QzoxM0NCQjNFOjFBMkExQTY6NkIwNjYyMzUiLCJ2aXNpdG9yX2lkIjoiNjQ5Nzg2MDU1NTEwNDQ3Nzc0OSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac2bd18137af42e290dc72247cc8f9b462d6a4a24b40fbdefb9aefbe1d2340b02b
hovercard-subject-tagissue:2524530091
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/124044/issue_layout
twitter:imagehttps://opengraph.githubassets.com/85449e65491ca0715b18ba9fb1ebb7d7f74c3af48e207ff62bf37b660f761df2/python/cpython/issues/124044
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/85449e65491ca0715b18ba9fb1ebb7d7f74c3af48e207ff62bf37b660f761df2/python/cpython/issues/124044
og:image:altFortifying 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:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamepicnixz
hostnamegithub.com
expected-hostnamegithub.com
None6324e6ac990fb6befbec840cc0e102a1071c339bfe8f9826bb12de2e3ba1d297
turbo-cache-controlno-preview
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release7f0aa75f4141d440c6110dc31af7ea7797abb6c4
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/cpython/issues/124044#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F124044
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F124044
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/issues/124044
Reloadhttps://github.com/python/cpython/issues/124044
Reloadhttps://github.com/python/cpython/issues/124044
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
https://github.com/python/cpython
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/124044
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/124044
Tracker: protect macros expansions using do { ... } while (0) constructions or via static inline equivalents when possiblehttps://github.com/python/cpython/issues/124044#top
https://github.com/picnixz
extension-moduleshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22extension-modules%22
interpreter-corehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
type-featurehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-feature%22
https://github.com/picnixz
picnixzhttps://github.com/picnixz
on Sep 13, 2024https://github.com/python/cpython/issues/124044#issue-2524530091
#123842https://github.com/python/cpython/pull/123842
PEP-7https://peps.python.org/7
PEP-670https://peps.python.org/670
PEP-670https://peps.python.org/670
PEP-670https://peps.python.org/670
https://www.quora.com/What-is-the-purpose-of-using-do-while-0-in-macroshttps://www.quora.com/What-is-the-purpose-of-using-do-while-0-in-macros
PEP 7https://peps.python.org/pep-0007/
1https://github.com/python/cpython/issues/124044#user-content-fn-1-c50d509d2cee2e9d11ffa559bcfab341
PEP-7https://peps.python.org/7
PEP-7https://peps.python.org/7
gh-124044: protect macros expansions in _cursesmodule.c using do { ... } while (0) constructions #124045https://github.com/python/cpython/pull/124045
↩https://github.com/python/cpython/issues/124044#user-content-fnref-1-c50d509d2cee2e9d11ffa559bcfab341
picnixzhttps://github.com/picnixz
type-featurehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-feature%22
interpreter-corehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
extension-moduleshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22extension-modules%22
easyhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22easy%22
on Sep 13, 2024https://github.com/python/cpython/issues/124044#event-14247044244
picnixzhttps://github.com/picnixz
on Sep 13, 2024https://github.com/python/cpython/issues/124044#event-14247045079
vstinnerhttps://github.com/vstinner
on Sep 13, 2024https://github.com/python/cpython/issues/124044#event-14247455281
gh-124044: protect macros expansions in `_cursesmodules.c` using `do …https://github.com/python/cpython/commit/e49d1b44d3ef2542c0ae165e14a7e5ffbc32b2d1
gh-124044https://github.com/python/cpython/issues/124044
e49d1b4https://github.com/python/cpython/commit/e49d1b44d3ef2542c0ae165e14a7e5ffbc32b2d1
https://github.com/ZeroIntensity
ZeroIntensityhttps://github.com/ZeroIntensity
on Sep 13, 2024https://github.com/python/cpython/issues/124044#issuecomment-2349384763
https://github.com/picnixz
picnixzhttps://github.com/picnixz
on Sep 13, 2024https://github.com/python/cpython/issues/124044#issuecomment-2349477378
https://github.com/vstinner
vstinnerhttps://github.com/vstinner
on Sep 13, 2024https://github.com/python/cpython/issues/124044#issuecomment-2350134235
@erlend-aaslandhttps://github.com/erlend-aasland
PEP 670https://peps.python.org/pep-0670/
PEP 674https://peps.python.org/pep-0674/
https://github.com/vstinner
vstinnerhttps://github.com/vstinner
on Sep 13, 2024https://github.com/python/cpython/issues/124044#issuecomment-2350136270
https://github.com/picnixz
picnixzhttps://github.com/picnixz
on Sep 13, 2024https://github.com/python/cpython/issues/124044#issuecomment-2350696996
picnixzhttps://github.com/picnixz
on Sep 13, 2024https://github.com/python/cpython/issues/124044#event-14255418197
https://github.com/vstinner
vstinnerhttps://github.com/vstinner
on Sep 14, 2024https://github.com/python/cpython/issues/124044#issuecomment-2350902042
picnixzhttps://github.com/picnixz
on Sep 14, 2024https://github.com/python/cpython/issues/124044#event-14257943379
https://github.com/picnixz
picnixzhttps://github.com/picnixz
on Sep 14, 2024https://github.com/python/cpython/issues/124044#issuecomment-2350921643
picnixzhttps://github.com/picnixz
easyhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22easy%22
on Sep 14, 2024https://github.com/python/cpython/issues/124044#event-14258143385
https://github.com/picnixz
picnixzhttps://github.com/picnixz
on Mar 16, 2025https://github.com/python/cpython/issues/124044#issuecomment-2727564730
picnixzhttps://github.com/picnixz
completedhttps://github.com/python/cpython/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on Mar 16, 2025https://github.com/python/cpython/issues/124044#event-16791682447
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/124044
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/124044
picnixzhttps://github.com/picnixz
extension-moduleshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22extension-modules%22
interpreter-corehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
type-featurehttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-feature%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Response headers:
Servergithub.com
Content-Typetext/html; charset=utf-8
Cache-Controlmax-age=0, private, must-revalidate

Viewport: width=device-width


URLs of crawlers that visited me.