我正在尝试创建一个解析器组合器。我定义了一个特征和一个trait Parser<'a> {
fn run(&self, input: &'a str) -> (Option<&'a str>, &'a str);
}
trait Parser<'a> {
fn run(&self, input: &'a str) -> (Option<&'a str>, &'a str);
}
pub struct Or<'a> {
p1: &'a Parser<'a>,
p2: &'a Parser<'a>,
}
impl<'a> Parser<'a> for Or<'a> {
fn run(&self, input: &'a str) -> (Option<&'a str>, &'a str) {
let (result, remainder) = self.p1.run(input);
match result {
Some(r) => (result, remainder),
None => self.p2.run(input),
}
}
}
impl<'a> Or<'a> {
fn new(p1: &'a Parser<'a>, p2: &'a Parser<'a>) -> Or<'a> {
Or { p1, p2 }
}
}
解析器:
Choice
现在我想定义一个pub struct Choice<'a> {
parsers: &'a Vec<&'a Parser<'a>>,
}
impl<'a> Choice<'a> {
fn new(parsers: &'a Vec<&'a Parser<'a>>) -> Choice<'a> {
Choice { parsers }
}
}
impl<'a> Parser<'a> for Choice<'a> {
fn run(&self, input: &'a str) -> (Option<&'a str>, &'a str) {
let parser: &Parser = self.parsers
.iter()
.fold(&AlwaysFails::new(), |sum, p2| &Or::new(sum, p2));
parser.run(input)
}
}
解析器,它应该迭代解析器向量并返回结果,如果它们中的任何一个成功:
AlwaysFails
(None, input)
是一个解析器,它总是返回pub struct AlwaysFails;
impl AlwaysFails {
fn new() -> Self {
AlwaysFails
}
}
impl<'a> Parser<'a> for AlwaysFails {
fn run(&self, input: &'a str) -> (Option<&'a str>, &'a str) {
(None, input)
}
}
的元组:
error[E0277]: the trait bound `&Parser<'a>: Parser<'_>` is not satisfied
--> src/main.rs:40:64
|
40 | .fold(&AlwaysFails::new(), |sum, p2| &Or::new(sum, p2));
| ^^ the trait `Parser<'_>` is not implemented for `&Parser<'a>`
|
= note: required for the cast to the object type `Parser<'_>`
我收到错误
{{1}}