Expand description
Document tree traversal to walk a shared borrow of a document tree.
Each method of the Visit
trait is a hook that can be overridden
to customize the behavior when mutating the corresponding type of node.
By default, every method recursively visits the substructure of the
input by invoking the right visitor method of each of its fields.
pub trait Visit<'doc> {
/* ... */
fn visit_item(&mut self, i: &'doc Item) {
visit_item(self, i);
}
/* ... */
}
pub fn visit_item<'doc, V>(v: &mut V, node: &'doc Item)
where
V: Visit<'doc> + ?Sized,
{
match node {
Item::None => {}
Item::Value(value) => v.visit_value(value),
Item::Table(table) => v.visit_table(table),
Item::ArrayOfTables(array) => v.visit_array_of_tables(array),
}
}
The API is modeled after syn::visit
.
Examples
This visitor stores every string in the document.
use toml_edit::visit::*;
#[derive(Default)]
struct StringCollector<'doc> {
strings: Vec<&'doc str>,
}
impl<'doc> Visit<'doc> for StringCollector<'doc> {
fn visit_string(&mut self, node: &'doc Formatted<String>) {
self.strings.push(node.value().as_str());
}
}
let input = r#"
laputa = "sky-castle"
the-force = { value = "surrounds-you" }
"#;
let mut document: Document = input.parse().unwrap();
let mut visitor = StringCollector::default();
visitor.visit_document(&document);
assert_eq!(visitor.strings, vec!["sky-castle", "surrounds-you"]);
For a more complex example where the visitor has internal state, see examples/visit.rs
on GitHub.
Traits
Document tree traversal to mutate an exclusive borrow of a document tree in-place.