1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Representation of a `#[doc(cfg(...))]` attribute.
13 // FIXME: Once RFC #1868 is implemented, switch to use those structures instead.
16 use std::fmt::{self, Write};
19 use syntax::symbol::Symbol;
20 use syntax::ast::{MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind, LitKind};
21 use syntax::parse::ParseSess;
22 use syntax::feature_gate::Features;
26 use html::escape::Escape;
28 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, Hash)]
30 /// Accepts all configurations.
32 /// Denies all configurations.
34 /// A generic configration option, e.g. `test` or `target_os = "linux"`.
35 Cfg(Symbol, Option<Symbol>),
36 /// Negate a configuration requirement, i.e. `not(x)`.
38 /// Union of a list of configuration requirements, i.e. `any(...)`.
40 /// Intersection of a list of configuration requirements, i.e. `all(...)`.
44 #[derive(PartialEq, Debug)]
45 pub struct InvalidCfgError {
46 pub msg: &'static str,
51 /// Parses a `NestedMetaItem` into a `Cfg`.
52 fn parse_nested(nested_cfg: &NestedMetaItem) -> Result<Cfg, InvalidCfgError> {
53 match nested_cfg.node {
54 NestedMetaItemKind::MetaItem(ref cfg) => Cfg::parse(cfg),
55 NestedMetaItemKind::Literal(ref lit) => Err(InvalidCfgError {
56 msg: "unexpected literal",
62 /// Parses a `MetaItem` into a `Cfg`.
64 /// The `MetaItem` should be the content of the `#[cfg(...)]`, e.g. `unix` or
65 /// `target_os = "redox"`.
67 /// If the content is not properly formatted, it will return an error indicating what and where
69 pub fn parse(cfg: &MetaItem) -> Result<Cfg, InvalidCfgError> {
70 let name = cfg.name();
72 MetaItemKind::Word => Ok(Cfg::Cfg(name, None)),
73 MetaItemKind::NameValue(ref lit) => match lit.node {
74 LitKind::Str(value, _) => Ok(Cfg::Cfg(name, Some(value))),
75 _ => Err(InvalidCfgError {
76 // FIXME: if the main #[cfg] syntax decided to support non-string literals,
77 // this should be changed as well.
78 msg: "value of cfg option should be a string literal",
82 MetaItemKind::List(ref items) => {
83 let mut sub_cfgs = items.iter().map(Cfg::parse_nested);
84 match &*name.as_str() {
85 "all" => sub_cfgs.fold(Ok(Cfg::True), |x, y| Ok(x? & y?)),
86 "any" => sub_cfgs.fold(Ok(Cfg::False), |x, y| Ok(x? | y?)),
87 "not" => if sub_cfgs.len() == 1 {
88 Ok(!sub_cfgs.next().unwrap()?)
91 msg: "expected 1 cfg-pattern",
95 _ => Err(InvalidCfgError {
96 msg: "invalid predicate",
104 /// Checks whether the given configuration can be matched in the current session.
106 /// Equivalent to `attr::cfg_matches`.
107 // FIXME: Actually make use of `features`.
108 pub fn matches(&self, parse_sess: &ParseSess, features: Option<&Features>) -> bool {
112 Cfg::Not(ref child) => !child.matches(parse_sess, features),
113 Cfg::All(ref sub_cfgs) => {
114 sub_cfgs.iter().all(|sub_cfg| sub_cfg.matches(parse_sess, features))
116 Cfg::Any(ref sub_cfgs) => {
117 sub_cfgs.iter().any(|sub_cfg| sub_cfg.matches(parse_sess, features))
119 Cfg::Cfg(name, value) => parse_sess.config.contains(&(name, value)),
123 /// Whether the configuration consists of just `Cfg` or `Not`.
124 fn is_simple(&self) -> bool {
126 Cfg::False | Cfg::True | Cfg::Cfg(..) | Cfg::Not(..) => true,
127 Cfg::All(..) | Cfg::Any(..) => false,
131 /// Whether the configuration consists of just `Cfg`, `Not` or `All`.
132 fn is_all(&self) -> bool {
134 Cfg::False | Cfg::True | Cfg::Cfg(..) | Cfg::Not(..) | Cfg::All(..) => true,
135 Cfg::Any(..) => false,
139 /// Renders the configuration for human display, as a short HTML description.
140 pub(crate) fn render_short_html(&self) -> String {
141 let mut msg = Html(self).to_string();
142 if self.should_capitalize_first_letter() {
143 if let Some(i) = msg.find(|c: char| c.is_ascii_alphanumeric()) {
144 msg[i .. i+1].make_ascii_uppercase();
150 /// Renders the configuration for long display, as a long HTML description.
151 pub(crate) fn render_long_html(&self) -> String {
152 let mut msg = format!("This is supported on <strong>{}</strong>", Html(self));
153 if self.should_append_only_to_description() {
154 msg.push_str(" only");
160 fn should_capitalize_first_letter(&self) -> bool {
162 Cfg::False | Cfg::True | Cfg::Not(..) => true,
163 Cfg::Any(ref sub_cfgs) | Cfg::All(ref sub_cfgs) => {
164 sub_cfgs.first().map(Cfg::should_capitalize_first_letter).unwrap_or(false)
166 Cfg::Cfg(name, _) => match &*name.as_str() {
167 "debug_assertions" | "target_endian" => true,
173 fn should_append_only_to_description(&self) -> bool {
175 Cfg::False | Cfg::True => false,
176 Cfg::Any(..) | Cfg::All(..) | Cfg::Cfg(..) => true,
177 Cfg::Not(ref child) => match **child {
178 Cfg::Cfg(..) => true,
185 impl ops::Not for Cfg {
187 fn not(self) -> Cfg {
189 Cfg::False => Cfg::True,
190 Cfg::True => Cfg::False,
191 Cfg::Not(cfg) => *cfg,
192 s => Cfg::Not(Box::new(s)),
197 impl ops::BitAndAssign for Cfg {
198 fn bitand_assign(&mut self, other: Cfg) {
199 match (self, other) {
200 (&mut Cfg::False, _) | (_, Cfg::True) => {},
201 (s, Cfg::False) => *s = Cfg::False,
202 (s @ &mut Cfg::True, b) => *s = b,
203 (&mut Cfg::All(ref mut a), Cfg::All(ref mut b)) => a.append(b),
204 (&mut Cfg::All(ref mut a), ref mut b) => a.push(mem::replace(b, Cfg::True)),
205 (s, Cfg::All(mut a)) => {
206 let b = mem::replace(s, Cfg::True);
211 let a = mem::replace(s, Cfg::True);
212 *s = Cfg::All(vec![a, b]);
218 impl ops::BitAnd for Cfg {
220 fn bitand(mut self, other: Cfg) -> Cfg {
226 impl ops::BitOrAssign for Cfg {
227 fn bitor_assign(&mut self, other: Cfg) {
228 match (self, other) {
229 (&mut Cfg::True, _) | (_, Cfg::False) => {},
230 (s, Cfg::True) => *s = Cfg::True,
231 (s @ &mut Cfg::False, b) => *s = b,
232 (&mut Cfg::Any(ref mut a), Cfg::Any(ref mut b)) => a.append(b),
233 (&mut Cfg::Any(ref mut a), ref mut b) => a.push(mem::replace(b, Cfg::True)),
234 (s, Cfg::Any(mut a)) => {
235 let b = mem::replace(s, Cfg::True);
240 let a = mem::replace(s, Cfg::True);
241 *s = Cfg::Any(vec![a, b]);
247 impl ops::BitOr for Cfg {
249 fn bitor(mut self, other: Cfg) -> Cfg {
255 struct Html<'a>(&'a Cfg);
257 fn write_with_opt_paren<T: fmt::Display>(
258 fmt: &mut fmt::Formatter,
263 fmt.write_char('(')?;
267 fmt.write_char(')')?;
273 impl<'a> fmt::Display for Html<'a> {
274 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
276 Cfg::Not(ref child) => match **child {
277 Cfg::Any(ref sub_cfgs) => {
278 let separator = if sub_cfgs.iter().all(Cfg::is_simple) {
283 for (i, sub_cfg) in sub_cfgs.iter().enumerate() {
284 fmt.write_str(if i == 0 { "neither " } else { separator })?;
285 write_with_opt_paren(fmt, !sub_cfg.is_all(), Html(sub_cfg))?;
289 ref simple @ Cfg::Cfg(..) => write!(fmt, "non-{}", Html(simple)),
290 ref c => write!(fmt, "not ({})", Html(c)),
293 Cfg::Any(ref sub_cfgs) => {
294 let separator = if sub_cfgs.iter().all(Cfg::is_simple) {
299 for (i, sub_cfg) in sub_cfgs.iter().enumerate() {
301 fmt.write_str(separator)?;
303 write_with_opt_paren(fmt, !sub_cfg.is_all(), Html(sub_cfg))?;
308 Cfg::All(ref sub_cfgs) => {
309 for (i, sub_cfg) in sub_cfgs.iter().enumerate() {
311 fmt.write_str(" and ")?;
313 write_with_opt_paren(fmt, !sub_cfg.is_simple(), Html(sub_cfg))?;
318 Cfg::True => fmt.write_str("everywhere"),
319 Cfg::False => fmt.write_str("nowhere"),
321 Cfg::Cfg(name, value) => {
322 let n = &*name.as_str();
323 let human_readable = match (n, value) {
324 ("unix", None) => "Unix",
325 ("windows", None) => "Windows",
326 ("debug_assertions", None) => "debug-assertions enabled",
327 ("target_os", Some(os)) => match &*os.as_str() {
328 "android" => "Android",
329 "bitrig" => "Bitrig",
330 "dragonfly" => "DragonFly BSD",
331 "emscripten" => "Emscripten",
332 "freebsd" => "FreeBSD",
333 "fuchsia" => "Fuchsia",
339 "netbsd" => "NetBSD",
340 "openbsd" => "OpenBSD",
342 "solaris" => "Solaris",
343 "windows" => "Windows",
346 ("target_arch", Some(arch)) => match &*arch.as_str() {
347 "aarch64" => "AArch64",
351 "mips64" => "MIPS-64",
352 "msp430" => "MSP430",
353 "powerpc" => "PowerPC",
354 "powerpc64" => "PowerPC-64",
356 "sparc64" => "SPARC64",
357 "wasm32" => "WebAssembly",
359 "x86_64" => "x86-64",
362 ("target_vendor", Some(vendor)) => match &*vendor.as_str() {
365 "rumprun" => "Rumprun",
369 ("target_env", Some(env)) => match &*env.as_str() {
373 "newlib" => "Newlib",
374 "uclibc" => "uClibc",
377 ("target_endian", Some(endian)) => return write!(fmt, "{}-endian", endian),
378 ("target_pointer_width", Some(bits)) => return write!(fmt, "{}-bit", bits),
381 if !human_readable.is_empty() {
382 fmt.write_str(human_readable)
383 } else if let Some(v) = value {
384 write!(fmt, "<code>{}=\"{}\"</code>", Escape(n), Escape(&*v.as_str()))
386 write!(fmt, "<code>{}</code>", Escape(n))
397 use syntax::symbol::Symbol;
399 use syntax::codemap::dummy_spanned;
400 use syntax_pos::DUMMY_SP;
401 use syntax::with_globals;
403 fn word_cfg(s: &str) -> Cfg {
404 Cfg::Cfg(Symbol::intern(s), None)
407 fn name_value_cfg(name: &str, value: &str) -> Cfg {
408 Cfg::Cfg(Symbol::intern(name), Some(Symbol::intern(value)))
414 assert_eq!(!Cfg::False, Cfg::True);
415 assert_eq!(!Cfg::True, Cfg::False);
416 assert_eq!(!word_cfg("test"), Cfg::Not(Box::new(word_cfg("test"))));
418 !Cfg::All(vec![word_cfg("a"), word_cfg("b")]),
419 Cfg::Not(Box::new(Cfg::All(vec![word_cfg("a"), word_cfg("b")])))
422 !Cfg::Any(vec![word_cfg("a"), word_cfg("b")]),
423 Cfg::Not(Box::new(Cfg::Any(vec![word_cfg("a"), word_cfg("b")])))
425 assert_eq!(!Cfg::Not(Box::new(word_cfg("test"))), word_cfg("test"));
432 let mut x = Cfg::False;
434 assert_eq!(x, Cfg::False);
436 x = word_cfg("test");
438 assert_eq!(x, Cfg::False);
440 x = word_cfg("test2");
442 assert_eq!(x, word_cfg("test2"));
445 x &= word_cfg("test3");
446 assert_eq!(x, word_cfg("test3"));
448 x &= word_cfg("test4");
449 assert_eq!(x, Cfg::All(vec![word_cfg("test3"), word_cfg("test4")]));
451 x &= word_cfg("test5");
452 assert_eq!(x, Cfg::All(vec![word_cfg("test3"), word_cfg("test4"), word_cfg("test5")]));
454 x &= Cfg::All(vec![word_cfg("test6"), word_cfg("test7")]);
455 assert_eq!(x, Cfg::All(vec![
463 let mut y = Cfg::Any(vec![word_cfg("a"), word_cfg("b")]);
465 assert_eq!(y, Cfg::All(vec![
471 Cfg::Any(vec![word_cfg("a"), word_cfg("b")]),
475 word_cfg("a") & word_cfg("b") & word_cfg("c"),
476 Cfg::All(vec![word_cfg("a"), word_cfg("b"), word_cfg("c")])
484 let mut x = Cfg::True;
486 assert_eq!(x, Cfg::True);
488 x = word_cfg("test");
490 assert_eq!(x, Cfg::True);
492 x = word_cfg("test2");
494 assert_eq!(x, word_cfg("test2"));
497 x |= word_cfg("test3");
498 assert_eq!(x, word_cfg("test3"));
500 x |= word_cfg("test4");
501 assert_eq!(x, Cfg::Any(vec![word_cfg("test3"), word_cfg("test4")]));
503 x |= word_cfg("test5");
504 assert_eq!(x, Cfg::Any(vec![word_cfg("test3"), word_cfg("test4"), word_cfg("test5")]));
506 x |= Cfg::Any(vec![word_cfg("test6"), word_cfg("test7")]);
507 assert_eq!(x, Cfg::Any(vec![
515 let mut y = Cfg::All(vec![word_cfg("a"), word_cfg("b")]);
517 assert_eq!(y, Cfg::Any(vec![
523 Cfg::All(vec![word_cfg("a"), word_cfg("b")]),
527 word_cfg("a") | word_cfg("b") | word_cfg("c"),
528 Cfg::Any(vec![word_cfg("a"), word_cfg("b"), word_cfg("c")])
537 name: Symbol::intern("all"),
538 node: MetaItemKind::Word,
541 assert_eq!(Cfg::parse(&mi), Ok(word_cfg("all")));
544 name: Symbol::intern("all"),
545 node: MetaItemKind::NameValue(dummy_spanned(LitKind::Str(
546 Symbol::intern("done"),
551 assert_eq!(Cfg::parse(&mi), Ok(name_value_cfg("all", "done")));
554 name: Symbol::intern("all"),
555 node: MetaItemKind::List(vec![
556 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
557 name: Symbol::intern("a"),
558 node: MetaItemKind::Word,
561 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
562 name: Symbol::intern("b"),
563 node: MetaItemKind::Word,
569 assert_eq!(Cfg::parse(&mi), Ok(word_cfg("a") & word_cfg("b")));
572 name: Symbol::intern("any"),
573 node: MetaItemKind::List(vec![
574 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
575 name: Symbol::intern("a"),
576 node: MetaItemKind::Word,
579 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
580 name: Symbol::intern("b"),
581 node: MetaItemKind::Word,
587 assert_eq!(Cfg::parse(&mi), Ok(word_cfg("a") | word_cfg("b")));
590 name: Symbol::intern("not"),
591 node: MetaItemKind::List(vec![
592 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
593 name: Symbol::intern("a"),
594 node: MetaItemKind::Word,
600 assert_eq!(Cfg::parse(&mi), Ok(!word_cfg("a")));
603 name: Symbol::intern("not"),
604 node: MetaItemKind::List(vec![
605 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
606 name: Symbol::intern("any"),
607 node: MetaItemKind::List(vec![
608 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
609 name: Symbol::intern("a"),
610 node: MetaItemKind::Word,
613 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
614 name: Symbol::intern("all"),
615 node: MetaItemKind::List(vec![
616 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
617 name: Symbol::intern("b"),
618 node: MetaItemKind::Word,
621 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
622 name: Symbol::intern("c"),
623 node: MetaItemKind::Word,
635 assert_eq!(Cfg::parse(&mi), Ok(!(word_cfg("a") | (word_cfg("b") & word_cfg("c")))));
638 name: Symbol::intern("all"),
639 node: MetaItemKind::List(vec![
640 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
641 name: Symbol::intern("a"),
642 node: MetaItemKind::Word,
645 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
646 name: Symbol::intern("b"),
647 node: MetaItemKind::Word,
650 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
651 name: Symbol::intern("c"),
652 node: MetaItemKind::Word,
658 assert_eq!(Cfg::parse(&mi), Ok(word_cfg("a") & word_cfg("b") & word_cfg("c")));
663 fn test_parse_err() {
666 name: Symbol::intern("foo"),
667 node: MetaItemKind::NameValue(dummy_spanned(LitKind::Bool(false))),
670 assert!(Cfg::parse(&mi).is_err());
673 name: Symbol::intern("not"),
674 node: MetaItemKind::List(vec![
675 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
676 name: Symbol::intern("a"),
677 node: MetaItemKind::Word,
680 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
681 name: Symbol::intern("b"),
682 node: MetaItemKind::Word,
688 assert!(Cfg::parse(&mi).is_err());
691 name: Symbol::intern("not"),
692 node: MetaItemKind::List(vec![]),
695 assert!(Cfg::parse(&mi).is_err());
698 name: Symbol::intern("foo"),
699 node: MetaItemKind::List(vec![
700 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
701 name: Symbol::intern("a"),
702 node: MetaItemKind::Word,
708 assert!(Cfg::parse(&mi).is_err());
711 name: Symbol::intern("all"),
712 node: MetaItemKind::List(vec![
713 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
714 name: Symbol::intern("foo"),
715 node: MetaItemKind::List(vec![]),
718 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
719 name: Symbol::intern("b"),
720 node: MetaItemKind::Word,
726 assert!(Cfg::parse(&mi).is_err());
729 name: Symbol::intern("any"),
730 node: MetaItemKind::List(vec![
731 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
732 name: Symbol::intern("a"),
733 node: MetaItemKind::Word,
736 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
737 name: Symbol::intern("foo"),
738 node: MetaItemKind::List(vec![]),
744 assert!(Cfg::parse(&mi).is_err());
747 name: Symbol::intern("not"),
748 node: MetaItemKind::List(vec![
749 dummy_spanned(NestedMetaItemKind::MetaItem(MetaItem {
750 name: Symbol::intern("foo"),
751 node: MetaItemKind::List(vec![]),
757 assert!(Cfg::parse(&mi).is_err());
762 fn test_render_short_html() {
765 word_cfg("unix").render_short_html(),
769 name_value_cfg("target_os", "macos").render_short_html(),
773 name_value_cfg("target_pointer_width", "16").render_short_html(),
777 name_value_cfg("target_endian", "little").render_short_html(),
781 (!word_cfg("windows")).render_short_html(),
785 (word_cfg("unix") & word_cfg("windows")).render_short_html(),
789 (word_cfg("unix") | word_cfg("windows")).render_short_html(),
794 word_cfg("unix") & word_cfg("windows") & word_cfg("debug_assertions")
795 ).render_short_html(),
796 "Unix and Windows and debug-assertions enabled"
800 word_cfg("unix") | word_cfg("windows") | word_cfg("debug_assertions")
801 ).render_short_html(),
802 "Unix or Windows or debug-assertions enabled"
806 !(word_cfg("unix") | word_cfg("windows") | word_cfg("debug_assertions"))
807 ).render_short_html(),
808 "Neither Unix nor Windows nor debug-assertions enabled"
812 (word_cfg("unix") & name_value_cfg("target_arch", "x86_64")) |
813 (word_cfg("windows") & name_value_cfg("target_pointer_width", "64"))
814 ).render_short_html(),
815 "Unix and x86-64, or Windows and 64-bit"
818 (!(word_cfg("unix") & word_cfg("windows"))).render_short_html(),
819 "Not (Unix and Windows)"
823 (word_cfg("debug_assertions") | word_cfg("windows")) & word_cfg("unix")
824 ).render_short_html(),
825 "(Debug-assertions enabled or Windows) and Unix"
831 fn test_render_long_html() {
834 word_cfg("unix").render_long_html(),
835 "This is supported on <strong>Unix</strong> only."
838 name_value_cfg("target_os", "macos").render_long_html(),
839 "This is supported on <strong>macOS</strong> only."
842 name_value_cfg("target_pointer_width", "16").render_long_html(),
843 "This is supported on <strong>16-bit</strong> only."
846 name_value_cfg("target_endian", "little").render_long_html(),
847 "This is supported on <strong>little-endian</strong> only."
850 (!word_cfg("windows")).render_long_html(),
851 "This is supported on <strong>non-Windows</strong> only."
854 (word_cfg("unix") & word_cfg("windows")).render_long_html(),
855 "This is supported on <strong>Unix and Windows</strong> only."
858 (word_cfg("unix") | word_cfg("windows")).render_long_html(),
859 "This is supported on <strong>Unix or Windows</strong> only."
863 word_cfg("unix") & word_cfg("windows") & word_cfg("debug_assertions")
864 ).render_long_html(),
865 "This is supported on <strong>Unix and Windows and debug-assertions enabled\
870 word_cfg("unix") | word_cfg("windows") | word_cfg("debug_assertions")
871 ).render_long_html(),
872 "This is supported on <strong>Unix or Windows or debug-assertions enabled\
877 !(word_cfg("unix") | word_cfg("windows") | word_cfg("debug_assertions"))
878 ).render_long_html(),
879 "This is supported on <strong>neither Unix nor Windows nor debug-assertions \
884 (word_cfg("unix") & name_value_cfg("target_arch", "x86_64")) |
885 (word_cfg("windows") & name_value_cfg("target_pointer_width", "64"))
886 ).render_long_html(),
887 "This is supported on <strong>Unix and x86-64, or Windows and 64-bit</strong> \
891 (!(word_cfg("unix") & word_cfg("windows"))).render_long_html(),
892 "This is supported on <strong>not (Unix and Windows)</strong>."
896 (word_cfg("debug_assertions") | word_cfg("windows")) & word_cfg("unix")
897 ).render_long_html(),
898 "This is supported on <strong>(debug-assertions enabled or Windows) and Unix\