1use std::str::FromStr;
7use std::sync::Arc;
8use std::{fmt, mem, ops};
9
10use itertools::Either;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
13use rustc_hir as hir;
14use rustc_hir::Attribute;
15use rustc_hir::attrs::{self, AttributeKind, CfgEntry, CfgHideShow, HideOrShow};
16use rustc_middle::ty::TyCtxt;
17use rustc_span::symbol::{Symbol, sym};
18use rustc_span::{DUMMY_SP, Span};
19use rustc_target::spec;
20
21use crate::display::{Joined as _, MaybeDisplay, Wrapped};
22use crate::html::escape::Escape;
23
24#[cfg(test)]
25mod tests;
26
27#[derive(Clone, Debug, Hash)]
28#[cfg_attr(test, derive(PartialEq))]
31pub(crate) struct Cfg(CfgEntry);
32
33fn is_simple_cfg(cfg: &CfgEntry) -> bool {
35 match cfg {
36 CfgEntry::Bool(..)
37 | CfgEntry::NameValue { .. }
38 | CfgEntry::Not(..)
39 | CfgEntry::Version(..) => true,
40 CfgEntry::All(..) | CfgEntry::Any(..) => false,
41 }
42}
43
44fn is_any_cfg(cfg: &CfgEntry) -> bool {
46 match cfg {
47 CfgEntry::Bool(..)
48 | CfgEntry::NameValue { .. }
49 | CfgEntry::Not(..)
50 | CfgEntry::Version(..)
51 | CfgEntry::All(..) => false,
52 CfgEntry::Any(..) => true,
53 }
54}
55
56fn strip_hidden(cfg: &CfgEntry, hidden: &FxHashSet<NameValueCfg>) -> Option<CfgEntry> {
57 match cfg {
58 CfgEntry::Bool(..) => Some(cfg.clone()),
59 CfgEntry::NameValue { .. } => {
60 if !hidden.contains(&NameValueCfg::from(cfg)) {
61 Some(cfg.clone())
62 } else {
63 None
64 }
65 }
66 CfgEntry::Not(cfg, _) => {
67 if let Some(cfg) = strip_hidden(cfg, hidden) {
68 Some(CfgEntry::Not(Box::new(cfg), DUMMY_SP))
69 } else {
70 None
71 }
72 }
73 CfgEntry::Any(cfgs, _) => {
74 let cfgs =
75 cfgs.iter().filter_map(|cfg| strip_hidden(cfg, hidden)).collect::<ThinVec<_>>();
76 if cfgs.is_empty() { None } else { Some(CfgEntry::Any(cfgs, DUMMY_SP)) }
77 }
78 CfgEntry::All(cfgs, _) => {
79 let cfgs =
80 cfgs.iter().filter_map(|cfg| strip_hidden(cfg, hidden)).collect::<ThinVec<_>>();
81 if cfgs.is_empty() { None } else { Some(CfgEntry::All(cfgs, DUMMY_SP)) }
82 }
83 CfgEntry::Version(..) => {
84 Some(cfg.clone())
86 }
87 }
88}
89
90fn should_capitalize_first_letter(cfg: &CfgEntry) -> bool {
91 match cfg {
92 CfgEntry::Bool(..) | CfgEntry::Not(..) | CfgEntry::Version(..) => true,
93 CfgEntry::Any(sub_cfgs, _) | CfgEntry::All(sub_cfgs, _) => {
94 sub_cfgs.first().map(should_capitalize_first_letter).unwrap_or(false)
95 }
96 CfgEntry::NameValue { name, .. } => {
97 *name == sym::debug_assertions || *name == sym::target_endian
98 }
99 }
100}
101
102impl Cfg {
103 pub(crate) fn render_short_html(&self) -> String {
105 let mut msg = Display(&self.0, Format::ShortHtml).to_string();
106 if should_capitalize_first_letter(&self.0)
107 && let Some(i) = msg.find(|c: char| c.is_ascii_alphanumeric())
108 {
109 msg[i..i + 1].make_ascii_uppercase();
110 }
111 msg
112 }
113
114 fn render_long_inner(&self, format: Format) -> String {
115 let on = if self.omit_preposition() {
116 " "
117 } else if self.should_use_with_in_description() {
118 " with "
119 } else {
120 " on "
121 };
122
123 let mut msg = if matches!(format, Format::LongHtml) {
124 format!("Available{on}<strong>{}</strong>", Display(&self.0, format))
125 } else {
126 format!("Available{on}{}", Display(&self.0, format))
127 };
128 if self.should_append_only_to_description() {
129 msg.push_str(" only");
130 }
131 msg
132 }
133
134 pub(crate) fn render_long_html(&self) -> String {
136 let mut msg = self.render_long_inner(Format::LongHtml);
137 msg.push('.');
138 msg
139 }
140
141 pub(crate) fn render_long_plain(&self) -> String {
143 self.render_long_inner(Format::LongPlain)
144 }
145
146 fn should_append_only_to_description(&self) -> bool {
147 match self.0 {
148 CfgEntry::Any(..)
149 | CfgEntry::All(..)
150 | CfgEntry::NameValue { .. }
151 | CfgEntry::Version(..)
152 | CfgEntry::Not(box CfgEntry::NameValue { .. }, _) => true,
153 CfgEntry::Not(..) | CfgEntry::Bool(..) => false,
154 }
155 }
156
157 fn should_use_with_in_description(&self) -> bool {
158 matches!(self.0, CfgEntry::NameValue { name, .. } if name == sym::target_feature)
159 }
160
161 pub(crate) fn simplify_with(&self, assume: &Self) -> Option<Self> {
167 if self.0.is_equivalent_to(&assume.0) {
168 None
169 } else if let CfgEntry::All(a, _) = &self.0 {
170 let mut sub_cfgs: ThinVec<CfgEntry> = if let CfgEntry::All(b, _) = &assume.0 {
171 a.iter().filter(|a| !b.iter().any(|b| a.is_equivalent_to(b))).cloned().collect()
172 } else {
173 a.iter().filter(|&a| !a.is_equivalent_to(&assume.0)).cloned().collect()
174 };
175 let len = sub_cfgs.len();
176 match len {
177 0 => None,
178 1 => sub_cfgs.pop().map(Cfg),
179 _ => Some(Cfg(CfgEntry::All(sub_cfgs, DUMMY_SP))),
180 }
181 } else if let CfgEntry::All(b, _) = &assume.0
182 && b.iter().any(|b| b.is_equivalent_to(&self.0))
183 {
184 None
185 } else {
186 Some(self.clone())
187 }
188 }
189
190 fn omit_preposition(&self) -> bool {
191 matches!(self.0, CfgEntry::Bool(..))
192 }
193
194 pub(crate) fn inner(&self) -> &CfgEntry {
195 &self.0
196 }
197}
198
199impl ops::Not for Cfg {
200 type Output = Cfg;
201 fn not(self) -> Cfg {
202 Cfg(match self.0 {
203 CfgEntry::Bool(v, s) => CfgEntry::Bool(!v, s),
204 CfgEntry::Not(cfg, _) => *cfg,
205 s => CfgEntry::Not(Box::new(s), DUMMY_SP),
206 })
207 }
208}
209
210impl ops::BitAndAssign for Cfg {
211 fn bitand_assign(&mut self, other: Cfg) {
212 match (&mut self.0, other.0) {
213 (CfgEntry::Bool(false, _), _) | (_, CfgEntry::Bool(true, _)) => {}
214 (s, CfgEntry::Bool(false, _)) => *s = CfgEntry::Bool(false, DUMMY_SP),
215 (s @ CfgEntry::Bool(true, _), b) => *s = b,
216 (CfgEntry::All(a, _), CfgEntry::All(ref mut b, _)) => {
217 for c in b.drain(..) {
218 if !a.iter().any(|a| a.is_equivalent_to(&c)) {
219 a.push(c);
220 }
221 }
222 }
223 (CfgEntry::All(a, _), ref mut b) => {
224 if !a.iter().any(|a| a.is_equivalent_to(b)) {
225 a.push(mem::replace(b, CfgEntry::Bool(true, DUMMY_SP)));
226 }
227 }
228 (s, CfgEntry::All(mut a, _)) => {
229 let b = mem::replace(s, CfgEntry::Bool(true, DUMMY_SP));
230 if !a.iter().any(|a| a.is_equivalent_to(&b)) {
231 a.push(b);
232 }
233 *s = CfgEntry::All(a, DUMMY_SP);
234 }
235 (s, b) => {
236 if !s.is_equivalent_to(&b) {
237 let a = mem::replace(s, CfgEntry::Bool(true, DUMMY_SP));
238 *s = CfgEntry::All(thin_vec![a, b], DUMMY_SP);
239 }
240 }
241 }
242 }
243}
244
245impl ops::BitAnd for Cfg {
246 type Output = Cfg;
247 fn bitand(mut self, other: Cfg) -> Cfg {
248 self &= other;
249 self
250 }
251}
252
253impl ops::BitOrAssign for Cfg {
254 fn bitor_assign(&mut self, other: Cfg) {
255 match (&mut self.0, other.0) {
256 (CfgEntry::Bool(true, _), _)
257 | (_, CfgEntry::Bool(false, _))
258 | (_, CfgEntry::Bool(true, _)) => {}
259 (s @ CfgEntry::Bool(false, _), b) => *s = b,
260 (CfgEntry::Any(a, _), CfgEntry::Any(ref mut b, _)) => {
261 for c in b.drain(..) {
262 if !a.iter().any(|a| a.is_equivalent_to(&c)) {
263 a.push(c);
264 }
265 }
266 }
267 (CfgEntry::Any(a, _), ref mut b) => {
268 if !a.iter().any(|a| a.is_equivalent_to(b)) {
269 a.push(mem::replace(b, CfgEntry::Bool(true, DUMMY_SP)));
270 }
271 }
272 (s, CfgEntry::Any(mut a, _)) => {
273 let b = mem::replace(s, CfgEntry::Bool(true, DUMMY_SP));
274 if !a.iter().any(|a| a.is_equivalent_to(&b)) {
275 a.push(b);
276 }
277 *s = CfgEntry::Any(a, DUMMY_SP);
278 }
279 (s, b) => {
280 if !s.is_equivalent_to(&b) {
281 let a = mem::replace(s, CfgEntry::Bool(true, DUMMY_SP));
282 *s = CfgEntry::Any(thin_vec![a, b], DUMMY_SP);
283 }
284 }
285 }
286 }
287}
288
289impl ops::BitOr for Cfg {
290 type Output = Cfg;
291 fn bitor(mut self, other: Cfg) -> Cfg {
292 self |= other;
293 self
294 }
295}
296
297#[derive(Clone, Copy)]
298enum Format {
299 LongHtml,
300 LongPlain,
301 ShortHtml,
302}
303
304impl Format {
305 fn is_long(self) -> bool {
306 match self {
307 Format::LongHtml | Format::LongPlain => true,
308 Format::ShortHtml => false,
309 }
310 }
311
312 fn is_html(self) -> bool {
313 match self {
314 Format::LongHtml | Format::ShortHtml => true,
315 Format::LongPlain => false,
316 }
317 }
318
319 fn escape(self, s: &str) -> impl fmt::Display {
320 if self.is_html() { Either::Left(Escape(s)) } else { Either::Right(s) }
321 }
322}
323
324struct Display<'a>(&'a CfgEntry, Format);
326
327impl Display<'_> {
328 fn code_wrappers(&self) -> Wrapped<&'static str> {
329 if self.1.is_html() { Wrapped::with("<code>", "</code>") } else { Wrapped::with("`", "`") }
330 }
331
332 fn display_sub_cfgs(
333 &self,
334 fmt: &mut fmt::Formatter<'_>,
335 sub_cfgs: &[CfgEntry],
336 separator: &str,
337 ) -> fmt::Result {
338 use fmt::Display as _;
339
340 let short_longhand = self.1.is_long() && {
341 let all_crate_features = sub_cfgs.iter().all(|sub_cfg| {
342 matches!(sub_cfg, CfgEntry::NameValue { name: sym::feature, value: Some(_), .. })
343 });
344 let all_target_features = sub_cfgs.iter().all(|sub_cfg| {
345 matches!(
346 sub_cfg,
347 CfgEntry::NameValue { name: sym::target_feature, value: Some(_), .. }
348 )
349 });
350
351 if all_crate_features {
352 fmt.write_str("crate features ")?;
353 true
354 } else if all_target_features {
355 fmt.write_str("target features ")?;
356 true
357 } else {
358 false
359 }
360 };
361
362 fmt::from_fn(|f| {
363 sub_cfgs
364 .iter()
365 .map(|sub_cfg| {
366 if let CfgEntry::NameValue { value: Some(feat), .. } = sub_cfg
367 && short_longhand
368 {
369 Either::Left(self.code_wrappers().wrap(feat))
370 } else {
371 Either::Right(
372 Wrapped::with_parens()
373 .when(is_any_cfg(sub_cfg))
374 .wrap(Display(sub_cfg, self.1)),
375 )
376 }
377 })
378 .joined(separator, f)
379 })
380 .fmt(fmt)?;
381
382 Ok(())
383 }
384}
385
386impl fmt::Display for Display<'_> {
387 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
388 match &self.0 {
389 CfgEntry::Not(box CfgEntry::Any(sub_cfgs, _), _) => {
390 let separator = if sub_cfgs.iter().all(is_simple_cfg) { " nor " } else { ", nor " };
391 fmt.write_str("neither ")?;
392
393 sub_cfgs
394 .iter()
395 .map(|sub_cfg| {
396 Wrapped::with_parens()
397 .when(is_any_cfg(sub_cfg))
398 .wrap(Display(sub_cfg, self.1))
399 })
400 .joined(separator, fmt)
401 }
402 CfgEntry::Not(box simple @ CfgEntry::NameValue { .. }, _) => {
403 write!(fmt, "non-{}", Display(simple, self.1))
404 }
405 CfgEntry::Not(box c, _) => write!(fmt, "not ({})", Display(c, self.1)),
406
407 CfgEntry::Any(sub_cfgs, _) => {
408 let separator = if sub_cfgs.iter().all(is_simple_cfg) { " or " } else { ", or " };
409 self.display_sub_cfgs(fmt, sub_cfgs.as_slice(), separator)
410 }
411 CfgEntry::All(sub_cfgs, _) => self.display_sub_cfgs(fmt, sub_cfgs.as_slice(), " and "),
412
413 CfgEntry::Bool(v, _) => {
414 if *v {
415 fmt.write_str("everywhere")
416 } else {
417 fmt.write_str("nowhere")
418 }
419 }
420
421 &CfgEntry::NameValue { name, value, .. } => {
422 let human_readable = match (*name, value) {
423 (sym::unix, None) => "Unix",
424 (sym::windows, None) => "Windows",
425 (sym::debug_assertions, None) => "debug-assertions enabled",
426 (sym::target_object_format, Some(format)) => match self.1 {
427 Format::LongHtml => {
428 return write!(fmt, "object format <code>{format}</code>");
429 }
430 Format::LongPlain => return write!(fmt, "object format `{format}`"),
431 Format::ShortHtml => return write!(fmt, "<code>{format}</code>"),
432 },
433 (sym::target_os, Some(os)) => human_readable_target_os(*os).unwrap_or_default(),
434 (sym::target_arch, Some(arch)) => {
435 human_readable_target_arch(*arch).unwrap_or_default()
436 }
437 (sym::target_vendor, Some(vendor)) => match vendor.as_str() {
438 "apple" => "Apple",
439 "pc" => "PC",
440 "sun" => "Sun",
441 "fortanix" => "Fortanix",
442 _ => "",
443 },
444 (sym::target_env, Some(env)) => {
445 human_readable_target_env(*env).unwrap_or_default()
446 }
447 (sym::target_endian, Some(endian)) => {
448 return write!(fmt, "{endian}-endian");
449 }
450 (sym::target_pointer_width, Some(bits)) => {
451 return write!(fmt, "{bits}-bit");
452 }
453 (sym::target_feature, Some(feat)) => match self.1 {
454 Format::LongHtml => {
455 return write!(fmt, "target feature <code>{feat}</code>");
456 }
457 Format::LongPlain => return write!(fmt, "target feature `{feat}`"),
458 Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
459 },
460 (sym::feature, Some(feat)) => match self.1 {
461 Format::LongHtml => {
462 return write!(fmt, "crate feature <code>{feat}</code>");
463 }
464 Format::LongPlain => return write!(fmt, "crate feature `{feat}`"),
465 Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
466 },
467 _ => "",
468 };
469 if !human_readable.is_empty() {
470 fmt.write_str(human_readable)
471 } else {
472 let value = value
473 .map(|v| fmt::from_fn(move |f| write!(f, "={}", self.1.escape(v.as_str()))))
474 .maybe_display();
475 self.code_wrappers()
476 .wrap(format_args!("{}{value}", self.1.escape(name.as_str())))
477 .fmt(fmt)
478 }
479 }
480
481 CfgEntry::Version(..) => {
482 Ok(())
484 }
485 }
486 }
487}
488
489fn human_readable_target_os(os: Symbol) -> Option<&'static str> {
490 let os = spec::Os::from_str(os.as_str()).ok()?;
491
492 use spec::Os::*;
493 Some(match os {
494 Aix => "AIX",
496 AmdHsa => "AMD HSA",
497 Android => "Android",
498 Cuda => "CUDA",
499 Cygwin => "Cygwin",
500 Dragonfly => "DragonFly BSD",
501 Emscripten => "Emscripten",
502 EspIdf => "ESP-IDF",
503 FreeBsd => "FreeBSD",
504 Fuchsia => "Fuchsia",
505 Haiku => "Haiku",
506 HelenOs => "HelenOS",
507 Hermit => "Hermit",
508 Horizon => "Horizon",
509 Hurd => "GNU/Hurd",
510 IOs => "iOS",
511 Illumos => "illumos",
512 L4Re => "L4Re",
513 Linux => "Linux",
514 LynxOs178 => "LynxOS-178",
515 MacOs => "macOS",
516 Managarm => "Managarm",
517 Motor => "Motor OS",
518 NetBsd => "NetBSD",
519 None => "bare-metal", Nto => "QNX Neutrino",
521 NuttX => "NuttX",
522 OpenBsd => "OpenBSD",
523 Psp => "Play Station Portable",
524 Psx => "Play Station 1",
525 Qurt => "QuRT",
526 Redox => "Redox OS",
527 Rtems => "RTEMS OS",
528 Solaris => "Solaris",
529 SolidAsp3 => "SOLID ASP3",
530 TeeOs => "TEEOS",
531 Trusty => "Trusty",
532 TvOs => "tvOS",
533 Uefi => "UEFI",
534 VexOs => "VEXos",
535 VisionOs => "visionOS",
536 Vita => "Play Station Vita",
537 VxWorks => "VxWorks",
538 Wasi => "WASI",
539 WatchOs => "watchOS",
540 Windows => "Windows",
541 Xous => "Xous",
542 Zkvm => "zero knowledge Virtual Machine",
543 Unknown | Other(_) => return Option::None,
545 })
546}
547
548fn human_readable_target_arch(os: Symbol) -> Option<&'static str> {
549 let arch = spec::Arch::from_str(os.as_str()).ok()?;
550
551 use spec::Arch::*;
552 Some(match arch {
553 AArch64 => "AArch64",
555 AmdGpu => "AMG GPU",
556 Arm => "ARM",
557 Arm64EC => "ARM64EC",
558 Avr => "AVR",
559 Bpf => "BPF",
560 CSky => "C-SKY",
561 Hexagon => "Hexagon",
562 LoongArch32 => "LoongArch64",
563 LoongArch64 => "LoongArch32",
564 M68k => "Motorola 680x0",
565 Mips => "MIPS",
566 Mips32r6 => "MIPS release 6",
567 Mips64 => "MIPS-64",
568 Mips64r6 => "MIPS-64 release 6",
569 Msp430 => "MSP430",
570 Nvptx64 => "NVidia GPU",
571 PowerPC => "PowerPC",
572 PowerPC64 => "PowerPC64",
573 RiscV32 => "RISC-V RV32",
574 RiscV64 => "RISC-V RV64",
575 S390x => "s390x",
576 Sparc => "SPARC",
577 Sparc64 => "SPARC-64",
578 SpirV => "SPIR-V",
579 Wasm32 | Wasm64 => "WebAssembly",
580 X86 => "x86",
581 X86_64 => "x86-64",
582 Xtensa => "Xtensa",
583 Other(_) => return None,
585 })
586}
587
588fn human_readable_target_env(env: Symbol) -> Option<&'static str> {
589 let env = spec::Env::from_str(env.as_str()).ok()?;
590
591 use spec::Env::*;
592 Some(match env {
593 Gnu => "GNU",
595 MacAbi => "Catalyst",
596 Mlibc => "mac ABI",
597 Msvc => "MSVC",
598 Musl => "musl",
599 Newlib => "Newlib",
600 Nto70 => "Neutrino 7.0",
601 Nto71 => "Neutrino 7.1",
602 Nto71IoSock => "Neutrino 7.1 with io-sock",
603 Nto80 => "Neutrino 8.0",
604 Ohos => "OpenHarmony",
605 P1 => "WASIp1",
606 P2 => "WASIp2",
607 P3 => "WASIp3",
608 Relibc => "relibc",
609 Sgx => "SGX",
610 Sim => "Simulator",
611 Uclibc => "uClibc",
612 V5 => "V5",
613 Unspecified | Other(_) => return None,
615 })
616}
617
618#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
619struct NameValueCfg {
620 name: Symbol,
621 value: Option<Symbol>,
622}
623
624impl NameValueCfg {
625 fn new(name: Symbol) -> Self {
626 Self { name, value: None }
627 }
628}
629
630impl<'a> From<&'a CfgEntry> for NameValueCfg {
631 fn from(cfg: &'a CfgEntry) -> Self {
632 match cfg {
633 CfgEntry::NameValue { name, value, .. } => NameValueCfg { name: *name, value: *value },
634 _ => NameValueCfg { name: sym::empty, value: None },
635 }
636 }
637}
638
639impl<'a> From<&'a attrs::CfgInfo> for NameValueCfg {
640 fn from(cfg: &'a attrs::CfgInfo) -> Self {
641 Self { name: cfg.name, value: cfg.value.map(|(value, _)| value) }
642 }
643}
644
645#[derive(Clone, Debug)]
647pub(crate) struct CfgInfo {
648 hidden_cfg: FxHashSet<NameValueCfg>,
651 current_cfg: Cfg,
654 auto_cfg_active: bool,
656 parent_is_doc_cfg: bool,
660}
661
662impl Default for CfgInfo {
663 fn default() -> Self {
664 Self {
665 hidden_cfg: FxHashSet::from_iter([
666 NameValueCfg::new(sym::test),
667 NameValueCfg::new(sym::doc),
668 NameValueCfg::new(sym::doctest),
669 ]),
670 current_cfg: Cfg(CfgEntry::Bool(true, DUMMY_SP)),
671 auto_cfg_active: true,
672 parent_is_doc_cfg: false,
673 }
674 }
675}
676
677fn show_hide_show_conflict_error(
678 tcx: TyCtxt<'_>,
679 item_span: rustc_span::Span,
680 previous: rustc_span::Span,
681) {
682 let mut diag = tcx.sess.dcx().struct_span_err(
683 item_span,
684 format!(
685 "same `cfg` was in `auto_cfg(hide(...))` and `auto_cfg(show(...))` on the same item"
686 ),
687 );
688 diag.span_note(previous, "first change was here");
689 diag.emit();
690}
691
692fn handle_auto_cfg_hide_show(
700 tcx: TyCtxt<'_>,
701 cfg_info: &mut CfgInfo,
702 attr: &CfgHideShow,
703 new_show_attrs: &mut FxHashMap<(Symbol, Option<Symbol>), rustc_span::Span>,
704 new_hide_attrs: &mut FxHashMap<(Symbol, Option<Symbol>), rustc_span::Span>,
705) {
706 for value in &attr.values {
707 let simple = NameValueCfg::from(value);
708 if attr.kind == HideOrShow::Show {
709 if let Some(span) = new_hide_attrs.get(&(simple.name, simple.value)) {
710 show_hide_show_conflict_error(tcx, value.span_for_name_and_value(), *span);
711 } else {
712 new_show_attrs.insert((simple.name, simple.value), value.span_for_name_and_value());
713 }
714 cfg_info.hidden_cfg.remove(&simple);
715 } else {
716 if let Some(span) = new_show_attrs.get(&(simple.name, simple.value)) {
717 show_hide_show_conflict_error(tcx, value.span_for_name_and_value(), *span);
718 } else {
719 new_hide_attrs.insert((simple.name, simple.value), value.span_for_name_and_value());
720 }
721 cfg_info.hidden_cfg.insert(simple);
722 }
723 }
724}
725
726pub(crate) fn extract_cfg_from_attrs<'a, I: Iterator<Item = &'a hir::Attribute> + Clone>(
727 attrs: I,
728 tcx: TyCtxt<'_>,
729 cfg_info: &mut CfgInfo,
730) -> Option<Arc<Cfg>> {
731 fn check_changed_auto_active_status(
732 changed_auto_active_status: &mut Option<rustc_span::Span>,
733 attr_span: Span,
734 cfg_info: &mut CfgInfo,
735 tcx: TyCtxt<'_>,
736 new_value: bool,
737 ) -> bool {
738 if let Some(first_change) = changed_auto_active_status {
739 if cfg_info.auto_cfg_active != new_value {
740 tcx.sess
741 .dcx()
742 .struct_span_err(
743 vec![*first_change, attr_span],
744 "`auto_cfg` was disabled and enabled more than once on the same item",
745 )
746 .emit();
747 return true;
748 }
749 } else {
750 *changed_auto_active_status = Some(attr_span);
751 }
752 cfg_info.auto_cfg_active = new_value;
753 false
754 }
755
756 let mut new_show_attrs = FxHashMap::default();
757 let mut new_hide_attrs = FxHashMap::default();
758
759 let mut doc_cfg = attrs
760 .clone()
761 .filter_map(|attr| match attr {
762 Attribute::Parsed(AttributeKind::Doc(d)) if !d.cfg.is_empty() => Some(d),
763 _ => None,
764 })
765 .peekable();
766 if doc_cfg.peek().is_some() {
768 if !cfg_info.parent_is_doc_cfg {
770 cfg_info.current_cfg = Cfg(CfgEntry::Bool(true, DUMMY_SP));
771 cfg_info.parent_is_doc_cfg = true;
772 }
773 for attr in doc_cfg {
774 for new_cfg in attr.cfg.clone() {
775 cfg_info.current_cfg &= Cfg(new_cfg);
776 }
777 }
778 } else {
779 cfg_info.parent_is_doc_cfg = false;
780 }
781
782 let mut changed_auto_active_status = None;
783
784 for attr in attrs {
786 if let Attribute::Parsed(AttributeKind::Doc(d)) = attr {
787 for (new_value, span) in &d.auto_cfg_change {
788 if check_changed_auto_active_status(
789 &mut changed_auto_active_status,
790 *span,
791 cfg_info,
792 tcx,
793 *new_value,
794 ) {
795 return None;
796 }
797 }
798 if let Some((_, span)) = d.auto_cfg.first() {
799 if check_changed_auto_active_status(
800 &mut changed_auto_active_status,
801 *span,
802 cfg_info,
803 tcx,
804 true,
805 ) {
806 return None;
807 }
808 for (value, _) in &d.auto_cfg {
809 handle_auto_cfg_hide_show(
810 tcx,
811 cfg_info,
812 value,
813 &mut new_show_attrs,
814 &mut new_hide_attrs,
815 );
816 }
817 }
818 } else if let hir::Attribute::Parsed(AttributeKind::TargetFeature { features, .. }) = attr {
819 for (feature, _) in features {
822 cfg_info.current_cfg &= Cfg(CfgEntry::NameValue {
823 name: sym::target_feature,
824 value: Some(*feature),
825 span: DUMMY_SP,
826 });
827 }
828 continue;
829 } else if !cfg_info.parent_is_doc_cfg
830 && let hir::Attribute::Parsed(AttributeKind::CfgTrace(cfgs)) = attr
831 {
832 for (new_cfg, _) in cfgs {
833 cfg_info.current_cfg &= Cfg(new_cfg.clone());
834 }
835 }
836 }
837
838 if !cfg_info.auto_cfg_active && !cfg_info.parent_is_doc_cfg {
841 None
842 } else if cfg_info.parent_is_doc_cfg {
843 if matches!(cfg_info.current_cfg.0, CfgEntry::Bool(true, _)) {
844 None
845 } else {
846 Some(Arc::new(cfg_info.current_cfg.clone()))
847 }
848 } else {
849 match strip_hidden(&cfg_info.current_cfg.0, &cfg_info.hidden_cfg) {
852 None | Some(CfgEntry::Bool(true, _)) => None,
853 Some(cfg) => Some(Arc::new(Cfg(cfg))),
854 }
855 }
856}