RustlerMatchSpec (rustler_match_spec v0.1.0)

Copy Markdown

Small, Erlang-inspired match specifications for Rustler event streams.

RustlerMatchSpec provides an Elixir macro that turns a restricted, idiomatic pattern-matching syntax into data shaped like Erlang match specifications:

[{match_head, match_guards, match_body}]

Parser/NIF packages can use this data to select and project native events without serializing whole native ASTs to Elixir.

Example

import RustlerMatchSpec

spec =
  match_spec do
    {:css_url, url, start, finish} when is_binary(url) ->
      %{url: url, start: start, end: finish}
  end

spec == [
  {{:css_url, :"$1", :"$2", :"$3"}, [{:is_binary, :"$1"}], [
    %{url: :"$1", start: :"$2", end: :"$3"}
  ]}
]

This package intentionally does not define parser-specific event names. OXC, Vize, or an HTML parser should define their own event constructors and return structs while reusing the same match-spec shape.

Summary

Types

An opaque native selector resource returned by compile/1.

t()

A compiled match specification term.

A match variable atom such as :'$1'.

Functions

Compile a match specification into an opaque native selector resource.

Compile restricted Elixir pattern syntax into a match-spec term.

Select projected results from a list of BEAM term events.

Returns a match variable atom, e.g. var(1) == :"$1".

Types

selector()

@opaque selector()

An opaque native selector resource returned by compile/1.

t()

@type t() :: [{term(), [term()], [term()]}]

A compiled match specification term.

variable()

@type variable() :: atom()

A match variable atom such as :'$1'.

Functions

compile(spec)

@spec compile(t()) :: selector()

Compile a match specification into an opaque native selector resource.

Reuse the returned selector when applying the same spec repeatedly.

match_spec(list)

(macro)

Compile restricted Elixir pattern syntax into a match-spec term.

Supported clause form:

pattern [when guard] -> body

Variables first seen in the pattern are assigned :"$1", :"$2", etc. The same variables can be referenced in guards and body terms.

select(events, spec_or_selector)

@spec select([term()], t() | selector()) :: [term()]

Select projected results from a list of BEAM term events.

The second argument can be either a raw match spec or a selector returned by compile/1. This is primarily the reference/test harness for the native evaluator. Parser packages should call the Rust crate directly from their own NIFs so native AST traversal and event projection stay in one native call.

var(index)

@spec var(pos_integer()) :: variable()

Returns a match variable atom, e.g. var(1) == :"$1".