Struct syntree::Builder

source ·
pub struct Builder<T, I, W>where
    I: Index,
    W: Width,{ /* 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 three type parameters of the tree determines the following properties:

  • T is the data stored in the tree.
  • I determines the numerical bounds of spans stored in the tree through the Index trait, if set to Empty the tree does not store any spans.
  • W determines the bounds of pointers in the tree through the Width trait, this decides how many elements that can be stored in the tree.

To use the default values, use the Builder::new constructor.

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, u32, usize>

source

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, I, W> Builder<T, I, W>where I: Index, W: Width,

source

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};

let mut tree: Builder<_, Empty, usize> = 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<_, Empty, u32> = syntree::tree_with! {
    "root" => {
        "child" => {
            "token"
        },
        "child2" => {}
    }
};

assert_eq!(tree, expected);
source

pub const fn cursor(&self) -> &I

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);
source

pub fn open(&mut self, data: T) -> Result<W::Pointer, 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 ben introduced either through Builder::close or Builder::close_at.

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()?;
source

pub fn close(&mut self) -> Result<(), 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()?;
source

pub fn token(&mut self, value: T, len: I::Length) -> Result<W::Pointer, 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 node identifiers.

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);
source

pub fn token_empty(&mut self, value: T) -> Result<W::Pointer, 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 node identifiers.

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);
source

pub fn checkpoint(&mut self) -> Result<Checkpoint<W::Pointer>, Error>

Get a checkpoint corresponding to the current position in the tree.

Mixing checkpoints

Note that using checkpoints from a different tree doesn’t have a well-specified behavior - it might seemingly work or it might raise an error during closing such as Error::MissingNode.

The following is not well-defined, here we’re using a checkpoint for a different tree but it “just happens” to work because both trees have identical internal topologies:

use syntree::{Builder, Error};

let mut a = Builder::new();
let mut b = Builder::new();

let c = b.checkpoint()?;

a.open("child")?;
a.close()?;

b.open("child")?;
b.close()?;

// Checkpoint use from different tree.
a.close_at(&c, "root")?;

let unexpected = syntree::tree! {
    "root" => {
        "child"
    }
};

assert_eq!(a.build()?, unexpected);
Errors

Errors with Error::Overflow in case we run out of node identifiers.

Panics

This panics if the number of nodes are too many to fit in a vector on your architecture. This corresponds to usize::MAX.

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);
source

pub fn close_at( &mut self, c: &Checkpoint<W::Pointer>, data: T ) -> Result<W::Pointer, 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.

This might also sporadically error with Error::MissingNode, in case a checkpoint is used that was constructed from another tree.

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 child = tree.node_with_range(0..3).ok_or("missing at 0..3")?;
assert_eq!(*child.value(), "child");

let lit = tree.first().and_then(|n| n.first()).and_then(|n| n.first()).ok_or("expected lit")?;
assert_eq!(*lit.value(), "lit");

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);
source

pub fn build(self) -> Result<Tree<T, I, W>, 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)));

Trait Implementations§

source§

impl<T, I, W> Clone for Builder<T, I, W>where T: Clone, I: Index, I::Indexes<W::Pointer>: Clone, W: Width, W::Pointer: Clone,

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T: Debug, I, W> Debug for Builder<T, I, W>where I: Index + Debug, W: Width + Debug, W::Pointer: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T, I, W> Default for Builder<T, I, W>where I: Index, W: Width,

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<T, I, W> !RefUnwindSafe for Builder<T, I, W>

§

impl<T, I, W> !Send for Builder<T, I, W>

§

impl<T, I, W> !Sync for Builder<T, I, W>

§

impl<T, I, W> Unpin for Builder<T, I, W>where I: Unpin, T: Unpin, <I as Index>::Indexes<<W as Width>::Pointer>: Unpin, <W as Width>::Pointer: Unpin,

§

impl<T, I, W> !UnwindSafe for Builder<T, I, W>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.