Skip to content

Commit

Permalink
Review Updates and added tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
wyatt-herkamp committed Mar 11, 2024
1 parent 0fb5d0d commit 447de3d
Show file tree
Hide file tree
Showing 6 changed files with 274 additions and 126 deletions.
2 changes: 1 addition & 1 deletion crates/cfg/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ rustc-hash.workspace = true

# locals deps
tt.workspace = true
syntax.workspace = true

[dev-dependencies]
expect-test = "1.4.1"
Expand All @@ -29,6 +28,7 @@ derive_arbitrary = "1.3.2"

# local deps
mbe.workspace = true
syntax.workspace = true

[lints]
workspace = true
77 changes: 2 additions & 75 deletions crates/cfg/src/cfg_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@
//!
//! See: <https://doc.rust-lang.org/reference/conditional-compilation.html#conditional-compilation>
use std::{fmt, iter::Peekable, slice::Iter as SliceIter};
use std::{fmt, slice::Iter as SliceIter};

use syntax::{
ast::{self, Meta},
NodeOrToken,
};
use tt::SmolStr;

/// A simple configuration value passed in from the outside.
Expand Down Expand Up @@ -51,12 +47,7 @@ impl CfgExpr {
pub fn parse<S>(tt: &tt::Subtree<S>) -> CfgExpr {
next_cfg_expr(&mut tt.token_trees.iter()).unwrap_or(CfgExpr::Invalid)
}
/// Parses a `cfg` attribute from the meta
pub fn parse_from_attr_meta(meta: Meta) -> Option<CfgExpr> {
let tt = meta.token_tree()?;
let mut iter = tt.token_trees_and_tokens().skip(1).peekable();
next_cfg_expr_from_syntax(&mut iter)
}

/// Fold the cfg by querying all basic `Atom` and `KeyValue` predicates.
pub fn fold(&self, query: &dyn Fn(&CfgAtom) -> bool) -> Option<bool> {
match self {
Expand All @@ -72,70 +63,6 @@ impl CfgExpr {
}
}
}
fn next_cfg_expr_from_syntax<I>(iter: &mut Peekable<I>) -> Option<CfgExpr>
where
I: Iterator<Item = NodeOrToken<ast::TokenTree, syntax::SyntaxToken>>,
{
let name = match iter.next() {
None => return None,
Some(NodeOrToken::Token(element)) => match element.kind() {
syntax::T![ident] => SmolStr::new(element.text()),
_ => return Some(CfgExpr::Invalid),
},
Some(_) => return Some(CfgExpr::Invalid),
};
let result = match name.as_str() {
"all" | "any" | "not" => {
let mut preds = Vec::new();
let Some(NodeOrToken::Node(tree)) = iter.next() else {
return Some(CfgExpr::Invalid);
};
let mut tree_iter = tree.token_trees_and_tokens().skip(1).peekable();
while tree_iter
.peek()
.filter(
|element| matches!(element, NodeOrToken::Token(token) if (token.kind() != syntax::T![')'])),
)
.is_some()
{
let pred = next_cfg_expr_from_syntax(&mut tree_iter);
if let Some(pred) = pred {
preds.push(pred);
}
}
let group = match name.as_str() {
"all" => CfgExpr::All(preds),
"any" => CfgExpr::Any(preds),
"not" => CfgExpr::Not(Box::new(preds.pop().unwrap_or(CfgExpr::Invalid))),
_ => unreachable!(),
};
Some(group)
}
_ => match iter.peek() {
Some(NodeOrToken::Token(element)) if (element.kind() == syntax::T![=]) => {
iter.next();
match iter.next() {
Some(NodeOrToken::Token(value_token))
if (value_token.kind() == syntax::SyntaxKind::STRING) =>
{
let value = value_token.text();
let value = SmolStr::new(value.trim_matches('"'));
Some(CfgExpr::Atom(CfgAtom::KeyValue { key: name, value }))
}
_ => None,
}
}
_ => Some(CfgExpr::Atom(CfgAtom::Flag(name))),
},
};
if let Some(NodeOrToken::Token(element)) = iter.peek() {
if element.kind() == syntax::T![,] {
iter.next();
}
}
result
}

fn next_cfg_expr<S>(it: &mut SliceIter<'_, tt::TokenTree<S>>) -> Option<CfgExpr> {
let name = match it.next() {
None => return None,
Expand Down
26 changes: 1 addition & 25 deletions crates/cfg/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
use arbitrary::{Arbitrary, Unstructured};
use expect_test::{expect, Expect};
use mbe::{syntax_node_to_token_tree, DummyTestSpanMap, DUMMY};
use syntax::{
ast::{self, Attr},
AstNode, SourceFile,
};
use syntax::{ast, AstNode};

use crate::{CfgAtom, CfgExpr, CfgOptions, DnfExpr};

Expand All @@ -15,22 +12,6 @@ fn assert_parse_result(input: &str, expected: CfgExpr) {
let cfg = CfgExpr::parse(&tt);
assert_eq!(cfg, expected);
}
fn check_dnf_from_syntax(input: &str, expect: Expect) {
let parse = SourceFile::parse(input);
let node = match parse.tree().syntax().descendants().find_map(Attr::cast) {
Some(it) => it,
None => {
let node = std::any::type_name::<Attr>();
panic!("Failed to make ast node `{node}` from text {input}")
}
};
let node = node.clone_subtree();
assert_eq!(node.syntax().text_range().start(), 0.into());

let cfg = CfgExpr::parse_from_attr_meta(node.meta().unwrap()).unwrap();
let actual = format!("#![cfg({})]", DnfExpr::new(cfg));
expect.assert_eq(&actual);
}

fn check_dnf(input: &str, expect: Expect) {
let source_file = ast::SourceFile::parse(input).ok().unwrap();
Expand Down Expand Up @@ -105,11 +86,6 @@ fn smoke() {

check_dnf("#![cfg(not(a))]", expect![[r#"#![cfg(not(a))]"#]]);
}
#[test]
fn cfg_from_attr() {
check_dnf_from_syntax(r#"#[cfg(test)]"#, expect![[r#"#![cfg(test)]"#]]);
check_dnf_from_syntax(r#"#[cfg(not(never))]"#, expect![[r#"#![cfg(not(never))]"#]]);
}

#[test]
fn distribute() {
Expand Down
118 changes: 118 additions & 0 deletions crates/hir-def/src/macro_expansion_tests/builtin_derive_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,3 +528,121 @@ impl < > $crate::fmt::Debug for Command< > where {
}"#]],
);
}
#[test]
fn test_debug_expand_with_cfg() {
check(
r#"
//- minicore: derive, fmt
use core::fmt::Debug;
#[derive(Debug)]
struct HideAndShow {
#[cfg(never)]
always_hide: u32,
#[cfg(not(never))]
always_show: u32,
}
#[derive(Debug)]
enum HideAndShowEnum {
#[cfg(never)]
AlwaysHide,
#[cfg(not(never))]
AlwaysShow{
#[cfg(never)]
always_hide: u32,
#[cfg(not(never))]
always_show: u32,
}
}
"#,
expect![[r#"
use core::fmt::Debug;
#[derive(Debug)]
struct HideAndShow {
#[cfg(never)]
always_hide: u32,
#[cfg(not(never))]
always_show: u32,
}
#[derive(Debug)]
enum HideAndShowEnum {
#[cfg(never)]
AlwaysHide,
#[cfg(not(never))]
AlwaysShow{
#[cfg(never)]
always_hide: u32,
#[cfg(not(never))]
always_show: u32,
}
}
impl < > $crate::fmt::Debug for HideAndShow< > where {
fn fmt(&self , f: &mut $crate::fmt::Formatter) -> $crate::fmt::Result {
match self {
HideAndShow {
always_show: always_show,
}
=>f.debug_struct("HideAndShow").field("always_show", &always_show).finish()
}
}
}
impl < > $crate::fmt::Debug for HideAndShowEnum< > where {
fn fmt(&self , f: &mut $crate::fmt::Formatter) -> $crate::fmt::Result {
match self {
HideAndShowEnum::AlwaysShow {
always_show: always_show,
}
=>f.debug_struct("AlwaysShow").field("always_show", &always_show).finish(),
}
}
}"#]],
);
}
#[test]
fn test_default_expand_with_cfg() {
check(
r#"
//- minicore: derive, default
#[derive(Default)]
struct Foo {
field1: i32,
#[cfg(never)]
field2: (),
}
#[derive(Default)]
enum Bar {
Foo,
#[cfg_attr(not(never), default)]
Bar,
}
"#,
expect![[r#"
#[derive(Default)]
struct Foo {
field1: i32,
#[cfg(never)]
field2: (),
}
#[derive(Default)]
enum Bar {
Foo,
#[cfg_attr(not(never), default)]
Bar,
}
impl < > $crate::default::Default for Foo< > where {
fn default() -> Self {
Foo {
field1: $crate::default::Default::default(),
}
}
}
impl < > $crate::default::Default for Bar< > where {
fn default() -> Self {
Bar::Bar
}
}"#]],
);
}
Loading

0 comments on commit 447de3d

Please sign in to comment.