welly_parser

Trait Tree

source
pub trait Tree: Debug + AsAny {
    // Provided method
    fn declare_keywords(declare: impl FnMut(&'static str, Self))
       where Self: Sized { ... }
}
Expand description

A type that represents a parse tree.

There are many types that implement Tree. It would be inconvenient to define an enum that can contain any of them. Instead, we use dyn Tree. You can use the methods of dyn Tree to match its actual type:

use welly_parser::{Tree};

// Invent a new kind of `Tree`.
#[derive(Debug)]
struct Fruit(&'static str);
impl Tree for Fruit {}

// An example `Fruit` wrapped as a `dyn Tree`.
let tree: Box<dyn Tree> = Box::new(Fruit("Apple"));

// Test whether `tree` is a `Fruit`.
let is_fruit: bool = tree.is::<Fruit>();
println!("{}", is_fruit);

// Borrow the `Fruit`.
let borrowed_fruit: Option<&Fruit> = tree.downcast_ref::<Fruit>();
println!("{}", borrowed_fruit.expect("Not a Fruit").0);

// Move the `Fruit`.
let owned_fruit: Result<Box<Fruit>, Box<dyn Tree>> = tree.downcast::<Fruit>();
println!("{}", owned_fruit.expect("Not a Fruit").0);

Provided Methods§

source

fn declare_keywords(declare: impl FnMut(&'static str, Self))
where Self: Sized,

declare() all the keywords whose parse trees are Selfs.

The default implementation declares no keywords.

Implementations§

source§

impl dyn Tree

source

pub fn is<T: Tree>(&self) -> bool

Returns true if the actual type of self is T.

source

pub fn downcast_ref<T: Tree>(&self) -> Option<&T>

Returns Some if the actual type of self is T.

source

pub fn downcast<T: Tree>(self: Box<Self>) -> Result<Box<T>, Box<Self>>

Returns Ok if the actual type of self is T.

Implementations on Foreign Types§

source§

impl Tree for char

source§

impl Tree for ()

Implementors§