Skip to content

Commit caa603d

Browse files
committed
Support @ marker in tree! macro to append subtrees
1 parent 44a220e commit caa603d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/lib.rs

+23
Original file line numberDiff line numberDiff line change
@@ -822,6 +822,22 @@ pub mod iter;
822822
/// };
823823
/// # }
824824
/// ```
825+
/// Compose trees using the `@` marker:
826+
/// ```
827+
/// #[macro_use] extern crate ego_tree;
828+
/// # fn main() {
829+
/// let subtree = tree! {
830+
/// "foo" => { "bar", "baz" }
831+
/// };
832+
/// let new_tree = tree! {
833+
/// "root" => {
834+
/// "child x",
835+
/// "child y",
836+
/// @ subtree,
837+
/// }
838+
/// };
839+
/// # }
840+
/// ```
825841
#[macro_export]
826842
macro_rules! tree {
827843
(@ $n:ident { }) => { };
@@ -858,6 +874,13 @@ macro_rules! tree {
858874
}
859875
};
860876

877+
// Append subtree from expression.
878+
(@ $n:ident { @ $subtree:expr $(, $($tail:tt)*)? }) => {{
879+
$n.append_subtree($subtree);
880+
$( tree!(@ $n { $($tail)* }); )?
881+
}};
882+
883+
861884
($root:expr) => { $crate::Tree::new($root) };
862885

863886
($root:expr => $children:tt) => {

tests/macro.rs

+24
Original file line numberDiff line numberDiff line change
@@ -163,3 +163,27 @@ fn mixed() {
163163

164164
assert_eq!(manual_tree, macro_tree);
165165
}
166+
167+
#[test]
168+
fn subtree() {
169+
let subtree = tree! {
170+
'x' => { 'y' => {'z'}}
171+
};
172+
let tree = tree! {
173+
'a' => {
174+
'b',
175+
'c' => {'d', 'e'},
176+
@ subtree.clone(),
177+
'f' => { @subtree },
178+
}
179+
};
180+
let expected_tree = tree! {
181+
'a' => {
182+
'b',
183+
'c' => {'d', 'e'},
184+
'x' => { 'y' => {'z'}},
185+
'f' => {'x' => { 'y' => {'z'}} },
186+
}
187+
};
188+
assert_eq!(tree, expected_tree);
189+
}

0 commit comments

Comments
 (0)