]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/cfg.rs
Render longhand multiple crate/target features nicer
[rust.git] / src / librustdoc / 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
6 use std::fmt::{self, Write};
7 use std::mem;
8 use std::ops;
9
10 use rustc_ast::ast::{LitKind, MetaItem, MetaItemKind, NestedMetaItem};
11 use rustc_feature::Features;
12 use rustc_session::parse::ParseSess;
13 use rustc_span::symbol::{sym, Symbol};
14
15 use rustc_span::Span;
16
17 use crate::html::escape::Escape;
18
19 #[cfg(test)]
20 mod tests;
21
22 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
23 pub enum Cfg {
24     /// Accepts all configurations.
25     True,
26     /// Denies all configurations.
27     False,
28     /// A generic configuration option, e.g., `test` or `target_os = "linux"`.
29     Cfg(Symbol, Option<Symbol>),
30     /// Negates a configuration requirement, i.e., `not(x)`.
31     Not(Box<Cfg>),
32     /// Union of a list of configuration requirements, i.e., `any(...)`.
33     Any(Vec<Cfg>),
34     /// Intersection of a list of configuration requirements, i.e., `all(...)`.
35     All(Vec<Cfg>),
36 }
37
38 #[derive(PartialEq, Debug)]
39 pub struct InvalidCfgError {
40     pub msg: &'static str,
41     pub span: Span,
42 }
43
44 impl Cfg {
45     /// Parses a `NestedMetaItem` into a `Cfg`.
46     fn parse_nested(nested_cfg: &NestedMetaItem) -> Result<Cfg, InvalidCfgError> {
47         match nested_cfg {
48             NestedMetaItem::MetaItem(ref cfg) => Cfg::parse(cfg),
49             NestedMetaItem::Literal(ref lit) => {
50                 Err(InvalidCfgError { msg: "unexpected literal", span: lit.span })
51             }
52         }
53     }
54
55     /// Parses a `MetaItem` into a `Cfg`.
56     ///
57     /// The `MetaItem` should be the content of the `#[cfg(...)]`, e.g., `unix` or
58     /// `target_os = "redox"`.
59     ///
60     /// If the content is not properly formatted, it will return an error indicating what and where
61     /// the error is.
62     pub fn parse(cfg: &MetaItem) -> Result<Cfg, InvalidCfgError> {
63         let name = match cfg.ident() {
64             Some(ident) => ident.name,
65             None => {
66                 return Err(InvalidCfgError {
67                     msg: "expected a single identifier",
68                     span: cfg.span,
69                 });
70             }
71         };
72         match cfg.kind {
73             MetaItemKind::Word => Ok(Cfg::Cfg(name, None)),
74             MetaItemKind::NameValue(ref lit) => match lit.kind {
75                 LitKind::Str(value, _) => Ok(Cfg::Cfg(name, Some(value))),
76                 _ => Err(InvalidCfgError {
77                     // FIXME: if the main #[cfg] syntax decided to support non-string literals,
78                     // this should be changed as well.
79                     msg: "value of cfg option should be a string literal",
80                     span: lit.span,
81                 }),
82             },
83             MetaItemKind::List(ref items) => {
84                 let mut sub_cfgs = items.iter().map(Cfg::parse_nested);
85                 match name {
86                     sym::all => sub_cfgs.fold(Ok(Cfg::True), |x, y| Ok(x? & y?)),
87                     sym::any => sub_cfgs.fold(Ok(Cfg::False), |x, y| Ok(x? | y?)),
88                     sym::not => {
89                         if sub_cfgs.len() == 1 {
90                             Ok(!sub_cfgs.next().unwrap()?)
91                         } else {
92                             Err(InvalidCfgError { msg: "expected 1 cfg-pattern", span: cfg.span })
93                         }
94                     }
95                     _ => Err(InvalidCfgError { msg: "invalid predicate", span: cfg.span }),
96                 }
97             }
98         }
99     }
100
101     /// Checks whether the given configuration can be matched in the current session.
102     ///
103     /// Equivalent to `attr::cfg_matches`.
104     // FIXME: Actually make use of `features`.
105     pub fn matches(&self, parse_sess: &ParseSess, features: Option<&Features>) -> bool {
106         match *self {
107             Cfg::False => false,
108             Cfg::True => true,
109             Cfg::Not(ref child) => !child.matches(parse_sess, features),
110             Cfg::All(ref sub_cfgs) => {
111                 sub_cfgs.iter().all(|sub_cfg| sub_cfg.matches(parse_sess, features))
112             }
113             Cfg::Any(ref sub_cfgs) => {
114                 sub_cfgs.iter().any(|sub_cfg| sub_cfg.matches(parse_sess, features))
115             }
116             Cfg::Cfg(name, value) => parse_sess.config.contains(&(name, value)),
117         }
118     }
119
120     /// Whether the configuration consists of just `Cfg` or `Not`.
121     fn is_simple(&self) -> bool {
122         match *self {
123             Cfg::False | Cfg::True | Cfg::Cfg(..) | Cfg::Not(..) => true,
124             Cfg::All(..) | Cfg::Any(..) => false,
125         }
126     }
127
128     /// Whether the configuration consists of just `Cfg`, `Not` or `All`.
129     fn is_all(&self) -> bool {
130         match *self {
131             Cfg::False | Cfg::True | Cfg::Cfg(..) | Cfg::Not(..) | Cfg::All(..) => true,
132             Cfg::Any(..) => false,
133         }
134     }
135
136     /// Renders the configuration for human display, as a short HTML description.
137     pub(crate) fn render_short_html(&self) -> String {
138         let mut msg = Html(self, true).to_string();
139         if self.should_capitalize_first_letter() {
140             if let Some(i) = msg.find(|c: char| c.is_ascii_alphanumeric()) {
141                 msg[i..i + 1].make_ascii_uppercase();
142             }
143         }
144         msg
145     }
146
147     /// Renders the configuration for long display, as a long HTML description.
148     pub(crate) fn render_long_html(&self) -> String {
149         let on = if self.should_use_with_in_description() { "with" } else { "on" };
150
151         let mut msg = format!("This is supported {} <strong>{}</strong>", on, Html(self, false));
152         if self.should_append_only_to_description() {
153             msg.push_str(" only");
154         }
155         msg.push('.');
156         msg
157     }
158
159     fn should_capitalize_first_letter(&self) -> bool {
160         match *self {
161             Cfg::False | Cfg::True | Cfg::Not(..) => true,
162             Cfg::Any(ref sub_cfgs) | Cfg::All(ref sub_cfgs) => {
163                 sub_cfgs.first().map(Cfg::should_capitalize_first_letter).unwrap_or(false)
164             }
165             Cfg::Cfg(name, _) => match name {
166                 sym::debug_assertions | sym::target_endian => true,
167                 _ => false,
168             },
169         }
170     }
171
172     fn should_append_only_to_description(&self) -> bool {
173         match *self {
174             Cfg::False | Cfg::True => false,
175             Cfg::Any(..) | Cfg::All(..) | Cfg::Cfg(..) => true,
176             Cfg::Not(ref child) => match **child {
177                 Cfg::Cfg(..) => true,
178                 _ => false,
179             },
180         }
181     }
182
183     fn should_use_with_in_description(&self) -> bool {
184         match *self {
185             Cfg::Cfg(name, _) if name == sym::target_feature => true,
186             _ => false,
187         }
188     }
189 }
190
191 impl ops::Not for Cfg {
192     type Output = Cfg;
193     fn not(self) -> Cfg {
194         match self {
195             Cfg::False => Cfg::True,
196             Cfg::True => Cfg::False,
197             Cfg::Not(cfg) => *cfg,
198             s => Cfg::Not(Box::new(s)),
199         }
200     }
201 }
202
203 impl ops::BitAndAssign for Cfg {
204     fn bitand_assign(&mut self, other: Cfg) {
205         match (self, other) {
206             (&mut Cfg::False, _) | (_, Cfg::True) => {}
207             (s, Cfg::False) => *s = Cfg::False,
208             (s @ &mut Cfg::True, b) => *s = b,
209             (&mut Cfg::All(ref mut a), Cfg::All(ref mut b)) => {
210                 for c in b.drain(..) {
211                     if !a.contains(&c) {
212                         a.push(c);
213                     }
214                 }
215             }
216             (&mut Cfg::All(ref mut a), ref mut b) => {
217                 if !a.contains(b) {
218                     a.push(mem::replace(b, Cfg::True));
219                 }
220             }
221             (s, Cfg::All(mut a)) => {
222                 let b = mem::replace(s, Cfg::True);
223                 if !a.contains(&b) {
224                     a.push(b);
225                 }
226                 *s = Cfg::All(a);
227             }
228             (s, b) => {
229                 if *s != b {
230                     let a = mem::replace(s, Cfg::True);
231                     *s = Cfg::All(vec![a, b]);
232                 }
233             }
234         }
235     }
236 }
237
238 impl ops::BitAnd for Cfg {
239     type Output = Cfg;
240     fn bitand(mut self, other: Cfg) -> Cfg {
241         self &= other;
242         self
243     }
244 }
245
246 impl ops::BitOrAssign for Cfg {
247     fn bitor_assign(&mut self, other: Cfg) {
248         match (self, other) {
249             (&mut Cfg::True, _) | (_, Cfg::False) => {}
250             (s, Cfg::True) => *s = Cfg::True,
251             (s @ &mut Cfg::False, b) => *s = b,
252             (&mut Cfg::Any(ref mut a), Cfg::Any(ref mut b)) => {
253                 for c in b.drain(..) {
254                     if !a.contains(&c) {
255                         a.push(c);
256                     }
257                 }
258             }
259             (&mut Cfg::Any(ref mut a), ref mut b) => {
260                 if !a.contains(b) {
261                     a.push(mem::replace(b, Cfg::True));
262                 }
263             }
264             (s, Cfg::Any(mut a)) => {
265                 let b = mem::replace(s, Cfg::True);
266                 if !a.contains(&b) {
267                     a.push(b);
268                 }
269                 *s = Cfg::Any(a);
270             }
271             (s, b) => {
272                 if *s != b {
273                     let a = mem::replace(s, Cfg::True);
274                     *s = Cfg::Any(vec![a, b]);
275                 }
276             }
277         }
278     }
279 }
280
281 impl ops::BitOr for Cfg {
282     type Output = Cfg;
283     fn bitor(mut self, other: Cfg) -> Cfg {
284         self |= other;
285         self
286     }
287 }
288
289 /// Pretty-print wrapper for a `Cfg`. Also indicates whether the "short-form" rendering should be
290 /// used.
291 struct Html<'a>(&'a Cfg, bool);
292
293 fn write_with_opt_paren<T: fmt::Display>(
294     fmt: &mut fmt::Formatter<'_>,
295     has_paren: bool,
296     obj: T,
297 ) -> fmt::Result {
298     if has_paren {
299         fmt.write_char('(')?;
300     }
301     obj.fmt(fmt)?;
302     if has_paren {
303         fmt.write_char(')')?;
304     }
305     Ok(())
306 }
307
308 impl<'a> fmt::Display for Html<'a> {
309     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
310         match *self.0 {
311             Cfg::Not(ref child) => match **child {
312                 Cfg::Any(ref sub_cfgs) => {
313                     let separator =
314                         if sub_cfgs.iter().all(Cfg::is_simple) { " nor " } else { ", nor " };
315                     for (i, sub_cfg) in sub_cfgs.iter().enumerate() {
316                         fmt.write_str(if i == 0 { "neither " } else { separator })?;
317                         write_with_opt_paren(fmt, !sub_cfg.is_all(), Html(sub_cfg, self.1))?;
318                     }
319                     Ok(())
320                 }
321                 ref simple @ Cfg::Cfg(..) => write!(fmt, "non-{}", Html(simple, self.1)),
322                 ref c => write!(fmt, "not ({})", Html(c, self.1)),
323             },
324
325             Cfg::Any(ref sub_cfgs) => {
326                 let separator = if sub_cfgs.iter().all(Cfg::is_simple) { " or " } else { ", or " };
327
328                 let short_longhand = !self.1 && {
329                     let all_crate_features = sub_cfgs
330                         .iter()
331                         .all(|sub_cfg| matches!(sub_cfg, Cfg::Cfg(sym::feature, Some(_))));
332                     let all_target_features = sub_cfgs
333                         .iter()
334                         .all(|sub_cfg| matches!(sub_cfg, Cfg::Cfg(sym::target_feature, Some(_))));
335
336                     if all_crate_features {
337                         fmt.write_str("crate features ")?;
338                         true
339                     } else if all_target_features {
340                         fmt.write_str("target features ")?;
341                         true
342                     } else {
343                         false
344                     }
345                 };
346
347                 for (i, sub_cfg) in sub_cfgs.iter().enumerate() {
348                     if i != 0 {
349                         fmt.write_str(separator)?;
350                     }
351                     if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) {
352                         write!(fmt, "<code>{}</code>", feat)?;
353                     } else {
354                         write_with_opt_paren(fmt, !sub_cfg.is_all(), Html(sub_cfg, self.1))?;
355                     }
356                 }
357                 Ok(())
358             }
359
360             Cfg::All(ref sub_cfgs) => {
361                 let short_longhand = !self.1 && {
362                     let all_crate_features = sub_cfgs
363                         .iter()
364                         .all(|sub_cfg| matches!(sub_cfg, Cfg::Cfg(sym::feature, Some(_))));
365                     let all_target_features = sub_cfgs
366                         .iter()
367                         .all(|sub_cfg| matches!(sub_cfg, Cfg::Cfg(sym::target_feature, Some(_))));
368
369                     if all_crate_features {
370                         fmt.write_str("crate features ")?;
371                         true
372                     } else if all_target_features {
373                         fmt.write_str("target features ")?;
374                         true
375                     } else {
376                         false
377                     }
378                 };
379
380                 for (i, sub_cfg) in sub_cfgs.iter().enumerate() {
381                     if i != 0 {
382                         fmt.write_str(" and ")?;
383                     }
384                     if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) {
385                         write!(fmt, "<code>{}</code>", feat)?;
386                     } else {
387                         write_with_opt_paren(fmt, !sub_cfg.is_simple(), Html(sub_cfg, self.1))?;
388                     }
389                 }
390                 Ok(())
391             }
392
393             Cfg::True => fmt.write_str("everywhere"),
394             Cfg::False => fmt.write_str("nowhere"),
395
396             Cfg::Cfg(name, value) => {
397                 let human_readable = match (name, value) {
398                     (sym::unix, None) => "Unix",
399                     (sym::windows, None) => "Windows",
400                     (sym::debug_assertions, None) => "debug-assertions enabled",
401                     (sym::target_os, Some(os)) => match &*os.as_str() {
402                         "android" => "Android",
403                         "dragonfly" => "DragonFly BSD",
404                         "emscripten" => "Emscripten",
405                         "freebsd" => "FreeBSD",
406                         "fuchsia" => "Fuchsia",
407                         "haiku" => "Haiku",
408                         "hermit" => "HermitCore",
409                         "illumos" => "illumos",
410                         "ios" => "iOS",
411                         "l4re" => "L4Re",
412                         "linux" => "Linux",
413                         "macos" => "macOS",
414                         "netbsd" => "NetBSD",
415                         "openbsd" => "OpenBSD",
416                         "redox" => "Redox",
417                         "solaris" => "Solaris",
418                         "windows" => "Windows",
419                         _ => "",
420                     },
421                     (sym::target_arch, Some(arch)) => match &*arch.as_str() {
422                         "aarch64" => "AArch64",
423                         "arm" => "ARM",
424                         "asmjs" => "JavaScript",
425                         "mips" => "MIPS",
426                         "mips64" => "MIPS-64",
427                         "msp430" => "MSP430",
428                         "powerpc" => "PowerPC",
429                         "powerpc64" => "PowerPC-64",
430                         "s390x" => "s390x",
431                         "sparc64" => "SPARC64",
432                         "wasm32" => "WebAssembly",
433                         "x86" => "x86",
434                         "x86_64" => "x86-64",
435                         _ => "",
436                     },
437                     (sym::target_vendor, Some(vendor)) => match &*vendor.as_str() {
438                         "apple" => "Apple",
439                         "pc" => "PC",
440                         "rumprun" => "Rumprun",
441                         "sun" => "Sun",
442                         "fortanix" => "Fortanix",
443                         _ => "",
444                     },
445                     (sym::target_env, Some(env)) => match &*env.as_str() {
446                         "gnu" => "GNU",
447                         "msvc" => "MSVC",
448                         "musl" => "musl",
449                         "newlib" => "Newlib",
450                         "uclibc" => "uClibc",
451                         "sgx" => "SGX",
452                         _ => "",
453                     },
454                     (sym::target_endian, Some(endian)) => return write!(fmt, "{}-endian", endian),
455                     (sym::target_pointer_width, Some(bits)) => return write!(fmt, "{}-bit", bits),
456                     (sym::target_feature, Some(feat)) => {
457                         if self.1 {
458                             return write!(fmt, "<code>{}</code>", feat);
459                         } else {
460                             return write!(fmt, "target feature <code>{}</code>", feat);
461                         }
462                     }
463                     (sym::feature, Some(feat)) => {
464                         if self.1 {
465                             return write!(fmt, "<code>{}</code>", feat);
466                         } else {
467                             return write!(fmt, "crate feature <code>{}</code>", feat);
468                         }
469                     }
470                     _ => "",
471                 };
472                 if !human_readable.is_empty() {
473                     fmt.write_str(human_readable)
474                 } else if let Some(v) = value {
475                     write!(
476                         fmt,
477                         "<code>{}=\"{}\"</code>",
478                         Escape(&name.as_str()),
479                         Escape(&v.as_str())
480                     )
481                 } else {
482                     write!(fmt, "<code>{}</code>", Escape(&name.as_str()))
483                 }
484             }
485         }
486     }
487 }