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.omit_preposition() {
175            ""
176        } else if self.should_use_with_in_description() {
177            "with "
178        } else {
179            "on "
180        };
181
182        let mut msg = format!("Available {on}<strong>{}</strong>", Display(self, Format::LongHtml));
183        if self.should_append_only_to_description() {
184            msg.push_str(" only");
185        }
186        msg.push('.');
187        msg
188    }
189
190    /// Renders the configuration for long display, as a long plain text description.
191    pub(crate) fn render_long_plain(&self) -> String {
192        let on = if self.should_use_with_in_description() { "with" } else { "on" };
193
194        let mut msg = format!("Available {on} {}", Display(self, Format::LongPlain));
195        if self.should_append_only_to_description() {
196            msg.push_str(" only");
197        }
198        msg
199    }
200
201    fn should_capitalize_first_letter(&self) -> bool {
202        match *self {
203            Cfg::False | Cfg::True | Cfg::Not(..) => true,
204            Cfg::Any(ref sub_cfgs) | Cfg::All(ref sub_cfgs) => {
205                sub_cfgs.first().map(Cfg::should_capitalize_first_letter).unwrap_or(false)
206            }
207            Cfg::Cfg(name, _) => name == sym::debug_assertions || name == sym::target_endian,
208        }
209    }
210
211    fn should_append_only_to_description(&self) -> bool {
212        match self {
213            Cfg::False | Cfg::True => false,
214            Cfg::Any(..) | Cfg::All(..) | Cfg::Cfg(..) => true,
215            Cfg::Not(box Cfg::Cfg(..)) => true,
216            Cfg::Not(..) => false,
217        }
218    }
219
220    fn should_use_with_in_description(&self) -> bool {
221        matches!(self, Cfg::Cfg(sym::target_feature, _))
222    }
223
224    /// Attempt to simplify this cfg by assuming that `assume` is already known to be true, will
225    /// return `None` if simplification managed to completely eliminate any requirements from this
226    /// `Cfg`.
227    ///
228    /// See `tests::test_simplify_with` for examples.
229    pub(crate) fn simplify_with(&self, assume: &Self) -> Option<Self> {
230        if self == assume {
231            None
232        } else if let Cfg::All(a) = self {
233            let mut sub_cfgs: Vec<Cfg> = if let Cfg::All(b) = assume {
234                a.iter().filter(|a| !b.contains(a)).cloned().collect()
235            } else {
236                a.iter().filter(|&a| a != assume).cloned().collect()
237            };
238            let len = sub_cfgs.len();
239            match len {
240                0 => None,
241                1 => sub_cfgs.pop(),
242                _ => Some(Cfg::All(sub_cfgs)),
243            }
244        } else if let Cfg::All(b) = assume
245            && b.contains(self)
246        {
247            None
248        } else {
249            Some(self.clone())
250        }
251    }
252
253    fn omit_preposition(&self) -> bool {
254        matches!(self, Cfg::True | Cfg::False)
255    }
256}
257
258impl ops::Not for Cfg {
259    type Output = Cfg;
260    fn not(self) -> Cfg {
261        match self {
262            Cfg::False => Cfg::True,
263            Cfg::True => Cfg::False,
264            Cfg::Not(cfg) => *cfg,
265            s => Cfg::Not(Box::new(s)),
266        }
267    }
268}
269
270impl ops::BitAndAssign for Cfg {
271    fn bitand_assign(&mut self, other: Cfg) {
272        match (self, other) {
273            (Cfg::False, _) | (_, Cfg::True) => {}
274            (s, Cfg::False) => *s = Cfg::False,
275            (s @ Cfg::True, b) => *s = b,
276            (Cfg::All(a), Cfg::All(ref mut b)) => {
277                for c in b.drain(..) {
278                    if !a.contains(&c) {
279                        a.push(c);
280                    }
281                }
282            }
283            (Cfg::All(a), ref mut b) => {
284                if !a.contains(b) {
285                    a.push(mem::replace(b, Cfg::True));
286                }
287            }
288            (s, Cfg::All(mut a)) => {
289                let b = mem::replace(s, Cfg::True);
290                if !a.contains(&b) {
291                    a.push(b);
292                }
293                *s = Cfg::All(a);
294            }
295            (s, b) => {
296                if *s != b {
297                    let a = mem::replace(s, Cfg::True);
298                    *s = Cfg::All(vec![a, b]);
299                }
300            }
301        }
302    }
303}
304
305impl ops::BitAnd for Cfg {
306    type Output = Cfg;
307    fn bitand(mut self, other: Cfg) -> Cfg {
308        self &= other;
309        self
310    }
311}
312
313impl ops::BitOrAssign for Cfg {
314    fn bitor_assign(&mut self, other: Cfg) {
315        match (self, other) {
316            (Cfg::True, _) | (_, Cfg::False) | (_, Cfg::True) => {}
317            (s @ Cfg::False, b) => *s = b,
318            (Cfg::Any(a), Cfg::Any(ref mut b)) => {
319                for c in b.drain(..) {
320                    if !a.contains(&c) {
321                        a.push(c);
322                    }
323                }
324            }
325            (Cfg::Any(a), ref mut b) => {
326                if !a.contains(b) {
327                    a.push(mem::replace(b, Cfg::True));
328                }
329            }
330            (s, Cfg::Any(mut a)) => {
331                let b = mem::replace(s, Cfg::True);
332                if !a.contains(&b) {
333                    a.push(b);
334                }
335                *s = Cfg::Any(a);
336            }
337            (s, b) => {
338                if *s != b {
339                    let a = mem::replace(s, Cfg::True);
340                    *s = Cfg::Any(vec![a, b]);
341                }
342            }
343        }
344    }
345}
346
347impl ops::BitOr for Cfg {
348    type Output = Cfg;
349    fn bitor(mut self, other: Cfg) -> Cfg {
350        self |= other;
351        self
352    }
353}
354
355#[derive(Clone, Copy)]
356enum Format {
357    LongHtml,
358    LongPlain,
359    ShortHtml,
360}
361
362impl Format {
363    fn is_long(self) -> bool {
364        match self {
365            Format::LongHtml | Format::LongPlain => true,
366            Format::ShortHtml => false,
367        }
368    }
369
370    fn is_html(self) -> bool {
371        match self {
372            Format::LongHtml | Format::ShortHtml => true,
373            Format::LongPlain => false,
374        }
375    }
376}
377
378/// Pretty-print wrapper for a `Cfg`. Also indicates what form of rendering should be used.
379struct Display<'a>(&'a Cfg, Format);
380
381fn write_with_opt_paren<T: fmt::Display>(
382    fmt: &mut fmt::Formatter<'_>,
383    has_paren: bool,
384    obj: T,
385) -> fmt::Result {
386    if has_paren {
387        fmt.write_char('(')?;
388    }
389    obj.fmt(fmt)?;
390    if has_paren {
391        fmt.write_char(')')?;
392    }
393    Ok(())
394}
395
396impl Display<'_> {
397    fn display_sub_cfgs(
398        &self,
399        fmt: &mut fmt::Formatter<'_>,
400        sub_cfgs: &[Cfg],
401        separator: &str,
402    ) -> fmt::Result {
403        use fmt::Display as _;
404
405        let short_longhand = self.1.is_long() && {
406            let all_crate_features =
407                sub_cfgs.iter().all(|sub_cfg| matches!(sub_cfg, Cfg::Cfg(sym::feature, Some(_))));
408            let all_target_features = sub_cfgs
409                .iter()
410                .all(|sub_cfg| matches!(sub_cfg, Cfg::Cfg(sym::target_feature, Some(_))));
411
412            if all_crate_features {
413                fmt.write_str("crate features ")?;
414                true
415            } else if all_target_features {
416                fmt.write_str("target features ")?;
417                true
418            } else {
419                false
420            }
421        };
422
423        fmt::from_fn(|f| {
424            sub_cfgs
425                .iter()
426                .map(|sub_cfg| {
427                    fmt::from_fn(move |fmt| {
428                        if let Cfg::Cfg(_, Some(feat)) = sub_cfg
429                            && short_longhand
430                        {
431                            if self.1.is_html() {
432                                write!(fmt, "<code>{feat}</code>")?;
433                            } else {
434                                write!(fmt, "`{feat}`")?;
435                            }
436                        } else {
437                            write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))?;
438                        }
439                        Ok(())
440                    })
441                })
442                .joined(separator, f)
443        })
444        .fmt(fmt)?;
445
446        Ok(())
447    }
448}
449
450impl fmt::Display for Display<'_> {
451    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
452        match self.0 {
453            Cfg::Not(box Cfg::Any(sub_cfgs)) => {
454                let separator =
455                    if sub_cfgs.iter().all(Cfg::is_simple) { " nor " } else { ", nor " };
456                fmt.write_str("neither ")?;
457
458                sub_cfgs
459                    .iter()
460                    .map(|sub_cfg| {
461                        fmt::from_fn(|fmt| {
462                            write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))
463                        })
464                    })
465                    .joined(separator, fmt)
466            }
467            Cfg::Not(box simple @ Cfg::Cfg(..)) => write!(fmt, "non-{}", Display(simple, self.1)),
468            Cfg::Not(box c) => write!(fmt, "not ({})", Display(c, self.1)),
469
470            Cfg::Any(sub_cfgs) => {
471                let separator = if sub_cfgs.iter().all(Cfg::is_simple) { " or " } else { ", or " };
472                self.display_sub_cfgs(fmt, sub_cfgs, separator)
473            }
474            Cfg::All(sub_cfgs) => self.display_sub_cfgs(fmt, sub_cfgs, " and "),
475
476            Cfg::True => fmt.write_str("everywhere"),
477            Cfg::False => fmt.write_str("nowhere"),
478
479            &Cfg::Cfg(name, value) => {
480                let human_readable = match (name, value) {
481                    (sym::unix, None) => "Unix",
482                    (sym::windows, None) => "Windows",
483                    (sym::debug_assertions, None) => "debug-assertions enabled",
484                    (sym::target_os, Some(os)) => match os.as_str() {
485                        "android" => "Android",
486                        "dragonfly" => "DragonFly BSD",
487                        "emscripten" => "Emscripten",
488                        "freebsd" => "FreeBSD",
489                        "fuchsia" => "Fuchsia",
490                        "haiku" => "Haiku",
491                        "hermit" => "HermitCore",
492                        "illumos" => "illumos",
493                        "ios" => "iOS",
494                        "l4re" => "L4Re",
495                        "linux" => "Linux",
496                        "macos" => "macOS",
497                        "netbsd" => "NetBSD",
498                        "openbsd" => "OpenBSD",
499                        "redox" => "Redox",
500                        "solaris" => "Solaris",
501                        "tvos" => "tvOS",
502                        "wasi" => "WASI",
503                        "watchos" => "watchOS",
504                        "windows" => "Windows",
505                        "visionos" => "visionOS",
506                        _ => "",
507                    },
508                    (sym::target_arch, Some(arch)) => match arch.as_str() {
509                        "aarch64" => "AArch64",
510                        "arm" => "ARM",
511                        "loongarch64" => "LoongArch LA64",
512                        "m68k" => "M68k",
513                        "csky" => "CSKY",
514                        "mips" => "MIPS",
515                        "mips32r6" => "MIPS Release 6",
516                        "mips64" => "MIPS-64",
517                        "mips64r6" => "MIPS-64 Release 6",
518                        "msp430" => "MSP430",
519                        "powerpc" => "PowerPC",
520                        "powerpc64" => "PowerPC-64",
521                        "riscv32" => "RISC-V RV32",
522                        "riscv64" => "RISC-V RV64",
523                        "s390x" => "s390x",
524                        "sparc64" => "SPARC64",
525                        "wasm32" | "wasm64" => "WebAssembly",
526                        "x86" => "x86",
527                        "x86_64" => "x86-64",
528                        _ => "",
529                    },
530                    (sym::target_vendor, Some(vendor)) => match vendor.as_str() {
531                        "apple" => "Apple",
532                        "pc" => "PC",
533                        "sun" => "Sun",
534                        "fortanix" => "Fortanix",
535                        _ => "",
536                    },
537                    (sym::target_env, Some(env)) => match env.as_str() {
538                        "gnu" => "GNU",
539                        "msvc" => "MSVC",
540                        "musl" => "musl",
541                        "newlib" => "Newlib",
542                        "uclibc" => "uClibc",
543                        "sgx" => "SGX",
544                        _ => "",
545                    },
546                    (sym::target_endian, Some(endian)) => return write!(fmt, "{endian}-endian"),
547                    (sym::target_pointer_width, Some(bits)) => return write!(fmt, "{bits}-bit"),
548                    (sym::target_feature, Some(feat)) => match self.1 {
549                        Format::LongHtml => {
550                            return write!(fmt, "target feature <code>{feat}</code>");
551                        }
552                        Format::LongPlain => return write!(fmt, "target feature `{feat}`"),
553                        Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
554                    },
555                    (sym::feature, Some(feat)) => match self.1 {
556                        Format::LongHtml => {
557                            return write!(fmt, "crate feature <code>{feat}</code>");
558                        }
559                        Format::LongPlain => return write!(fmt, "crate feature `{feat}`"),
560                        Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
561                    },
562                    _ => "",
563                };
564                if !human_readable.is_empty() {
565                    fmt.write_str(human_readable)
566                } else if let Some(v) = value {
567                    if self.1.is_html() {
568                        write!(
569                            fmt,
570                            r#"<code>{}="{}"</code>"#,
571                            Escape(name.as_str()),
572                            Escape(v.as_str())
573                        )
574                    } else {
575                        write!(fmt, r#"`{name}="{v}"`"#)
576                    }
577                } else if self.1.is_html() {
578                    write!(fmt, "<code>{}</code>", Escape(name.as_str()))
579                } else {
580                    write!(fmt, "`{name}`")
581                }
582            }
583        }
584    }
585}