我想解析一个由这个 BNF 表示的程序:
<log_and_expression> := <and_expression> (<space>* "&&" <space>* <and_expression>)*
<and_expression> := <unary_expression> (<space>* "&" <space>* <unary_expression>)*
<unary_expression> := ("&" <space>*)* <identifier>
<identifier> := "a" | "b" | "c" | ...
<space> := " " | "\t" | "\n" | "\r"
这个 BNF 解析小程序。log_and 表示逻辑与。
我使用解析器库 nom 编写了 Rust 程序:
use nom::{
branch::{alt, permutation},
bytes::complete::{escaped_transform, is_not, tag, take_while_m_n},
character::complete::{
char, digit1, hex_digit1, line_ending, multispace0, multispace1, none_of, space0, space1,
},
combinator::{all_consuming, map, opt, value},
error::VerboseError,
multi::{many0, many1},
number::complete::double,
sequence::{delimited, tuple},
IResult,
};
#[derive(Debug, PartialEq, Clone)]
pub struct LogAndExpression {
pub and_expression: AndExpression,
pub tail: Vec<AndExpression>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct AndExpression {
pub unary_expression: UnaryExpression,
pub tail: Vec<UnaryExpression>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct UnaryExpression {
pub unary_operators: Vec<String>,
pub identifier: String,
}
pub fn log_and_expression(s: &str) -> IResult<&str, LogAndExpression> {
map(
tuple((
and_expression,
many0(
map(
tuple((
multispace0,
tag("&&"),
multispace0,
and_expression,
)),
|(_, _, _, expression)| expression,
)
),
)),
|(expression, vec)| LogAndExpression {
and_expression: expression,
tail: vec,
},
)(s)
}
pub fn and_expression(s: &str) -> IResult<&str, AndExpression> {
map(
tuple((
unary_expression,
many0(
map(
tuple((
multispace0,
tag("&"),
multispace0,
unary_expression,
)),
|(_, _, _, expression)| expression,
)
),
)),
|(expression, vec)| AndExpression {
unary_expression: expression,
tail: vec,
},
)(s)
}
pub fn unary_expression(s: &str) -> IResult<&str, UnaryExpression> {
map(
tuple((
many0(
map(
tuple((
tag("&"),
multispace0
)),
|(opr, _): (&str, &str)| opr.to_owned(),
)
),
is_not(" &"),
)),
|(unary_operators, identifier)| UnaryExpression {
unary_operators: unary_operators,
identifier: identifier.to_owned(),
},
)(s)
}
fn main() {
println!("{:?}", log_and_expression("a && b"));
}
此代码输出 parse 的结果a && b
。
log_and_expression
解析程序。
我想要的结果是a LogAnd b
。但结果是:
Ok(("", LogAndExpression { and_expression: AndExpression { unary_expression: UnaryExpression { unary_operators: [], identifier: "a" }, tail: [UnaryExpression { unary_operators: ["&"], identifier: "b" }] }, tail: [] }))
这意味着a And &b
。
如何使用 nom 正确解析该程序?