Skip to main content

Fold

Trait Fold 

pub trait Fold {
    type Value;

    // Required methods
    fn leaf(&mut self, name: &str, leaf: FoldLeaf<'_>) -> Self::Value;
    fn rule(&mut self, name: &str, children: Vec<Self::Value>) -> Self::Value;
}
Expand description

A bottom-up fold algebra: what a leaf is worth, and how a rule combines its children’s values. The Rust sibling of Lark’s Transformer — both methods dispatch on a display name, with the same shape: rule is called with the rule’s DISPLAY name (aliases included) and the already-folded children in order; leaf with the token TYPE name ("NUMBER" — or "" for the hole a [...] optional inserts under maybe_placeholders).

use hyperlark::{Fold, FoldLeaf, Lark, LarkOptions};

struct Depth;
impl Fold for Depth {
    type Value = usize;
    fn leaf(&mut self, _: &str, _: FoldLeaf<'_>) -> usize { 0 }
    fn rule(&mut self, _: &str, kids: Vec<usize>) -> usize {
        1 + kids.into_iter().max().unwrap_or(0)
    }
}

let parser = Lark::from_lark_source(
    "start: \"(\" start \")\" | \"x\"",
    LarkOptions::default(),
).unwrap();
// One algebra, applied to many results — it is just a value.
let mut depth = Depth;
assert_eq!(parser.parse("((x))").unwrap().fold(&mut depth), 3);
assert_eq!(parser.parse("x").unwrap().fold(&mut depth), 1);

Required Associated Types§

type Value

Required Methods§

fn leaf(&mut self, name: &str, leaf: FoldLeaf<'_>) -> Self::Value

fn rule(&mut self, name: &str, children: Vec<Self::Value>) -> Self::Value

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

§

impl<T, L, R> Fold for FnFold<L, R>
where L: FnMut(&str, FoldLeaf<'_>) -> T, R: FnMut(&str, Vec<T>) -> T,

§

type Value = T