[][src]Trait moore_common::score::NodeMaker

pub trait NodeMaker<I, N> {
    fn make(&self, id: I) -> Result<N>;
}

The NodeMaker trait allows for nodes to be generated from an ID.

This is useful in conjunction with the NodeStorage and Scoreboard traits. If a value is requested that the scoreboard cannot find, this trait allows for the node to be generated. For example, if the AST for a node is requested but does not exist, this trait can be implemented in such a way that said AST is loaded. This allows for complex on-demand loading and compilation to be implemented.

The nodes are expected to be owned either by the caller or some arena. Therefore only a reference to the created node is returned.

Example

use moore_common::score::{self, NodeMaker};

#[derive(PartialEq, Eq, Debug)]
struct Foo;
#[derive(PartialEq, Eq, Debug)]
struct Bar;

struct FooId(usize);
struct BarId(usize);

struct Table;

impl<'tn> NodeMaker<FooId, &'tn Foo> for Table {
    fn make(&self, id: FooId) -> score::Result<&'tn Foo> {
        static FOO: Foo = Foo;
        Ok(&FOO) // usually you would allocate this in an arena
    }
}

impl<'tn> NodeMaker<BarId, &'tn Bar> for Table {
    fn make(&self, id: BarId) -> score::Result<&'tn Bar> {
        static BAR: Bar = Bar;
        Ok(&BAR) // usually you would allocate this in an arena
    }
}

let tbl = Table;
let foo = tbl.make(FooId(1)).unwrap();
let bar = tbl.make(BarId(2)).unwrap();
assert_eq!(foo, &Foo);
assert_eq!(bar, &Bar);

// The following would produce a compiler error due to type mismatch:
// assert_eq!(foo, &Bar);
// assert_eq!(bar, &Foo);

Required methods

fn make(&self, id: I) -> Result<N>

Creates the node with the given ID.

Returns Err(()) upon failure. Note that the generated node has lifetime 'tn that outlives the NodeMaker. This is required to allow for the NodeMaker to generate multiple nodes at the same time. The generated nodes should be owned by an arena or the owner of the NodeMaker itself.

Loading content...

Implementors

Loading content...