Urgau
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # `--check-cfg` Stabilization Report :tada: ## Summary This adds a new top-level command line option `--check-cfg` (to `rustc` and `rustdoc`) in order to enable checking conditional compilation at compile time. `rustc` will check every `#[cfg(name = "value")]`, `#[cfg_attr(name = "value")]`, `#[link(name = "a", cfg(name = "value"))]` attributes and `cfg!(name = "value")` macro calls. `--cfg` arguments are _not_ checked[^arg]. [^arg]: For a big part of the existance of the feature, `--cfg` CLI args were also checked, but given that it interacted badly Cargo `RUSTFLAGS`, it was removed and left as an future posibility in the documentation. The syntax looks (roughly) like this: > `rustc --check-cfg 'cfg(name, values("value1", "value2", ... "valueN"))'` <details> From the [unstable book documentation](https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html#the-cfg-form): > To enable checking of values, but to provide an *none*/empty set of expected values (ie. expect `#[cfg(name)]`), use these forms: > > ```bash > rustc --check-cfg 'cfg(name)' > rustc --check-cfg 'cfg(name, values(none()))' > ``` > > To enable checking of name but not values, use one of these forms: > > - No expected values (_will lint on every value_): > ```bash > rustc --check-cfg 'cfg(name, values())' > ``` > > - Unknown expected values (_will never lint_): > ```bash > rustc --check-cfg 'cfg(name, values(any()))' > ``` > > To avoid repeating the same set of values, use this form: > > ```bash > rustc --check-cfg 'cfg(name1, ..., nameN, values("value1", "value2", ..., "valueN"))' > ``` > > The `--check-cfg cfg(...)` option can be repeated, both for the same condition name and for different names. If it is repeated for the same condition name, then the sets of values for that condition are merged together (precedence is given to `values(any())`). > Like with `values(any())`, well known names checking can be disabled by passing `cfg(any())` as argument to `--check-cfg`. </details> ### Example ```bash rustc --check-cfg 'cfg(is_embedded, has_feathers)' \ --check-cfg 'cfg(feature, values("zapping", "lasers"))' foo.rs ``` ```rust #[cfg(is_embedded)] // This condition is expected, as 'is_embedded' was provided in --check-cfg fn do_embedded() {} // and doesn't take any value #[cfg(has_feathers)] // This condition is expected, as 'has_feathers' was provided in --check-cfg fn do_features() {} // and doesn't take any value #[cfg(has_mumble_frotz)] // This condition is UNEXPECTED, as 'has_mumble_frotz' was NEVER provided // in any --check-cfg arguments fn do_mumble_frotz() {} #[cfg(feature = "lasers")] // This condition is expected, as "lasers" is an expected value of `feature` fn shoot_lasers() {} #[cfg(feature = "monkeys")] // This condition is UNEXPECTED, as "monkeys" is NOT an expected value of // `feature` fn write_shakespeare() {} ``` ```text warning: unexpected `cfg` condition name: `has_mumble_frotz` --> foo.rs:7:7 | 7 | #[cfg(has_mumble_frotz)] | ^^^^^^^^^^^^^^^^ | = help: expected names are: `debug_assertions`, `doc`, `doctest`, `feature`, `has_feathers`, `is_embedded`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(has_mumble_frotz)` = note: see <https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `monkeys` --> foo.rs:14:7 | 14 | #[cfg(feature = "monkeys")] | ^^^^^^^^^^^^^^^^^^^ | = note: expected values for `feature` are: `lasers`, `zapping` = help: to expect this configuration use `--check-cfg=cfg(feature, values("monkeys"))` = note: see <https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html> for more information about checking conditional configuration warning: 2 warnings emitted ``` ### Well known names and values From the [unstable book](https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html#well-known-names-and-values) section: > `rustc` has a internal list of well known names and their corresponding values. > Those well known names and values follows the same stability as what they refer to. <details> As of `2024-01-09T`, the list of known names is as follows: - `debug_assertions` - `doc` - `doctest` - `miri` - `overflow_checks` - `panic` - `proc_macro` - `relocation_model` - `sanitize` - `sanitizer_cfi_generalize_pointers` - `sanitizer_cfi_normalize_integers` - `target_abi` - `target_arch` - `target_endian` - `target_env` - `target_family` - `target_feature` - `target_has_atomic` - `target_has_atomic_equal_alignment` - `target_has_atomic_load_store` - `target_os` - `target_pointer_width` - `target_thread_local` - `target_vendor` - `test` - `unix` - `windows` </details> ## Cargo integration Since [~1.61 nightly Cargo](https://github.com/rust-lang/cargo/pull/10408) there has been some form of integration of `--check-cfg` in Cargo with the `-Zcheck-cfg`. The latest and current one is [`-Zcheck-cfg`](https://doc.rust-lang.org/cargo/reference/unstable.html#check-cfg) which: > Enables checking conditional compilation at compile time with `rustc` `--check-cfg`. It enables `feature`, well known names, well known values and [`cargo::rustc-check-cfg`](https://doc.rust-lang.org/cargo/reference/unstable.html#cargorustc-check-cfgcheck_cfg) (in build scripts). A stabilization report for Cargo will be done and would propose to make the behavior of `-Zcheck-cfg` the default. ## Documentation and Testing The feature is described in the [unstable book](https://doc.rust-lang.org/nightly/unstable-book/) under it's [own section](https://doc.rust-lang.org/nightly/unstable-book/compiler-flags/check-cfg.html). The feature is being _extensively tested_ under [`tests/ui/check-cfg`](https://github.com/rust-lang/rust/tree/92d727796be7c882d2efbc06e08bbf4743cf29dc/tests/ui/check-cfg) _(27 test files)_. To give a some highlights: - [tests/ui/check-cfg/cargo-feature.rs](https://github.com/rust-lang/rust/blob/92d727796be7c882d2efbc06e08bbf4743cf29dc/tests/ui/check-cfg/cargo-feature.rs) simulate the behavior of Cargo `-Zcheck-cfg` - [tests/ui/check-cfg/invalid-arguments.rs](https://github.com/rust-lang/rust/blob/92d727796be7c882d2efbc06e08bbf4743cf29dc/tests/ui/check-cfg/invalid-arguments.rs) test that we rejects every invalid syntax - [tests/ui/check-cfg/well-known-values.rs](https://github.com/rust-lang/rust/blob/92d727796be7c882d2efbc06e08bbf4743cf29dc/tests/ui/check-cfg/well-known-values.rs) anti-regression test for well known name and values - [tests/ui/check-cfg/unexpected-cfg-{name,value}.rs](https://github.com/rust-lang/rust/blob/92d727796be7c882d2efbc06e08bbf4743cf29dc/tests/ui/check-cfg/unexpected-cfg-name.rs) check for basic mistakes (like `widnows` instead of `windows`) - [tests/ui/check-cfg/allow-{at-crate-level,macro-cfg,same-level,top-level,upper-level}.rs](https://github.com/rust-lang/rust/blob/92d727796be7c882d2efbc06e08bbf4743cf29dc/tests/ui/check-cfg/allow-at-crate-level.rs) testing that allowing the lint `unexpected_cfgs` works in different situations ## Real World Usage - [rust-lang/rust bootstrap](https://github.com/rust-lang/rust/blob/159bdc1e9313d63ed97ae79fd7c6037393f3ab88/src/bootstrap/src/lib.rs#L75-L93) - [Cargo `-Zcheck-cfg`](https://doc.rust-lang.org/cargo/reference/unstable.html#check-cfg) - [`portable-atomic`: `build.sh`](https://github.com/taiki-e/portable-atomic/blob/5ea2db6ad3e4132cdd6a1c992313410511ababab/tools/build.sh#L239-L252) - [Rust for Linux](https://github.com/rust-lang/rust/issues/82450#issuecomment-1947462977)[^rfl] [^rfl]: from the Call for testing ## Unresolved questions - From the [tracking issue](https://github.com/rust-lang/rust/issues/82450#issue-814708119): Which configs should be in the well known list? Currently the informal logic that has been followed is to include all the configs that are: 1. User facing _(nightly or not)_ (rational: internal cfgs are by their name not to be shown) 2. Set by a Rust Toolchain tool (rational: `rustc` is not the only tool that sets cfgs, `rustdoc` sets `doc` and `doctest`, `cargo-miri` sets `miri`, docs.rs sets `docsrs`, ...) 3. Must be an immutable set of names and values (rational: if it's not immutable, `rustc` cannot possibly know the what to add; this excludes Cargo `feature` cfg) I propose that we continue to follow this rule. -------- # `-Zcheck-cfg` Stabilization Report :tada: ## Summary This enables checking conditional compilation at compile time by passing a new command line option `--check-cfg` to all `rustc` and `rustdoc` invocations. In particular this enables checking Cargo features and custom configs with `cargo::rustc-check-cfg` (in build scripts). <small>_Since [rust#117522](https://github.com/rust-lang/rust/pull/117522) setting custom `--cfg` on `RUSTFLAGS` no longer has an impact on any crates, only uses of them in the code triggers the warnings._</small> ### Example ```bash cargo check ``` ```toml [package] name = "y" version = "0.1.0" edition = "2021" [features] lasers = [] zapping = [] ``` ```rust #[cfg(feature = "lasers")] // This condition is expected, as "lasers" is an expected value of `feature` fn shoot_lasers() {} #[cfg(feature = "monkeys")] // This condition is UNEXPECTED, as "monkeys" is NOT an expected value of // `feature` fn write_shakespeare() {} #[cfg(windosw)] // This condition is UNEXPECTED, it's supposed to be `windows` fn win() {} ``` ```text warning: unexpected `cfg` condition value: `monkeys` --> src/lib.rs:4:7 | 4 | #[cfg(feature = "monkeys")] // This condition is UNEXPECTED, as "monkeys" is NOT an expected valu... | ^^^^^^^^^^^^^^^^^^^ | = note: expected values for `feature` are: `lasers`, `zapping` = help: consider adding `monkeys` as a feature in `Cargo.toml` = note: see <https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition name: `windosw` --> src/lib.rs:8:7 | 8 | #[cfg(windosw)] // This condition is UNEXPECTED, it's supposed to be `windows` | ^^^^^^^ help: there is a config with a similar name: `windows` | = help: consider using a Cargo feature instead or adding `println!("cargo:rustc-check-cfg=cfg(windosw)");` to the top of a `build.rs` = note: see <https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg> for more information about checking conditional configuration warning: `foo` (lib) generated 2 warnings ``` ## Enable-by-default Per the tracking issue, there is one last but important question to address: > Should these flags be enabled by default? What's the unintrusive interface to provide for users to opt-out the checking? I propose that the behavior be enabled by default without a way to opt out, otherwise users will probably not see their mistakes in time or not know about the flag at all. ## Impact A crater run was done in rust#120701, the full summary can be found there. The sort version is: > After manually checking 3 categories (most unexpected features, `target_*`, and general) I wasn't able to find any false positive[^false_positives]; in total 9649 actions would need to be taken across 5959 projects (1.4% of all the projects tested), by either: fixing the typo, removing the staled condition, marking as expected the custom cfg, adding the feature to the `features` table... > > [^false_positives]: by "false positive" I mean: missing well known names/values A [Call for testing](https://github.com/rust-lang/rfcs/pull/3013#issuecomment-1936648479) was also performed and the responses were generaly positive, there were questions about the default set well know names/values and some anti pattern `#[path]` file sharing, but those are ortogonal to this stabilization. ### Mitigations options However to mitigate it's impact we probably want to annonce the feature ahead of time and provide ahead of time a "migration guide" for users of custom configs. #### None We can consider that the impact is minimal enough and that positives of the feature are strong enough to not do anything more. #### Edition bound We have a edition (2024) that is approaching, we could bound the feature to being enabled on being enabled only for edition>=2024. ##### on Cargo side We would only pass `--check-cfg` on newer editions. ##### on rustc side We (Cargo) would always pass `--check-cfg` but the lint would be allow by default for edition<2024 and warn-by-default for edition>=2024. ## Documentation and Testing The feature is currently documented in the [check-cfg](https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg) section of the Cargo unstable features chapter. Stabilizing the feature would mainly involve documentating `cargo::rustc-check-cfg` as stable and providing users with a "migration page". The feature is being _extensively tested_ under [`tests/testsuite/check_cfg.rs`](https://github.com/rust-lang/cargo/blob/7bb7b539558dc88bea44cee4168b6269bf8177b0/tests/testsuite/check_cfg.rs) _(~20 tests)_. To give a some highlights: - [`features_with_namespaced_features`](https://github.com/rust-lang/cargo/blob/7bb7b539558dc88bea44cee4168b6269bf8177b0/tests/testsuite/check_cfg.rs#L116): test the feature with optional deps, explicit feature and path dependencies - [`well_known_names_values`](https://github.com/rust-lang/cargo/blob/7bb7b539558dc88bea44cee4168b6269bf8177b0/tests/testsuite/check_cfg.rs#L216): test that even without any Cargo features Cargo still emits the appropriate `--check-cfg` args - [`well_known_names_values_doctest`](https://github.com/rust-lang/cargo/blob/7bb7b539558dc88bea44cee4168b6269bf8177b0/tests/testsuite/check_cfg.rs#L292): test the integration with `rustdoc` - [`build_script`](https://github.com/rust-lang/cargo/blob/7bb7b539558dc88bea44cee4168b6269bf8177b0/tests/testsuite/check_cfg.rs#L331): test `cargo::rustc-check-cfg` in build script - [`features_fingerprinting`](https://github.com/rust-lang/cargo/blob/7bb7b539558dc88bea44cee4168b6269bf8177b0/tests/testsuite/check_cfg.rs#L145): simple test that makes sure that Cargo rerun rustc if the delcared features changes ## Real World Usage - [rust-lang/rust bootstrap](https://github.com/rust-lang/rust/blob/159bdc1e9313d63ed97ae79fd7c6037393f3ab88/src/bootstrap/src/lib.rs#L75-L93) - [`portable-atomic`: `build.sh`](https://github.com/taiki-e/portable-atomic/blob/5ea2db6ad3e4132cdd6a1c992313410511ababab/tools/build.sh#L239-L252) ## Unresolved questions - How to deal with the impact of enabling the feature? See above for run down of the options. - Should the build script directive warning be appeased ahead of the stabilization ?

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully