Search code examples
rustcompiler-construction

How cfg are dealt with in rustc?


This is a further question on How to extract nightly features used in a crate?.

I also want to know where and how #![cfg_attr(target_os = "macos", feature(...))] is turned into #![feature(...).

Could someone give me some tips about the process of rustc dealing with cfg.


Solution

  • The rustc_expand crate is responsible for expanding macros. It special cases #[cfg] and #[cfg_attr] when parsing attribute macros such that they aren't treated like normal macros.

    • rustc_expand calls rustc_parse::parse_cfg_attr to parse the attribute.
    • With the parsed macro, rustc_expand calls rustc_attr::cfg_matches to evaluate if the condition is met.
    • rustc_expand then either includes or doesn't include the attribute passed as an argument.