rustdoc/clean/
cfg.rs

1//! The representation of a `#[doc(cfg(...))]` attribute.
2
3// FIXME: Once the portability lint RFC is implemented (see tracking issue #41619),
4// switch to use those structures instead.
5
6use std::fmt::{self, Write};
7use std::{mem, ops};
8
9use rustc_ast::{LitKind, MetaItem, MetaItemInner, MetaItemKind, MetaItemLit};
10use rustc_data_structures::fx::FxHashSet;
11use rustc_session::parse::ParseSess;
12use rustc_span::Span;
13use rustc_span::symbol::{Symbol, sym};
14
15use crate::display::Joined as _;
16use crate::html::escape::Escape;
17
18#[cfg(test)]
19mod tests;
20
21#[derive(Clone, Debug, PartialEq, Eq, Hash)]
22pub(crate) enum Cfg {
23    /// Accepts all configurations.
24    True,
25    /// Denies all configurations.
26    False,
27    /// A generic configuration option, e.g., `test` or `target_os = "linux"`.
28    Cfg(Symbol, Option<Symbol>),
29    /// Negates a configuration requirement, i.e., `not(x)`.
30    Not(Box<Cfg>),
31    /// Union of a list of configuration requirements, i.e., `any(...)`.
32    Any(Vec<Cfg>),
33    /// Intersection of a list of configuration requirements, i.e., `all(...)`.
34    All(Vec<Cfg>),
35}
36
37#[derive(PartialEq, Debug)]
38pub(crate) struct InvalidCfgError {
39    pub(crate) msg: &'static str,
40    pub(crate) span: Span,
41}
42
43impl Cfg {
44    /// Parses a `MetaItemInner` into a `Cfg`.
45    fn parse_nested(
46        nested_cfg: &MetaItemInner,
47        exclude: &FxHashSet<Cfg>,
48    ) -> Result<Option<Cfg>, InvalidCfgError> {
49        match nested_cfg {
50            MetaItemInner::MetaItem(cfg) => Cfg::parse_without(cfg, exclude),
51            MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(b), .. }) => match *b {
52                true => Ok(Some(Cfg::True)),
53                false => Ok(Some(Cfg::False)),
54            },
55            MetaItemInner::Lit(lit) => {
56                Err(InvalidCfgError { msg: "unexpected literal", span: lit.span })
57            }
58        }
59    }
60
61    pub(crate) fn parse_without(
62        cfg: &MetaItem,
63        exclude: &FxHashSet<Cfg>,
64    ) -> Result<Option<Cfg>, InvalidCfgError> {
65        let name = match cfg.ident() {
66            Some(ident) => ident.name,
67            None => {
68                return Err(InvalidCfgError {
69                    msg: "expected a single identifier",
70                    span: cfg.span,
71                });
72            }
73        };
74        match cfg.kind {
75            MetaItemKind::Word => {
76                let cfg = Cfg::Cfg(name, None);
77                if exclude.contains(&cfg) { Ok(None) } else { Ok(Some(cfg)) }
78            }
79            MetaItemKind::NameValue(ref lit) => match lit.kind {
80                LitKind::Str(value, _) => {
81                    let cfg = Cfg::Cfg(name, Some(value));
82                    if exclude.contains(&cfg) { Ok(None) } else { Ok(Some(cfg)) }
83                }
84                _ => Err(InvalidCfgError {
85                    // FIXME: if the main #[cfg] syntax decided to support non-string literals,
86                    // this should be changed as well.
87                    msg: "value of cfg option should be a string literal",
88                    span: lit.span,
89                }),
90            },
91            MetaItemKind::List(ref items) => {
92                let orig_len = items.len();
93                let mut sub_cfgs =
94                    items.iter().filter_map(|i| Cfg::parse_nested(i, exclude).transpose());
95                let ret = match name {
96                    sym::all => sub_cfgs.try_fold(Cfg::True, |x, y| Ok(x & y?)),
97                    sym::any => sub_cfgs.try_fold(Cfg::False, |x, y| Ok(x | y?)),
98                    sym::not => {
99                        if orig_len == 1 {
100                            let mut sub_cfgs = sub_cfgs.collect::<Vec<_>>();
101                            if sub_cfgs.len() == 1 {
102                                Ok(!sub_cfgs.pop().unwrap()?)
103                            } else {
104                                return Ok(None);
105                            }
106                        } else {
107                            Err(InvalidCfgError { msg: "expected 1 cfg-pattern", span: cfg.span })
108                        }
109                    }
110                    _ => Err(InvalidCfgError { msg: "invalid predicate", span: cfg.span }),
111                };
112                match ret {
113                    Ok(c) => Ok(Some(c)),
114                    Err(e) => Err(e),
115                }
116            }
117        }
118    }
119
120    /// Parses a `MetaItem` into a `Cfg`.
121    ///
122    /// The `MetaItem` should be the content of the `#[cfg(...)]`, e.g., `unix` or
123    /// `target_os = "redox"`.
124    ///
125    /// If the content is not properly formatted, it will return an error indicating what and where
126    /// the error is.
127    pub(crate) fn parse(cfg: &MetaItemInner) -> Result<Cfg, InvalidCfgError> {
128        Self::parse_nested(cfg, &FxHashSet::default()).map(|ret| ret.unwrap())
129    }
130
131    /// Checks whether the given configuration can be matched in the current session.
132    ///
133    /// Equivalent to `attr::cfg_matches`.
134    pub(crate) fn matches(&self, psess: &ParseSess) -> bool {
135        match *self {
136            Cfg::False => false,
137            Cfg::True => true,
138            Cfg::Not(ref child) => !child.matches(psess),
139            Cfg::All(ref sub_cfgs) => sub_cfgs.iter().all(|sub_cfg| sub_cfg.matches(psess)),
140            Cfg::Any(ref sub_cfgs) => sub_cfgs.iter().any(|sub_cfg| sub_cfg.matches(psess)),
141            Cfg::Cfg(name, value) => psess.config.contains(&(name, value)),
142        }
143    }
144
145    /// Whether the configuration consists of just `Cfg` or `Not`.
146    fn is_simple(&self) -> bool {
147        match *self {
148            Cfg::False | Cfg::True | Cfg::Cfg(..) | Cfg::Not(..) => true,
149            Cfg::All(..) | Cfg::Any(..) => false,
150        }
151    }
152
153    /// Whether the configuration consists of just `Cfg`, `Not` or `All`.
154    fn is_all(&self) -> bool {
155        match *self {
156            Cfg::False | Cfg::True | Cfg::Cfg(..) | Cfg::Not(..) | Cfg::All(..) => true,
157            Cfg::Any(..) => false,
158        }
159    }
160
161    /// Renders the configuration for human display, as a short HTML description.
162    pub(crate) fn render_short_html(&self) -> String {
163        let mut msg = Display(self, Format::ShortHtml).to_string();
164        if self.should_capitalize_first_letter()
165            && let Some(i) = msg.find(|c: char| c.is_ascii_alphanumeric())
166        {
167            msg[i..i + 1].make_ascii_uppercase();
168        }
169        msg
170    }
171
172    /// Renders the configuration for long display, as a long HTML description.
173    pub(crate) fn render_long_html(&self) -> String {
174        let on = if self.should_use_with_in_description() { "with" } else { "on" };
175
176        let mut msg =
177            format!("Available {on} <strong>{}</strong>", Display(self, Format::LongHtml));
178        if self.should_append_only_to_description() {
179            msg.push_str(" only");
180        }
181        msg.push('.');
182        msg
183    }
184
185    /// Renders the configuration for long display, as a long plain text description.
186    pub(crate) fn render_long_plain(&self) -> String {
187        let on = if self.should_use_with_in_description() { "with" } else { "on" };
188
189        let mut msg = format!("Available {on} {}", Display(self, Format::LongPlain));
190        if self.should_append_only_to_description() {
191            msg.push_str(" only");
192        }
193        msg
194    }
195
196    fn should_capitalize_first_letter(&self) -> bool {
197        match *self {
198            Cfg::False | Cfg::True | Cfg::Not(..) => true,
199            Cfg::Any(ref sub_cfgs) | Cfg::All(ref sub_cfgs) => {
200                sub_cfgs.first().map(Cfg::should_capitalize_first_letter).unwrap_or(false)
201            }
202            Cfg::Cfg(name, _) => name == sym::debug_assertions || name == sym::target_endian,
203        }
204    }
205
206    fn should_append_only_to_description(&self) -> bool {
207        match *self {
208            Cfg::False | Cfg::True => false,
209            Cfg::Any(..) | Cfg::All(..) | Cfg::Cfg(..) => true,
210            Cfg::Not(box Cfg::Cfg(..)) => true,
211            Cfg::Not(..) => false,
212        }
213    }
214
215    fn should_use_with_in_description(&self) -> bool {
216        matches!(self, Cfg::Cfg(sym::target_feature, _))
217    }
218
219    /// Attempt to simplify this cfg by assuming that `assume` is already known to be true, will
220    /// return `None` if simplification managed to completely eliminate any requirements from this
221    /// `Cfg`.
222    ///
223    /// See `tests::test_simplify_with` for examples.
224    pub(crate) fn simplify_with(&self, assume: &Self) -> Option<Self> {
225        if self == assume {
226            None
227        } else if let Cfg::All(a) = self {
228            let mut sub_cfgs: Vec<Cfg> = if let Cfg::All(b) = assume {
229                a.iter().filter(|a| !b.contains(a)).cloned().collect()
230            } else {
231                a.iter().filter(|&a| a != assume).cloned().collect()
232            };
233            let len = sub_cfgs.len();
234            match len {
235                0 => None,
236                1 => sub_cfgs.pop(),
237                _ => Some(Cfg::All(sub_cfgs)),
238            }
239        } else if let Cfg::All(b) = assume
240            && b.contains(self)
241        {
242            None
243        } else {
244            Some(self.clone())
245        }
246    }
247}
248
249impl ops::Not for Cfg {
250    type Output = Cfg;
251    fn not(self) -> Cfg {
252        match self {
253            Cfg::False => Cfg::True,
254            Cfg::True => Cfg::False,
255            Cfg::Not(cfg) => *cfg,
256            s => Cfg::Not(Box::new(s)),
257        }
258    }
259}
260
261impl ops::BitAndAssign for Cfg {
262    fn bitand_assign(&mut self, other: Cfg) {
263        match (self, other) {
264            (&mut Cfg::False, _) | (_, Cfg::True) => {}
265            (s, Cfg::False) => *s = Cfg::False,
266            (s @ &mut Cfg::True, b) => *s = b,
267            (&mut Cfg::All(ref mut a), Cfg::All(ref mut b)) => {
268                for c in b.drain(..) {
269                    if !a.contains(&c) {
270                        a.push(c);
271                    }
272                }
273            }
274            (&mut Cfg::All(ref mut a), ref mut b) => {
275                if !a.contains(b) {
276                    a.push(mem::replace(b, Cfg::True));
277                }
278            }
279            (s, Cfg::All(mut a)) => {
280                let b = mem::replace(s, Cfg::True);
281                if !a.contains(&b) {
282                    a.push(b);
283                }
284                *s = Cfg::All(a);
285            }
286            (s, b) => {
287                if *s != b {
288                    let a = mem::replace(s, Cfg::True);
289                    *s = Cfg::All(vec![a, b]);
290                }
291            }
292        }
293    }
294}
295
296impl ops::BitAnd for Cfg {
297    type Output = Cfg;
298    fn bitand(mut self, other: Cfg) -> Cfg {
299        self &= other;
300        self
301    }
302}
303
304impl ops::BitOrAssign for Cfg {
305    fn bitor_assign(&mut self, other: Cfg) {
306        match (self, other) {
307            (Cfg::True, _) | (_, Cfg::False) | (_, Cfg::True) => {}
308            (s @ &mut Cfg::False, b) => *s = b,
309            (&mut Cfg::Any(ref mut a), Cfg::Any(ref mut b)) => {
310                for c in b.drain(..) {
311                    if !a.contains(&c) {
312                        a.push(c);
313                    }
314                }
315            }
316            (&mut Cfg::Any(ref mut a), ref mut b) => {
317                if !a.contains(b) {
318                    a.push(mem::replace(b, Cfg::True));
319                }
320            }
321            (s, Cfg::Any(mut a)) => {
322                let b = mem::replace(s, Cfg::True);
323                if !a.contains(&b) {
324                    a.push(b);
325                }
326                *s = Cfg::Any(a);
327            }
328            (s, b) => {
329                if *s != b {
330                    let a = mem::replace(s, Cfg::True);
331                    *s = Cfg::Any(vec![a, b]);
332                }
333            }
334        }
335    }
336}
337
338impl ops::BitOr for Cfg {
339    type Output = Cfg;
340    fn bitor(mut self, other: Cfg) -> Cfg {
341        self |= other;
342        self
343    }
344}
345
346#[derive(Clone, Copy)]
347enum Format {
348    LongHtml,
349    LongPlain,
350    ShortHtml,
351}
352
353impl Format {
354    fn is_long(self) -> bool {
355        match self {
356            Format::LongHtml | Format::LongPlain => true,
357            Format::ShortHtml => false,
358        }
359    }
360
361    fn is_html(self) -> bool {
362        match self {
363            Format::LongHtml | Format::ShortHtml => true,
364            Format::LongPlain => false,
365        }
366    }
367}
368
369/// Pretty-print wrapper for a `Cfg`. Also indicates what form of rendering should be used.
370struct Display<'a>(&'a Cfg, Format);
371
372fn write_with_opt_paren<T: fmt::Display>(
373    fmt: &mut fmt::Formatter<'_>,
374    has_paren: bool,
375    obj: T,
376) -> fmt::Result {
377    if has_paren {
378        fmt.write_char('(')?;
379    }
380    obj.fmt(fmt)?;
381    if has_paren {
382        fmt.write_char(')')?;
383    }
384    Ok(())
385}
386
387impl Display<'_> {
388    fn display_sub_cfgs(
389        &self,
390        fmt: &mut fmt::Formatter<'_>,
391        sub_cfgs: &[Cfg],
392        separator: &str,
393    ) -> fmt::Result {
394        use fmt::Display as _;
395
396        let short_longhand = self.1.is_long() && {
397            let all_crate_features =
398                sub_cfgs.iter().all(|sub_cfg| matches!(sub_cfg, Cfg::Cfg(sym::feature, Some(_))));
399            let all_target_features = sub_cfgs
400                .iter()
401                .all(|sub_cfg| matches!(sub_cfg, Cfg::Cfg(sym::target_feature, Some(_))));
402
403            if all_crate_features {
404                fmt.write_str("crate features ")?;
405                true
406            } else if all_target_features {
407                fmt.write_str("target features ")?;
408                true
409            } else {
410                false
411            }
412        };
413
414        fmt::from_fn(|f| {
415            sub_cfgs
416                .iter()
417                .map(|sub_cfg| {
418                    fmt::from_fn(move |fmt| {
419                        if let Cfg::Cfg(_, Some(feat)) = sub_cfg
420                            && short_longhand
421                        {
422                            if self.1.is_html() {
423                                write!(fmt, "<code>{feat}</code>")?;
424                            } else {
425                                write!(fmt, "`{feat}`")?;
426                            }
427                        } else {
428                            write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))?;
429                        }
430                        Ok(())
431                    })
432                })
433                .joined(separator, f)
434        })
435        .fmt(fmt)?;
436
437        Ok(())
438    }
439}
440
441impl fmt::Display for Display<'_> {
442    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
443        match *self.0 {
444            Cfg::Not(ref child) => match **child {
445                Cfg::Any(ref sub_cfgs) => {
446                    let separator =
447                        if sub_cfgs.iter().all(Cfg::is_simple) { " nor " } else { ", nor " };
448                    fmt.write_str("neither ")?;
449
450                    sub_cfgs
451                        .iter()
452                        .map(|sub_cfg| {
453                            fmt::from_fn(|fmt| {
454                                write_with_opt_paren(
455                                    fmt,
456                                    !sub_cfg.is_all(),
457                                    Display(sub_cfg, self.1),
458                                )
459                            })
460                        })
461                        .joined(separator, fmt)
462                }
463                ref simple @ Cfg::Cfg(..) => write!(fmt, "non-{}", Display(simple, self.1)),
464                ref c => write!(fmt, "not ({})", Display(c, self.1)),
465            },
466
467            Cfg::Any(ref sub_cfgs) => {
468                let separator = if sub_cfgs.iter().all(Cfg::is_simple) { " or " } else { ", or " };
469                self.display_sub_cfgs(fmt, sub_cfgs, separator)
470            }
471            Cfg::All(ref sub_cfgs) => self.display_sub_cfgs(fmt, sub_cfgs, " and "),
472
473            Cfg::True => fmt.write_str("everywhere"),
474            Cfg::False => fmt.write_str("nowhere"),
475
476            Cfg::Cfg(name, value) => {
477                let human_readable = match (name, value) {
478                    (sym::unix, None) => "Unix",
479                    (sym::windows, None) => "Windows",
480                    (sym::debug_assertions, None) => "debug-assertions enabled",
481                    (sym::target_os, Some(os)) => match os.as_str() {
482                        "android" => "Android",
483                        "dragonfly" => "DragonFly BSD",
484                        "emscripten" => "Emscripten",
485                        "freebsd" => "FreeBSD",
486                        "fuchsia" => "Fuchsia",
487                        "haiku" => "Haiku",
488                        "hermit" => "HermitCore",
489                        "illumos" => "illumos",
490                        "ios" => "iOS",
491                        "l4re" => "L4Re",
492                        "linux" => "Linux",
493                        "macos" => "macOS",
494                        "netbsd" => "NetBSD",
495                        "openbsd" => "OpenBSD",
496                        "redox" => "Redox",
497                        "solaris" => "Solaris",
498                        "tvos" => "tvOS",
499                        "wasi" => "WASI",
500                        "watchos" => "watchOS",
501                        "windows" => "Windows",
502                        "visionos" => "visionOS",
503                        _ => "",
504                    },
505                    (sym::target_arch, Some(arch)) => match arch.as_str() {
506                        "aarch64" => "AArch64",
507                        "arm" => "ARM",
508                        "loongarch64" => "LoongArch LA64",
509                        "m68k" => "M68k",
510                        "csky" => "CSKY",
511                        "mips" => "MIPS",
512                        "mips32r6" => "MIPS Release 6",
513                        "mips64" => "MIPS-64",
514                        "mips64r6" => "MIPS-64 Release 6",
515                        "msp430" => "MSP430",
516                        "powerpc" => "PowerPC",
517                        "powerpc64" => "PowerPC-64",
518                        "riscv32" => "RISC-V RV32",
519                        "riscv64" => "RISC-V RV64",
520                        "s390x" => "s390x",
521                        "sparc64" => "SPARC64",
522                        "wasm32" | "wasm64" => "WebAssembly",
523                        "x86" => "x86",
524                        "x86_64" => "x86-64",
525                        _ => "",
526                    },
527                    (sym::target_vendor, Some(vendor)) => match vendor.as_str() {
528                        "apple" => "Apple",
529                        "pc" => "PC",
530                        "sun" => "Sun",
531                        "fortanix" => "Fortanix",
532                        _ => "",
533                    },
534                    (sym::target_env, Some(env)) => match env.as_str() {
535                        "gnu" => "GNU",
536                        "msvc" => "MSVC",
537                        "musl" => "musl",
538                        "newlib" => "Newlib",
539                        "uclibc" => "uClibc",
540                        "sgx" => "SGX",
541                        _ => "",
542                    },
543                    (sym::target_endian, Some(endian)) => return write!(fmt, "{endian}-endian"),
544                    (sym::target_pointer_width, Some(bits)) => return write!(fmt, "{bits}-bit"),
545                    (sym::target_feature, Some(feat)) => match self.1 {
546                        Format::LongHtml => {
547                            return write!(fmt, "target feature <code>{feat}</code>");
548                        }
549                        Format::LongPlain => return write!(fmt, "target feature `{feat}`"),
550                        Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
551                    },
552                    (sym::feature, Some(feat)) => match self.1 {
553                        Format::LongHtml => {
554                            return write!(fmt, "crate feature <code>{feat}</code>");
555                        }
556                        Format::LongPlain => return write!(fmt, "crate feature `{feat}`"),
557                        Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
558                    },
559                    _ => "",
560                };
561                if !human_readable.is_empty() {
562                    fmt.write_str(human_readable)
563                } else if let Some(v) = value {
564                    if self.1.is_html() {
565                        write!(
566                            fmt,
567                            r#"<code>{}="{}"</code>"#,
568                            Escape(name.as_str()),
569                            Escape(v.as_str())
570                        )
571                    } else {
572                        write!(fmt, r#"`{name}="{v}"`"#)
573                    }
574                } else if self.1.is_html() {
575                    write!(fmt, "<code>{}</code>", Escape(name.as_str()))
576                } else {
577                    write!(fmt, "`{name}`")
578                }
579            }
580        }
581    }
582}