pub struct Builder<T, F = FlavorDefault>{ /* private fields */ }Expand description
A builder for a Tree.
This maintains a stack of nodes being built which has to be balanced with
calls to Builder::open and Builder::close.
§Type parameters and bounds
The two type parameters of the builder determine the following properties:
Tis the data stored in the tree.Fis the Flavor, declared withflavor!. ItsIndexdetermines the numerical bounds of spans, and if set to Empty the tree does not store any spans. ItsWidthdetermines the bounds of pointers in the tree, which decides how many nodes can be stored in it. It also selects theStorageused and its error type.
To use the default values, use the Builder::new constructor.
§Errors
Besides the errors documented on each method, any method which adds a node
or token can fail with Error::Flavor if the flavor’s storage fails to
grow.
§Examples
let mut tree = syntree::Builder::new();
tree.open("root")?;
tree.open("child")?;
tree.close()?;
tree.open("child")?;
tree.close()?;
tree.close()?;
let tree = tree.build()?;
let expected = syntree::tree! {
"root" => {
"child" => {},
"child" => {}
}
};
assert_eq!(tree, expected);Implementations§
Source§impl<T> Builder<T, FlavorDefault>where
T: Copy,
impl<T> Builder<T, FlavorDefault>where
T: Copy,
Sourcepub const fn new() -> Self
pub const fn new() -> Self
Construct a new tree with a default Span based on u32.
For a constructor that can use custom bounds, use Builder::new_with.
§Examples
let mut tree = syntree::Builder::new();
tree.open("root")?;
tree.open("child")?;
tree.token("token", 5)?;
tree.close()?;
tree.open("child2")?;
tree.close()?;
tree.close()?;
let tree = tree.build()?;
let expected = syntree::tree! {
"root" => {
"child" => {
("token", 5)
},
"child2" => {}
}
};
assert_eq!(tree, expected);Source§impl<T, F> Builder<T, F>
impl<T, F> Builder<T, F>
Sourcepub const fn new_with() -> Self
pub const fn new_with() -> Self
Construct a new tree with a custom span.
To build a tree with default bounds, see Builder::new. Also see the Builder documentation for what the different bounds means.
§Examples
use syntree::{Builder, Empty, Tree};
syntree::flavor! {
struct FlavorEmpty {
type Index = Empty;
type Width = u32;
}
}
let mut tree: Builder<_, FlavorEmpty> = Builder::new_with();
tree.open("root")?;
tree.open("child")?;
tree.token("token", Empty)?;
tree.close()?;
tree.open("child2")?;
tree.close()?;
tree.close()?;
let tree = tree.build()?;
let expected: Tree<_, FlavorEmpty> = syntree::tree_with! {
"root" => {
"child" => {
"token"
},
"child2" => {}
}
};
assert_eq!(tree, expected);Sourcepub fn with_capacity(tokens: usize) -> Result<Self, Error<F::Error>>
pub fn with_capacity(tokens: usize) -> Result<Self, Error<F::Error>>
Construct a new builder with capacity for tokens tokens.
Every call to Builder::token (and its variants) adds one token,
and a token with an explicit span which leaves a gap after the previous
token takes one more entry. Interior nodes, added by Builder::open
and Builder::close_at, are sized separately through
Builder::with_capacities.
§Errors
Errors with Error::Flavor if the flavor’s storage can’t hold
tokens tokens.
§Examples
use syntree::{Builder, FlavorDefault};
let mut tree = Builder::<_, FlavorDefault>::with_capacity(2)?;
tree.open("root")?;
tree.token("token", 5)?;
tree.close()?;
let tree = tree.build()?;
assert_eq!(tree.len(), 2);
assert!(tree.capacity() >= 2);Sourcepub fn with_capacities(
nodes: usize,
tokens: usize,
) -> Result<Self, Error<F::Error>>
pub fn with_capacities( nodes: usize, tokens: usize, ) -> Result<Self, Error<F::Error>>
Construct a new builder with capacity for nodes interior nodes and
tokens tokens.
See Builder::with_capacity for what the counts mean.
§Errors
Errors with Error::Flavor if the flavor’s storage can’t hold
nodes nodes or tokens tokens.
§Examples
use syntree::{Builder, FlavorDefault};
let source = "a b";
// At most one token per byte, and a root node.
let mut tree = Builder::<_, FlavorDefault>::with_capacities(1, source.len())?;
tree.open("root")?;
tree.token("word", 1)?;
tree.token("ws", 1)?;
tree.token("word", 1)?;
tree.close()?;
let tree = tree.build()?;
assert_eq!(tree.len(), 4);
assert_eq!(tree.capacity(), 4);Sourcepub fn reserve(
&mut self,
nodes: usize,
tokens: usize,
) -> Result<(), Error<F::Error>>
pub fn reserve( &mut self, nodes: usize, tokens: usize, ) -> Result<(), Error<F::Error>>
Reserve capacity for at least nodes more interior nodes and tokens
more tokens.
See Builder::with_capacity for what the counts mean.
§Errors
Errors with Error::Flavor if the flavor’s storage can’t hold that
many more nodes or tokens.
§Examples
let mut tree = syntree::Builder::new();
tree.reserve(1, 1)?;
tree.open("root")?;
tree.token("token", 5)?;
tree.close()?;
let tree = tree.build()?;
assert_eq!(tree.len(), 2);Sourcepub fn reserve_checkpoints(
&mut self,
additional: usize,
) -> Result<(), Error<F::Error>>
pub fn reserve_checkpoints( &mut self, additional: usize, ) -> Result<(), Error<F::Error>>
Reserve room for at least additional more checkpoints.
Checkpoints are stored in the builder, so a parser which knows roughly how many it will take can size that storage up front instead of growing it.
Errors with Error::Flavor if the flavor’s storage can’t hold that
many more checkpoints.
§Examples
let mut tree = syntree::Builder::new();
tree.reserve_checkpoints(2)?;
let c = tree.checkpoint()?;
tree.token("token", 5)?;
tree.close_at(c, "wrapper")?;
let tree = tree.build()?;
assert_eq!(tree.len(), 2);Sourcepub const fn cursor(&self) -> &F::Index
pub const fn cursor(&self) -> &F::Index
Get a reference to the current cursor position of the syntax tree.
The cursor position is the position in which it’s been advanced so far as a result of calls to Builder::token and indicates the current starting index of the next span.
§Examples
let mut tree = syntree::Builder::new();
assert_eq!(*tree.cursor(), 0);
tree.open("child")?;
assert_eq!(*tree.cursor(), 0);
tree.token("lit", 4)?;
assert_eq!(*tree.cursor(), 4);
tree.close()?;
assert_eq!(*tree.cursor(), 4);
let tree = tree.build()?;
let expected = syntree::tree! {
"child" => {
("lit", 4)
}
};
assert_eq!(tree, expected);Sourcepub fn set_cursor(&mut self, cursor: F::Index)
pub fn set_cursor(&mut self, cursor: F::Index)
Set the cursor position of the syntax tree.
This is used to implicitly set spans when using spanless constructions
methods. Range queries such as Tree::node_with_range assume that
tokens are added in non-decreasing order, so the cursor should not be
moved backwards past an already added token.
§Examples
use syntree::Span;
let mut tree = syntree::Builder::new();
tree.open("child")?;
tree.token("lit", 4)?;
// Skip two units of input which are not part of the tree.
tree.set_cursor(6);
assert_eq!(*tree.cursor(), 6);
tree.token("lit", 2)?;
tree.close()?;
let tree = tree.build()?;
let child = tree.first().ok_or("missing child")?;
assert_eq!(child.span(), &Span::new(0, 8));
let spans = child.children().map(|n| n.span()).collect::<Vec<_>>();
assert_eq!(spans, [Span::new(0, 4), Span::new(6, 8)]);Sourcepub fn open(&mut self, data: T) -> Result<F::Pointer, Error<F::Error>>
pub fn open(&mut self, data: T) -> Result<F::Pointer, Error<F::Error>>
Start a node with the given data.
This pushes a new link with the given type onto the stack which links
itself onto the last sibling node that was introduced either through
Builder::close, Builder::close_at, or
Builder::close_at_with.
§Errors
Errors with Error::Overflow in case we run out of node
identifiers.
§Examples
let mut tree = syntree::Builder::new();
tree.open("root")?;
tree.open("child")?;
tree.close()?;
tree.open("child")?;
tree.close()?;
tree.close()?;Sourcepub fn open_with(
&mut self,
data: T,
span: Span<F::Index>,
) -> Result<F::Pointer, Error<F::Error>>
pub fn open_with( &mut self, data: T, span: Span<F::Index>, ) -> Result<F::Pointer, Error<F::Error>>
Start a node with the given data and span.
This pushes a new link with the given type onto the stack which links
itself onto the last sibling node that was introduced either through
Builder::close, Builder::close_at or Builder::close_at_with.
This does not advance the cursor position, in order to fix tree
construction use Builder::set_cursor.
§Errors
Errors with Error::Overflow in case we run out of node
identifiers.
§Examples
use syntree::Span;
let mut tree = syntree::Builder::new();
tree.open("root")?;
tree.open_with("child", Span::new(0, 3))?;
tree.close()?;
tree.open_with("child", Span::new(3, 6))?;
tree.close()?;
tree.close()?;
let tree = tree.build()?;
let expected = syntree::tree! {
("root", (0, 6)) => {
("child", (0, 3)) => {},
("child", (3, 6)) => {}
}
};
assert_eq!(tree, expected);Sourcepub fn close(&mut self) -> Result<(), Error<F::Error>>
pub fn close(&mut self) -> Result<(), Error<F::Error>>
End a node being built.
This will pop a value of the stack, and set that value as the next
sibling which will be used with Builder::open.
§Errors
This call must be balanced with a prior call to Builder::open.
If not this will result in an Error::CloseError being raised.
§Examples
let mut tree = syntree::Builder::new();
tree.open("root")?;
tree.open("child")?;
tree.close()?;
tree.open("child")?;
tree.close()?;
tree.close()?;Sourcepub fn token(
&mut self,
value: T,
len: F::Length,
) -> Result<F::Pointer, Error<F::Error>>
pub fn token( &mut self, value: T, len: F::Length, ) -> Result<F::Pointer, Error<F::Error>>
Declare a token with the specified value and a corresponding len.
A token is always a terminating element without children.
§Errors
Errors with Error::Overflow in case we run out of token
identifiers, or Error::TokenOrder if the token would start before
the end of the previous token, which happens after
Builder::set_cursor moves the cursor back.
§Examples
let mut tree = syntree::Builder::new();
tree.open("child")?;
tree.token("lit", 4)?;
tree.close()?;
let tree = tree.build()?;
let expected = syntree::tree! {
"child" => {
("lit", 4)
}
};
assert_eq!(tree, expected);Sourcepub fn token_with(
&mut self,
value: T,
span: Span<F::Index>,
) -> Result<F::Pointer, Error<F::Error>>
pub fn token_with( &mut self, value: T, span: Span<F::Index>, ) -> Result<F::Pointer, Error<F::Error>>
Insert a token with a custom span.
The span is joined into the spans of the enclosing nodes and the tree. Tokens are stored in source order, so a token can’t start before the end of the previous one, but it may leave a gap after it.
§Errors
Errors with Error::Overflow in case we run out of token
identifiers, or Error::TokenOrder if span starts before the end
of the previous token or ends before it starts.
§Examples
use syntree::Span;
let mut tree = syntree::Builder::new();
tree.open_with("child", Span::new(0, 10))?;
tree.token_with("lit", Span::new(2, 4))?;
tree.token_with("lit2", Span::new(4, 6))?;
tree.close()?;
let tree = tree.build()?;
let child = tree.first().ok_or("missing child")?;
assert_eq!(child.span(), &Span::new(0, 10));
let spans = child.children().map(|n| (n.value(), n.span())).collect::<Vec<_>>();
assert_eq!(spans, [("lit", Span::new(2, 4)), ("lit2", Span::new(4, 6))]);
assert_eq!(tree.span(), &Span::new(0, 10));Tokens with spans forces the cursor to be set to the end of the span.
use syntree::Span;
let mut tree = syntree::Builder::new();
tree.open("child")?;
tree.token_with("lit", Span::new(2, 4))?;
tree.token_with("lit2", Span::new(4, 6))?;
assert_eq!(*tree.cursor(), 6);
tree.token("lit3", 6)?;
tree.close()?;
let tree = tree.build()?;
let child = tree.first().ok_or("missing child")?;
assert_eq!(child.span(), &Span::new(0, 12));
let lit3 = child.last().ok_or("missing lit3")?;
assert_eq!(lit3.value(), "lit3");
assert_eq!(lit3.span(), &Span::new(6, 12));
assert_eq!(tree.span(), &Span::new(0, 12));Sourcepub fn token_empty(&mut self, value: T) -> Result<F::Pointer, Error<F::Error>>
pub fn token_empty(&mut self, value: T) -> Result<F::Pointer, Error<F::Error>>
Declare a token with the specified value and an empty length.
A token is always a terminating element without children.
§Errors
Errors with Error::Overflow in case we run out of token
identifiers, or Error::TokenOrder if the token would start before
the end of the previous token, which happens after
Builder::set_cursor moves the cursor back.
§Examples
let mut tree = syntree::Builder::new();
tree.open("child")?;
tree.token_empty("lit")?;
tree.close()?;
let tree = tree.build()?;
let expected = syntree::tree! {
"child" => {
"lit"
}
};
assert_eq!(tree, expected);Sourcepub fn trivia(
&mut self,
value: T,
len: F::Length,
) -> Result<F::Pointer, Error<F::Error>>
pub fn trivia( &mut self, value: T, len: F::Length, ) -> Result<F::Pointer, Error<F::Error>>
Insert a trivia token with the given length, such as whitespace or a comment.
Trivia is stored like any other token, so the spans of the enclosing
nodes and of the tree cover it and the source round-trips losslessly.
It is only hidden from iteration: Node::children, Node::walk
and the other iterators skip trivia unless asked to include it with
with_trivia(). Point accessors such as Node::first or
Token::next are structural and do see it. Use Token::is_trivia
to tell it apart.
§Errors
Errors like Builder::token.
§Examples
let mut tree = syntree::Builder::new();
tree.open("call")?;
tree.token("ident", 3)?;
tree.trivia("whitespace", 1)?;
tree.token("paren", 2)?;
tree.close()?;
let tree = tree.build()?;
let call = tree.first().and_then(|e| e.into_node()).ok_or("missing call")?;
assert_eq!(call.span(), &syntree::Span::new(0, 6));
let kinds = call.children().map(|e| e.value()).collect::<Vec<_>>();
assert_eq!(kinds, ["ident", "paren"]);
let kinds = call.children().with_trivia().map(|e| e.value()).collect::<Vec<_>>();
assert_eq!(kinds, ["ident", "whitespace", "paren"]);Sourcepub fn trivia_with(
&mut self,
value: T,
span: Span<F::Index>,
) -> Result<F::Pointer, Error<F::Error>>
pub fn trivia_with( &mut self, value: T, span: Span<F::Index>, ) -> Result<F::Pointer, Error<F::Error>>
Insert a trivia token with a custom span. This is Builder::trivia
with an explicit span, like Builder::token_with is to
Builder::token.
§Errors
Errors like Builder::token_with.
§Examples
use syntree::Span;
let mut tree = syntree::Builder::new();
tree.token_with("ident", Span::new(0, 3))?;
tree.trivia_with("comment", Span::new(4, 9))?;
let tree = tree.build()?;
assert_eq!(tree.span(), &Span::new(0, 9));
assert_eq!(tree.children().count(), 1);
let comment = tree.last().and_then(|e| e.into_token()).ok_or("missing comment")?;
assert!(comment.is_trivia());
assert_eq!(comment.span(), Span::new(4, 9));Sourcepub fn checkpoint(&mut self) -> Result<Checkpoint<F::Pointer>, Error<F::Error>>
pub fn checkpoint(&mut self) -> Result<Checkpoint<F::Pointer>, Error<F::Error>>
Get a checkpoint corresponding to the current position in the tree.
Checkpoints are only meaningful to the builder that handed them out. A
checkpoint used on another builder refers to that builder’s checkpoint
with the same index, or raises Error::MissingCheckpoint if it has
none.
§Errors
Errors with Error::Flavor if the checkpoint can’t be stored.
§Examples
let mut tree = syntree::Builder::new();
let c = tree.checkpoint()?;
tree.open("child")?;
tree.token("lit", 3)?;
tree.close()?;
tree.close_at(c, "root")?;
let tree = tree.build()?;
let expected = syntree::tree! {
"root" => {
"child" => {
("lit", 3)
}
}
};
assert_eq!(tree, expected);Sourcepub fn close_at(
&mut self,
c: Checkpoint<F::Pointer>,
data: T,
) -> Result<F::Pointer, Error<F::Error>>
pub fn close_at( &mut self, c: Checkpoint<F::Pointer>, data: T, ) -> Result<F::Pointer, Error<F::Error>>
Insert a node that wraps from the given checkpointed location.
§Errors
The checkpoint being closed must be a sibling. Otherwise a
Error::CloseAtError will be raised.
A checkpoint this builder did not hand out raises
Error::MissingCheckpoint.
§Examples
let mut tree = syntree::Builder::new();
let c = tree.checkpoint()?;
tree.token("lit", 3)?;
tree.close_at(c, "root")?;
let tree = tree.build()?;
let expected = syntree::tree! {
"root" => {
("lit", 3)
}
};
assert_eq!(tree, expected);More complex example:
let mut tree = syntree::Builder::new();
let c = tree.checkpoint()?;
tree.open("number")?;
tree.token("lit", 3)?;
tree.close()?;
tree.token("whitespace", 1)?;
tree.open("number")?;
tree.token("lit", 2)?;
tree.close()?;
tree.close_at(c, "root")?;
let tree = tree.build()?;
let expected = syntree::tree! {
"root" => {
"number" => {
("lit", 3)
},
("whitespace", 1),
"number" => {
("lit", 2)
},
}
};
assert_eq!(tree, expected);Adding a token after a checkpoint:
let mut tree = syntree::Builder::new();
let c = tree.checkpoint()?;
tree.open("child")?;
tree.token("lit", 3)?;
tree.close()?;
tree.close_at(c, "root")?;
tree.token("sibling", 3)?;
let tree = tree.build()?;
let lit = tree.node_with_range(0..3).ok_or("missing at 0..3")?;
assert_eq!(lit.value(), "lit");
let child = lit.parent().ok_or("missing child")?;
assert_eq!(child.value(), "child");
let root = lit.ancestors().last().ok_or("missing root")?;
assert_eq!(root.value(), "root");
assert_eq!(root.parent(), None);
let expected = syntree::tree! {
"root" => {
"child" => {
("lit", 3)
}
},
("sibling", 3)
};
assert_eq!(tree, expected);Sourcepub fn close_at_with(
&mut self,
c: Checkpoint<F::Pointer>,
data: T,
span: Span<F::Index>,
) -> Result<F::Pointer, Error<F::Error>>
pub fn close_at_with( &mut self, c: Checkpoint<F::Pointer>, data: T, span: Span<F::Index>, ) -> Result<F::Pointer, Error<F::Error>>
Insert a node with a custom length.
§Errors
The checkpoint being closed must be a sibling. Otherwise a
Error::CloseAtError will be raised.
A checkpoint this builder did not hand out raises
Error::MissingCheckpoint.
§Examples
use syntree::Span;
let mut tree = syntree::Builder::new();
let c = tree.checkpoint()?;
tree.token_with("lit", Span::new(1, 3))?;
tree.close_at_with(c, "custom", Span::new(0, 6))?;
tree.token_with("lit2", Span::new(6, 8))?;
let tree = tree.build()?;
let root = tree.first().ok_or("missing root")?;
assert_eq!(root.value(), "custom");
assert_eq!(root.span(), &Span::new(0, 6));
assert_eq!(tree.span(), &Span::new(0, 8));Sourcepub fn build(self) -> Result<Tree<T, F>, Error<F::Error>>
pub fn build(self) -> Result<Tree<T, F>, Error<F::Error>>
Build a Tree from the current state of the builder.
§Errors
This requires the stack in the builder to be empty. Otherwise a
Error::BuildError will be raised.
§Examples
let mut tree = syntree::Builder::new();
tree.open("child")?;
tree.token("number", 3)?;
tree.close()?;
tree.open("child")?;
tree.close()?;
let tree = tree.build()?;
let expected = syntree::tree! {
"child" => {
("number", 3)
},
"child" => {},
};
assert_eq!(tree, expected);If a tree is unbalanced during construction, building will fail with an error:
use syntree::{Error, Span, Builder};
let mut tree = syntree::Builder::new();
tree.open("number")?;
tree.token("lit", 3)?;
tree.close()?;
tree.open("number")?;
// "number" is left open.
assert!(matches!(tree.build(), Err(Error::BuildError)));