| 1 | use peg::RuleResult; |
| 2 | |
| 3 | peg::parser!( grammar test() for str { |
| 4 | rule position() -> usize = #{|input, pos| RuleResult::Matched(pos, pos)} |
| 5 | pub rule test1() -> usize = ['a']* p1:position() ['b']* { p1 } |
| 6 | |
| 7 | pub rule fail() -> usize = #{|input, pos| RuleResult::Failed} |
| 8 | |
| 9 | rule custom_literal(literal: &str) = #{|input, pos| { |
| 10 | let l = literal.len(); |
| 11 | if input.len() >= pos + l && &input.as_bytes()[pos..pos + l] == literal.as_bytes() { |
| 12 | RuleResult::Matched(pos + l, ()) |
| 13 | } else { |
| 14 | RuleResult::Failed |
| 15 | } |
| 16 | }} |
| 17 | pub rule test2() = custom_literal("foo") "_" custom_literal("bar") |
| 18 | }); |
| 19 | |
| 20 | fn main() { |
| 21 | assert_eq!(test::test1("aaaabb"), Ok(4)); |
| 22 | assert_eq!(test::fail("aaaabb").unwrap_err().location.offset, 0); |
| 23 | |
| 24 | assert_eq!(test::test2("foo_bar"), Ok(())); |
| 25 | } |