Using Pest.rs, how can I add a capture to the tree?

144 Views Asked by At

Let's say I have a rule like this,

conf = { SOI ~ ("FOO" ~ "BAR"?) ~ NEWLINE ~ EOI }

This will produce a tree that does not distinguish between "FOO" and "FOOBAR" this,

Pair {
    rule: conf,
    span: Span {
        str: "FOOBAR\n",
        start: 0,
        end: 7,
    },
    inner: [
        Pair {
            rule: EOI,
            span: Span {
                str: "",
                start: 7,
                end: 7,
            },
            inner: [],
        },
    ],
}

However, this isn't what I want, what I want is a tree like this,

Pair {
    rule: conf,
    span: Span {
        str: "FOOBAR\n",
        start: 0,
        end: 7,
    },
    inner: [
        Pair {
            rule: term,
            span: Span {
                str: "FOOBAR",
                start: 0,
                end: 6,
            },
            inner: [],
        },
        Pair {
            rule: EOI,
            span: Span {
                str: "",
                start: 7,
                end: 7,
            },
            inner: [],
        },
    ],
}

Which I could produce with this,

term = { "FOO" ~ "BAR"? }
conf = { SOI ~ term ~ NEWLINE ~ EOI }

But I don't want to actually have to specify a term for this, I want to be able to inline the specification. I want to do this because essentially I am trying to model these conditionals, ifdef, ifndef, elifdef, elifndef, else, and endif. And It would like cleaner to say,

conditional = {
  ( "ifndef" | "ifdef" ) ~ conditional_block
  ( ( "elifndef" | "elifdef" ) ~ conditional_block )?
  ( "else" ~ conditional_block )?
}

Then to have model each ifdef, ifndef; and elifdef, elifndef as two separate tokens that will only be used there.

_if      = { ".ifndef" | ".ifdef" }
_elseif  = { ".elifndef" | ".elifdef" }
_else    = { ".else" }
_endif   = { ".endif" }
conditional = {
  _if ~ conditional_block
  ~ ( _elseif ~ conditional_block )?
  ~ ( _else ~ conditional_block )?
  ~ _endif
}
0

There are 0 best solutions below