Skip to main content

Crate rustler_match_spec

Crate rustler_match_spec 

Source
Expand description

Erlang-style match specifications for Rustler native event streams.

rustler_match_spec is a small selector engine for Rustler NIFs that expose many structured native facts to Elixir. A NIF can decode an Elixir match-spec term into a Selector, stream parser- or analyzer-defined events through Selector::run_event, and return only the projected results.

This avoids the common pattern of serializing a large native AST or result tree to the BEAM just so Elixir can walk it and keep a few fields.

§Event model

Native events implement MatchEvent. The evaluator treats each event as a tuple-like record:

A match pattern such as {:import, source, start, finish} therefore matches an event whose tag is :import and whose positional fields 1, 2, and 3 bind to source, start, and finish.

§Rust integration sketch

use rustler::{Atom, Env, NifResult, Term};
use rustler_match_spec::{MatchEvent, Selector, ValueRef};

struct ImportEvent<'a> {
    import_atom: Atom,
    source: &'a str,
    start: u32,
    end: u32,
}

impl<'a> MatchEvent<'a> for ImportEvent<'a> {
    fn tag(&self) -> Atom { self.import_atom }
    fn arity(&self) -> usize { 4 }

    fn positional_field(&self, index: usize) -> Option<ValueRef<'a>> {
        match index {
            1 => Some(ValueRef::Str(self.source)),
            2 => Some(ValueRef::U64(self.start as u64)),
            3 => Some(ValueRef::U64(self.end as u64)),
            _ => None,
        }
    }

    fn field(&self, _name: Atom) -> Option<ValueRef<'a>> { None }
}

fn select_imports<'env>(env: Env<'env>, selector: Selector) -> NifResult<Vec<Term<'env>>> {
    let mut out = Vec::new();

    for event in native_import_events() {
        selector.run_event(env, &event, &mut out)?;
    }

    Ok(out)
}

The companion Elixir package provides RustlerMatchSpec.match_spec/1, RustlerMatchSpec.compile/1, and RustlerMatchSpec.select/2.

Structs§

Selector

Enums§

ValueRef
A borrowed value exposed by a native event.

Traits§

MatchEvent
A parser-defined event that can be matched by a selector.