|
| 1 | +use std::{ |
| 2 | + fmt::{self, Debug}, |
| 3 | + slice::Iter as SliceIter, |
| 4 | +}; |
| 5 | + |
| 6 | +use crate::{cfg_expr::next_cfg_expr, CfgAtom, CfgExpr}; |
| 7 | +use tt::{Delimiter, SmolStr, Span}; |
| 8 | +/// Represents a `#[cfg_attr(.., my_attr)]` attribute. |
| 9 | +#[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 10 | +pub struct CfgAttr<S> { |
| 11 | + /// Expression in `cfg_attr` attribute. |
| 12 | + pub cfg_expr: CfgExpr, |
| 13 | + /// Inner attribute. |
| 14 | + pub attr: tt::Subtree<S>, |
| 15 | +} |
| 16 | + |
| 17 | +impl<S: Clone + Span + Debug> CfgAttr<S> { |
| 18 | + /// Parses a sub tree in the form of (cfg_expr, inner_attribute) |
| 19 | + pub fn parse(tt: &tt::Subtree<S>) -> Option<CfgAttr<S>> { |
| 20 | + let mut iter = tt.token_trees.iter(); |
| 21 | + let cfg_expr = next_cfg_expr(&mut iter).unwrap_or(CfgExpr::Invalid); |
| 22 | + // FIXME: This is probably not the right way to do this |
| 23 | + // Get's the span of the next token tree |
| 24 | + let first_span = iter.as_slice().first().map(|tt| tt.first_span())?; |
| 25 | + let attr = tt::Subtree { |
| 26 | + delimiter: Delimiter::invisible_spanned(first_span), |
| 27 | + token_trees: iter.cloned().collect(), |
| 28 | + }; |
| 29 | + Some(CfgAttr { cfg_expr, attr: attr }) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +#[cfg(test)] |
| 34 | +mod tests { |
| 35 | + use expect_test::{expect, Expect}; |
| 36 | + use mbe::{syntax_node_to_token_tree, DummyTestSpanMap, DUMMY}; |
| 37 | + use syntax::{ast, AstNode}; |
| 38 | + |
| 39 | + use crate::{CfgAttr, DnfExpr}; |
| 40 | + |
| 41 | + fn check_dnf(input: &str, expected_dnf: Expect, expected_attrs: Expect) { |
| 42 | + let source_file = ast::SourceFile::parse(input).ok().unwrap(); |
| 43 | + let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap(); |
| 44 | + let tt = syntax_node_to_token_tree(tt.syntax(), DummyTestSpanMap, DUMMY); |
| 45 | + let Some(CfgAttr { cfg_expr, attr }) = CfgAttr::parse(&tt) else { |
| 46 | + assert!(false, "failed to parse cfg_attr"); |
| 47 | + return; |
| 48 | + }; |
| 49 | + |
| 50 | + let actual = format!("#![cfg({})]", DnfExpr::new(cfg_expr)); |
| 51 | + expected_dnf.assert_eq(&actual); |
| 52 | + let actual_attrs = format!("#![{}]", attr); |
| 53 | + expected_attrs.assert_eq(&actual_attrs); |
| 54 | + } |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn smoke() { |
| 58 | + check_dnf( |
| 59 | + r#"#![cfg_attr(feature = "nightly", feature(slice_split_at_unchecked))]"#, |
| 60 | + expect![[r#"#![cfg(feature = "nightly")]"#]], |
| 61 | + expect![r#"#![feature (slice_split_at_unchecked)]"#], |
| 62 | + ); |
| 63 | + |
| 64 | + check_dnf( |
| 65 | + r#"#![cfg_attr(not(feature = "std"), no_std)]"#, |
| 66 | + expect![[r#"#![cfg(not(feature = "std"))]"#]], |
| 67 | + expect![r#"#![no_std]"#], |
| 68 | + ); |
| 69 | + } |
| 70 | +} |
0 commit comments