Attribute Macro rust_sitter::leaf

source ·
#[leaf]
Expand description

Defines a field which matches a specific token in the source string. The token can be defined by passing one of two arguments

  • text: a string literal that will be exactly matched
  • pattern: a regular expression that will be matched against the source string

If the resulting token needs to be converted into a richer type at runtime, such as a number, then the transform argument can be used to specify a function that will be called with the token’s text.

The attribute can also be applied to a struct or enum variant with no fields.

§Examples

Using the leaf attribute on a field:

Number(
    #[rust_sitter::leaf(pattern = r"\d+", transform = |v| v.parse().unwrap())]
    u32
)

Using the attribute on a unit struct or unit enum variant:

#[rust_sitter::leaf(text = "9")]
struct BigDigit;

enum SmallDigit {
    #[rust_sitter::leaf(text = "0")]
    Zero,
    #[rust_sitter::leaf(text = "1")]
    One,
}