1use std::fmt;
7
8use purrdf_lex::allocation::Memory;
9use syn::{Expr, ExprLit, Lit, Meta};
10
11use crate::cfg::{CfgExpr, parse_list};
12use crate::facts::{AttrFact, ModBody};
13use crate::index::Index;
14use crate::meter::{ItemAdmission, Meter};
15use crate::{
16 ItemId, LoadError, LoadErrorKind, LoadOptions, RelPath, SourceFile, SymbolKind, Workspace,
17};
18
19#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct CompilerPlatform {
22 os: String,
23 families: Vec<String>,
24 unix: bool,
25 windows: bool,
26}
27
28#[derive(Debug)]
30#[non_exhaustive]
31pub enum CompilerPlatformError {
32 Syntax {
34 line: String,
36 source: syn::Error,
38 },
39 NonStringValue {
41 line: String,
43 },
44 NonAtomic {
46 line: String,
48 },
49 MissingOs,
51 MultipleOs,
53}
54
55impl fmt::Display for CompilerPlatformError {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 match self {
58 Self::Syntax { line, source } => write!(f, "invalid compiler cfg {line:?}: {source}"),
59 Self::NonStringValue { line } => {
60 write!(f, "compiler cfg value is not a string: {line:?}")
61 }
62 Self::NonAtomic { line } => write!(f, "compiler cfg is not atomic: {line:?}"),
63 Self::MissingOs => f.write_str("compiler cfg is missing target_os"),
64 Self::MultipleOs => f.write_str("compiler cfg contains multiple target_os entries"),
65 }
66 }
67}
68
69impl std::error::Error for CompilerPlatformError {
70 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
71 match self {
72 Self::Syntax { source, .. } => Some(source),
73 _ => None,
74 }
75 }
76}
77
78impl fmt::Display for CompilerPlatform {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 write!(
81 f,
82 "target_os={:?}, target_family={:?}, unix={}, windows={}",
83 self.os, self.families, self.unix, self.windows
84 )
85 }
86}
87
88impl CompilerPlatform {
89 pub fn parse(output: &str) -> Result<Self, CompilerPlatformError> {
94 let mut os = None;
95 let mut families = Vec::new();
96 let mut unix = false;
97 let mut windows = false;
98 for line in output.lines().filter(|line| !line.trim().is_empty()) {
99 let meta: Meta =
100 syn::parse_str(line).map_err(|source| CompilerPlatformError::Syntax {
101 line: line.to_owned(),
102 source,
103 })?;
104 match meta {
105 Meta::Path(path) => {
106 unix |= path.is_ident("unix");
107 windows |= path.is_ident("windows");
108 }
109 Meta::NameValue(pair) => {
110 let Expr::Lit(ExprLit {
111 lit: Lit::Str(value),
112 ..
113 }) = pair.value
114 else {
115 return Err(CompilerPlatformError::NonStringValue {
116 line: line.to_owned(),
117 });
118 };
119 if pair.path.is_ident("target_os") {
120 if os.replace(value.value()).is_some() {
121 return Err(CompilerPlatformError::MultipleOs);
122 }
123 } else if pair.path.is_ident("target_family") {
124 families.push(value.value());
125 }
126 }
127 Meta::List(_) => {
128 return Err(CompilerPlatformError::NonAtomic {
129 line: line.to_owned(),
130 });
131 }
132 }
133 }
134 Ok(Self {
135 os: os.ok_or(CompilerPlatformError::MissingOs)?,
136 families,
137 unix,
138 windows,
139 })
140 }
141}
142
143#[derive(Debug)]
148pub struct TestPlatformGuard<'w> {
149 attrs: Vec<&'w AttrFact>,
150 uncertain: bool,
151}
152
153impl TestPlatformGuard<'_> {
154 #[must_use]
156 pub fn has_platform_condition(&self) -> bool {
157 self.attrs
158 .iter()
159 .any(|attr| attribute(attr).is_some_and(|meta| mentions_platform(&meta)))
160 }
161
162 #[must_use]
167 pub fn evaluate(&self, platform: &CompilerPlatform) -> Option<bool> {
168 if self.uncertain {
169 return None;
170 }
171 all(self
172 .attrs
173 .iter()
174 .map(|attr| attribute(attr).and_then(|meta| evaluate_attribute(&meta, platform))))
175 }
176}
177
178impl fmt::Display for TestPlatformGuard<'_> {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 f.write_str("all(")?;
181 for (index, attr) in self.attrs.iter().enumerate() {
182 if index != 0 {
183 f.write_str(", ")?;
184 }
185 write!(f, "{}{}", attr.path, attr.args)?;
186 }
187 if self.uncertain {
188 if !self.attrs.is_empty() {
189 f.write_str(", ")?;
190 }
191 f.write_str("unknown source route")?;
192 }
193 f.write_str(")")
194 }
195}
196
197fn attribute(attr: &AttrFact) -> Option<Meta> {
198 syn::parse_str(&format!("{}{}", attr.path, attr.args)).ok()
199}
200
201fn all(values: impl IntoIterator<Item = Option<bool>>) -> Option<bool> {
202 let mut unknown = false;
203 for value in values {
204 match value {
205 Some(false) => return Some(false),
206 None => unknown = true,
207 Some(true) => {}
208 }
209 }
210 (!unknown).then_some(true)
211}
212
213fn any(values: impl IntoIterator<Item = Option<bool>>) -> Option<bool> {
214 all(values.into_iter().map(|value| value.map(|value| !value))).map(|value| !value)
215}
216
217fn platform_atom(meta: &Meta, platform: &CompilerPlatform) -> Option<bool> {
218 match meta {
219 Meta::Path(path) if path.is_ident("unix") => Some(platform.unix),
220 Meta::Path(path) if path.is_ident("windows") => Some(platform.windows),
221 Meta::NameValue(pair) => {
222 let Expr::Lit(ExprLit {
223 lit: Lit::Str(value),
224 ..
225 }) = &pair.value
226 else {
227 return None;
228 };
229 if pair.path.is_ident("target_os") {
230 Some(value.value() == platform.os)
231 } else if pair.path.is_ident("target_family") {
232 Some(platform.families.contains(&value.value()))
233 } else {
234 None
235 }
236 }
237 _ => None,
238 }
239}
240
241fn evaluate(expr: &CfgExpr, platform: &CompilerPlatform) -> Option<bool> {
242 match expr {
243 CfgExpr::Other(text) => syn::parse_str(text)
244 .ok()
245 .and_then(|meta| platform_atom(&meta, platform)),
246 CfgExpr::Not(inner) => evaluate(inner, platform).map(|value| !value),
247 CfgExpr::All(values) if !values.is_empty() => {
248 all(values.iter().map(|value| evaluate(value, platform)))
249 }
250 CfgExpr::Any(values) if !values.is_empty() => {
251 any(values.iter().map(|value| evaluate(value, platform)))
252 }
253 CfgExpr::Boolean(_) | CfgExpr::Test | CfgExpr::All(_) | CfgExpr::Any(_) => None,
254 }
255}
256
257fn evaluate_attribute(meta: &Meta, platform: &CompilerPlatform) -> Option<bool> {
258 let Meta::List(list) = meta else {
259 return Some(true);
260 };
261 if !list.path.is_ident("cfg") && !list.path.is_ident("cfg_attr") {
262 return Some(true);
263 }
264 let parts = crate::cfg::parse_punctuated(&list.tokens).ok()?;
265 let condition = CfgExpr::from_meta_configured(parts.first()?).ok()?;
266 if list.path.is_ident("cfg") {
267 return (parts.len() == 1)
268 .then(|| evaluate(&condition, platform))
269 .flatten();
270 }
271 if parts.len() == 1 {
272 return parts.trailing_punct().then_some(true);
273 }
274 any([
276 evaluate(&condition, platform).map(|value| !value),
277 all(parts
278 .iter()
279 .skip(1)
280 .map(|part| evaluate_attribute(part, platform))),
281 ])
282}
283
284fn mentions_platform(meta: &Meta) -> bool {
285 match meta {
286 Meta::Path(path) => path.is_ident("unix") || path.is_ident("windows"),
287 Meta::NameValue(pair) => {
288 pair.path.is_ident("target_os") || pair.path.is_ident("target_family")
289 }
290 Meta::List(list) => {
291 parse_list(&list.tokens).is_ok_and(|parts| parts.iter().any(mentions_platform))
292 }
293 }
294}
295
296struct Builder<'w, 'm, 'a, 'g> {
297 attrs: Vec<&'w AttrFact>,
298 uncertain: bool,
299 memory: &'m mut Memory<'a, ItemAdmission<'g>>,
300 meter: &'g Meter,
301 file: &'g RelPath,
302}
303
304impl<'w> Builder<'w, '_, '_, '_> {
305 fn attrs(&mut self, attrs: &'w [AttrFact]) -> Result<(), LoadError> {
306 self.meter.work(attrs.len(), self.file, None)?;
307 for attr in attrs
308 .iter()
309 .filter(|attr| matches!(attr.path.as_str(), "cfg" | "cfg_attr"))
310 {
311 self.meter.work(
312 attr.path.len().saturating_add(attr.args.len()),
313 self.file,
314 None,
315 )?;
316 let meta = attribute(attr).ok_or_else(|| {
317 LoadError::new(
318 self.file,
319 None,
320 LoadErrorKind::Internal {
321 what: "retained cfg attribute is not valid metadata".into(),
322 },
323 )
324 })?;
325 validate_attribute(&meta).map_err(|what| {
326 LoadError::new(self.file, None, LoadErrorKind::Internal { what })
327 })?;
328 self.memory
329 .push(&mut self.attrs, attr)
330 .map_err(|error| LoadError::new(self.file, None, LoadErrorKind::Storage(error)))?;
331 }
332 Ok(())
333 }
334
335 fn site(&mut self, file: &'w SourceFile, start: usize, module: bool) -> Result<(), LoadError> {
336 self.attrs(&file.facts.attrs)?;
337 let mut body: &ModBody = &file.facts.body;
338 loop {
339 self.meter.work(
340 body.items.len().saturating_add(body.mods.len()),
341 self.file,
342 None,
343 )?;
344 if !module
345 && let Some(item) = body.items.iter().find(|item| item.span.start_byte == start)
346 {
347 return self.attrs(&item.attrs);
348 }
349 if module
350 && let Some(item) = body.mods.iter().find(|item| item.span.start_byte == start)
351 {
352 self.uncertain |= !item.paths.conditional.is_empty();
353 return self.attrs(&item.attrs);
354 }
355 let mut enclosing = body.mods.iter().chain(&body.blocks).filter(|item| {
356 item.inline.is_some() && item.span.start_byte <= start && start < item.span.end_byte
357 });
358 let Some(selected) = enclosing.next() else {
359 return Err(LoadError::new(
360 self.file,
361 None,
362 LoadErrorKind::Internal {
363 what: "indexed source item has no retained attribute site".into(),
364 },
365 ));
366 };
367 if enclosing.next().is_some() {
368 return Err(LoadError::new(
369 self.file,
370 None,
371 LoadErrorKind::Internal {
372 what: "retained inline module spans overlap".into(),
373 },
374 ));
375 }
376 self.uncertain |= !selected.paths.conditional.is_empty();
377 self.attrs(&selected.attrs)?;
378 body = selected.inline.as_ref().expect("selected inline module");
381 }
382 }
383}
384
385fn ordinary(kind: SymbolKind) -> bool {
386 matches!(
387 kind,
388 SymbolKind::Fn
389 | SymbolKind::Trait
390 | SymbolKind::Struct
391 | SymbolKind::Enum
392 | SymbolKind::Union
393 | SymbolKind::TypeAlias
394 | SymbolKind::Const
395 | SymbolKind::Static
396 | SymbolKind::ExternCrate
397 | SymbolKind::Mod
398 )
399}
400
401pub(crate) fn guard<'w>(
402 source: &'w Workspace,
403 id: ItemId,
404 index: &'w Index,
405 options: &LoadOptions,
406 used: usize,
407) -> Result<TestPlatformGuard<'w>, LoadError> {
408 let missing = || {
409 LoadError::new(
410 &RelPath::root(),
411 None,
412 LoadErrorKind::Internal {
413 what: "platform guard requires a valid indexed item and source context".into(),
414 },
415 )
416 };
417 let item = source.item(id).ok_or_else(missing)?;
418 let meter = Meter::new(options);
419 meter.items(used, &item.file, Some(item.name_line))?;
420 let mut admission = ItemAdmission::new(&meter, &item.file);
421 let result = (|| {
422 let mut memory = Memory::new(&mut admission);
423 let mut builder = Builder {
424 attrs: Vec::new(),
425 uncertain: false,
426 memory: &mut memory,
427 meter: &meter,
428 file: &item.file,
429 };
430 let file = source.file(&item.file).ok_or_else(missing)?;
431 builder
432 .meter
433 .work(index.root_items.len(), &item.file, Some(item.name_line))?;
434 let root = index.root_items.values().any(|root| *root == id);
435 let ordinary = ordinary(item.kind);
436 if root {
437 builder.attrs(&file.facts.attrs)?;
438 } else if ordinary {
439 builder.site(file, item.span.start_byte, item.kind == SymbolKind::Mod)?;
440 } else {
441 builder.uncertain = true;
443 }
444 let parent = item.path.rsplit_once("::").map(|(parent, _)| parent);
445 builder
446 .meter
447 .work(index.modules.len(), &item.file, Some(item.name_line))?;
448 let mut module = if root {
449 index.target_roots.get(item.target.index()).copied()
450 } else {
451 index.modules.iter().position(|module| {
452 module.target == item.target && Some(module.path.as_str()) == parent
453 })
454 };
455 while let Some(at) = module {
456 let Some(parent) = index.modules[at].parent else {
457 break;
458 };
459 builder
460 .meter
461 .work(index.module_of.len(), &item.file, Some(item.name_line))?;
462 let mut sites = index.module_of.iter().filter(|(_, child)| **child == at);
463 let Some((&decl, _)) = sites.next() else {
464 builder
465 .meter
466 .work(index.block_modules.len(), &item.file, Some(item.name_line))?;
467 if index.block_modules.iter().any(|block| block.module == at) {
468 builder.uncertain = true;
471 break;
472 }
473 return Err(missing());
474 };
475 if sites.next().is_some() {
476 builder.uncertain = true;
477 break;
478 }
479 let decl = &index.items[decl.0];
480 builder.site(
481 source.file(&decl.file).ok_or_else(missing)?,
482 decl.span.start_byte,
483 true,
484 )?;
485 module = Some(parent);
486 }
487 if module.is_none() {
488 if ordinary || root {
489 return Err(missing());
490 }
491 builder.uncertain = true;
492 }
493 if let Some(target) = source.target(item.target) {
494 builder.attrs(&source.file(&target.root).ok_or_else(missing)?.facts.attrs)?;
495 } else {
496 return Err(missing());
497 }
498 Ok::<_, LoadError>(TestPlatformGuard {
499 attrs: builder.attrs,
500 uncertain: builder.uncertain,
501 })
502 })();
503 result.map_err(|error| match error.kind {
504 LoadErrorKind::Storage(native) => admission.error(native),
505 _ => error,
506 })
507}
508
509fn validate_attribute(meta: &Meta) -> Result<(), String> {
510 let Meta::List(list) = meta else {
511 return if meta.path().is_ident("cfg") || meta.path().is_ident("cfg_attr") {
512 Err("retained cfg attribute requires a predicate list".into())
513 } else {
514 Ok(())
515 };
516 };
517 if !list.path.is_ident("cfg") && !list.path.is_ident("cfg_attr") {
518 return Ok(());
519 }
520 let parts = crate::cfg::parse_punctuated(&list.tokens)?;
521 let first = parts
522 .first()
523 .ok_or("retained cfg attribute has no predicate")?;
524 CfgExpr::from_meta_configured(first)?;
525 if list.path.is_ident("cfg") {
526 if parts.len() != 1 {
527 return Err("retained cfg attribute has several predicates".into());
528 }
529 } else {
530 if parts.len() == 1 && !parts.trailing_punct() {
531 return Err("retained cfg_attr requires a comma after its predicate".into());
532 }
533 for part in parts.iter().skip(1) {
534 validate_attribute(part)?;
535 }
536 }
537 Ok(())
538}
539
540#[cfg(test)]
541mod tests {
542 use super::*;
543 use crate::MemoryTree;
544
545 fn workspace(files: &[(&str, &str)]) -> Workspace {
546 let tree: MemoryTree =
547 std::iter::once(("Cargo.toml", "[package]\nname='demo'\nversion='0.1.0'\n"))
548 .chain(files.iter().copied())
549 .collect();
550 Workspace::load(&tree, &["."]).unwrap()
551 }
552
553 fn at<'a>(source: &'a Workspace, path: &str) -> TestPlatformGuard<'a> {
554 let item = source
555 .items()
556 .find(|item| item.path.as_str() == path)
557 .unwrap();
558 source.test_platform_guard(item.id).unwrap()
559 }
560
561 fn linux() -> CompilerPlatform {
562 CompilerPlatform::parse("target_os=\"linux\"\ntarget_family=\"unix\"\nunix\n").unwrap()
563 }
564
565 fn windows() -> CompilerPlatform {
566 CompilerPlatform::parse("target_os=\"windows\"\ntarget_family=\"windows\"\nwindows\n")
567 .unwrap()
568 }
569
570 #[test]
571 fn platform_guard_reference_storage_uses_the_remaining_item_grant() {
572 let tree = MemoryTree::from([
573 ("Cargo.toml", "[package]\nname='demo'\nversion='0.1.0'\n"),
574 ("src/lib.rs", "#[cfg(windows)]\n#[test]\nfn selected() {}\n"),
575 ]);
576 let source = Workspace::load(&tree, &["."]).unwrap();
577 let item = source
578 .items()
579 .find(|item| item.path.as_str() == "demo::selected")
580 .unwrap();
581 let item_bytes = source.usage().item_bytes;
582 let admitted = source.test_platform_guard(item.id).unwrap();
583 assert_eq!(admitted.attrs.len(), 1);
586 let pointer_bytes = admitted.attrs.capacity() * size_of::<&AttrFact>();
587 assert!(pointer_bytes > 0);
588 assert_eq!(admitted.evaluate(&linux()), Some(false));
589 drop(admitted);
590
591 let sufficient = LoadOptions {
592 max_item_bytes: item_bytes + pointer_bytes,
593 ..LoadOptions::default()
594 };
595 let source = Workspace::load_with(&tree, &["."], &sufficient).unwrap();
596 let item = source
597 .items()
598 .find(|item| item.path.as_str() == "demo::selected")
599 .unwrap();
600 let admitted = source.test_platform_guard(item.id).unwrap();
601 assert_eq!(admitted.attrs.len(), 1);
602 assert_eq!(admitted.evaluate(&linux()), Some(false));
603
604 for remaining in [0, pointer_bytes - 1] {
607 let limit = item_bytes + remaining;
608 let options = LoadOptions {
609 max_item_bytes: limit,
610 ..LoadOptions::default()
611 };
612 let source = Workspace::load_with(&tree, &["."], &options).unwrap();
613 assert_eq!(source.usage().item_bytes, item_bytes);
614 let item = source
615 .items()
616 .find(|item| item.path.as_str() == "demo::selected")
617 .unwrap();
618 let error = source.test_platform_guard(item.id).unwrap_err();
619 assert!(
620 matches!(error.kind, LoadErrorKind::Budget { budget: crate::Budget::ItemBytes, limit: actual } if actual == limit),
621 "{error}"
622 );
623 assert_eq!(error.file.as_str(), "src/lib.rs");
624 assert_eq!(error.line, None);
625 }
626 }
627
628 #[test]
629 fn platform_guard_work_exhaustion_is_typed_beside_a_sufficient_neighbor() {
630 let source = workspace(&[("src/lib.rs", "#[cfg(windows)]\n#[test]\nfn selected() {}\n")]);
631 let item = source
632 .items()
633 .find(|item| item.path.as_str() == "demo::selected")
634 .unwrap();
635 let options = LoadOptions {
638 max_work: 0,
639 ..LoadOptions::default()
640 };
641 let error = guard(
642 &source,
643 item.id,
644 source.index(),
645 &options,
646 source.usage().item_bytes,
647 )
648 .unwrap_err();
649 assert!(
650 matches!(
651 error.kind,
652 LoadErrorKind::Budget {
653 budget: crate::Budget::Work,
654 limit: 0
655 }
656 ),
657 "{error}"
658 );
659 assert_eq!(error.file.as_str(), "src/lib.rs");
660 assert_eq!(error.line, Some(3));
661 let accepted = source.test_platform_guard(item.id).unwrap();
662 assert_eq!(accepted.evaluate(&linux()), Some(false));
663 assert_eq!(accepted.evaluate(&windows()), Some(true));
664 }
665
666 #[test]
667 fn parent_platform_guards_do_not_filter_the_source_inventory() {
668 let source = workspace(&[
669 (
670 "src/lib.rs",
671 r"
672 #[cfg(windows)] mod windows {
673 #[test] fn a_disk_tree_refuses_a_reserved_device_name_or_a_trailing_dot_or_space_beside_a_plain_name() {}
674 #[test] fn the_final_path_of_a_handle_is_its_canonical_path_and_lies_under_the_root() {}
675 }
676 #[cfg(windows)] mod external;
677 #[test] fn plain() {}
678 ",
679 ),
680 ("src/external.rs", "#[test] fn external_test() {}"),
681 ]);
682 for path in [
683 "demo::windows::a_disk_tree_refuses_a_reserved_device_name_or_a_trailing_dot_or_space_beside_a_plain_name",
684 "demo::windows::the_final_path_of_a_handle_is_its_canonical_path_and_lies_under_the_root",
685 "demo::external::external_test",
686 ] {
687 let guard = at(&source, path);
688 assert!(guard.has_platform_condition());
689 assert_eq!(guard.evaluate(&linux()), Some(false));
690 assert_eq!(guard.evaluate(&windows()), Some(true));
691 assert!(guard.to_string().contains("windows"));
692 }
693 assert_eq!(at(&source, "demo::plain").evaluate(&linux()), Some(true));
694 assert_eq!(source.test_fns().unwrap().len(), 4);
695 }
696
697 #[test]
698 fn inner_crate_and_external_module_guards_are_both_observed() {
699 let source = workspace(&[
700 ("src/lib.rs", "#![cfg(target_family=\"unix\")] mod child;"),
701 (
702 "src/child.rs",
703 "#![cfg(target_os=\"linux\")] #[test] fn selected() {}",
704 ),
705 ]);
706 let guard = at(&source, "demo::child::selected");
707 assert_eq!(guard.evaluate(&linux()), Some(true));
708 assert_eq!(guard.evaluate(&windows()), Some(false));
709 }
710
711 #[test]
712 fn nonplatform_conditions_and_cfg_attr_do_not_invent_exclusion() {
713 let source = workspace(&[(
714 "src/lib.rs",
715 r#"
716 #[cfg(all(not(test), windows))] #[test] fn nonplatform() {}
717 #[cfg(all(any(), windows))] #[test] fn constant() {}
718 #[cfg(false)] #[test] fn literal_false() {}
719 #[cfg(r#false)] #[test] fn raw_false() {}
720 #[cfg_attr(unix,)] #[test] fn empty_platform_attr() {}
721 #[cfg_attr(custom,)] #[test] fn empty_unknown_attr() {}
722 #[cfg(any(feature="extra", windows))] #[test] fn feature() {}
723 #[cfg_attr(test, cfg(windows))] #[test] fn unknown_attr() {}
724 #[cfg_attr(unix, cfg(target_os="linux"))] #[test] fn implication() {}
725 #[cfg(windows)] #[test] fn bare() {}
726 "#,
727 )]);
728 for path in ["demo::nonplatform", "demo::constant"] {
729 assert_eq!(at(&source, path).evaluate(&windows()), None);
730 assert_eq!(at(&source, path).evaluate(&linux()), Some(false));
731 }
732 assert_eq!(at(&source, "demo::feature").evaluate(&linux()), None);
733 for name in ["demo::literal_false", "demo::raw_false"] {
734 assert_eq!(at(&source, name).evaluate(&linux()), None);
735 assert_eq!(at(&source, name).evaluate(&windows()), None);
736 }
737 for name in ["demo::empty_platform_attr", "demo::empty_unknown_attr"] {
738 assert_eq!(at(&source, name).evaluate(&linux()), Some(true));
739 assert_eq!(at(&source, name).evaluate(&windows()), Some(true));
740 }
741 for malformed in [
742 "cfg_attr(unix)",
743 "cfg_attr()",
744 "cfg_attr(,)",
745 "cfg(::windows)",
746 "cfg_attr(::windows,)",
747 ] {
748 let meta = syn::parse_str(malformed).expect("retained metadata syntax");
749 assert!(validate_attribute(&meta).is_err(), "{malformed}");
750 assert_eq!(evaluate_attribute(&meta, &linux()), None, "{malformed}");
751 }
752 for (malformed, correction) in [
753 ("cfg(::windows)", "unqualified"),
754 ("cfg_attr(::windows,)", "unqualified"),
755 ("cfg_attr(unix)", "comma"),
756 ] {
757 let text = format!("#[{malformed}] #[test] fn malformed() {{}}");
758 let invalid = workspace(&[("src/lib.rs", &text)]);
759 let item = invalid
760 .resolve("demo::malformed")
761 .expect("structural item")
762 .sites[0];
763 let error = invalid
764 .test_platform_guard(item)
765 .expect_err("malformed guard");
766 assert!(error.to_string().contains(correction), "{error}");
767 }
768 assert_eq!(at(&source, "demo::bare").evaluate(&linux()), Some(false));
769 assert_eq!(at(&source, "demo::bare").evaluate(&windows()), Some(true));
770 assert_eq!(at(&source, "demo::unknown_attr").evaluate(&linux()), None);
771 assert_eq!(
772 at(&source, "demo::implication").evaluate(&linux()),
773 Some(true)
774 );
775 assert_eq!(
776 at(&source, "demo::implication").evaluate(&windows()),
777 Some(true)
778 );
779 let custom =
780 CompilerPlatform::parse("target_os=\"linux\"\ntarget_family=\"unix\"\nwindows\n")
781 .unwrap();
782 assert_eq!(at(&source, "demo::bare").evaluate(&custom), Some(true));
783 }
784
785 #[test]
786 fn compiler_platform_refuses_incomplete_or_malformed_output() {
787 assert!(matches!(
788 CompilerPlatform::parse("unix\n"),
789 Err(CompilerPlatformError::MissingOs)
790 ));
791 assert!(matches!(
792 CompilerPlatform::parse("target_os=\"linux\"\ntarget_os=\"linux\"\n"),
793 Err(CompilerPlatformError::MultipleOs)
794 ));
795 assert!(matches!(
796 CompilerPlatform::parse("target_os=123\n"),
797 Err(CompilerPlatformError::NonStringValue { .. })
798 ));
799 assert!(matches!(
800 CompilerPlatform::parse("target_os=\"linux\"\nall(unix)\n"),
801 Err(CompilerPlatformError::NonAtomic { .. })
802 ));
803 let syntax =
804 CompilerPlatform::parse("target_os =\n").expect_err("a missing cfg value is malformed");
805 assert!(matches!(syntax, CompilerPlatformError::Syntax { .. }));
806 assert!(std::error::Error::source(&syntax).is_some());
807 assert!(CompilerPlatform::parse("target_os=\"none\"\n").is_ok());
808 }
809
810 #[test]
811 fn conditional_module_routes_remain_unknown() {
812 let source = workspace(&[
813 (
814 "src/lib.rs",
815 "#[cfg_attr(feature=\"alternate\",path=\"alternate.rs\")] mod child;",
816 ),
817 ("src/child.rs", "#[cfg(windows)] #[test] fn selected() {}"),
818 ("src/alternate.rs", "#[cfg(unix)] #[test] fn selected() {}"),
819 ]);
820 let alternatives: Vec<_> = source
821 .items()
822 .filter(|item| item.path.as_str() == "demo::child::selected")
823 .collect();
824 assert_ne!(alternatives.len(), 0);
825 for item in alternatives {
826 let guard = source.test_platform_guard(item.id).unwrap();
827 assert_eq!(guard.evaluate(&linux()), None);
828 }
829 }
830
831 #[test]
832 fn invalid_item_is_an_actionable_error() {
833 let source = workspace(&[("src/lib.rs", "#[test] fn plain() {}")]);
834 let error = source.test_platform_guard(ItemId(usize::MAX)).unwrap_err();
835 assert!(matches!(error.kind, LoadErrorKind::Internal { .. }));
836 }
837}