我正在使用nom 4.2.2为基于文本的格式编写解析器,我正在使用the whitespace facility来跳过空格。我必须使用自定义解析器,因为此格式将一些不常见的字符视为空格。按照该页面上的示例,我使用eat_separator
创建了一个。
如何有效地扩展我的空间解析器以消耗从#
到行尾的行注释?这些注释可以出现在字符串中除外。我总是想抛弃评论的内容:没有什么比预处理器指令更好的了。
这是一个棘手的问题;编写Python解析器时我也有它。
以下是我最终实现“换行符可选地以注释开头”的方式:
named!(pub newline<StrSpan, ()>,
map!(
many1!(
tuple!(
spaces_nonl,
opt!(preceded!(char!('#'), many0!(none_of!("\n")))),
char!('\n')
)
),
|_| ()
)
);
named!(pub spaces_nl<StrSpan, ()>,
map!(many0!(alt!(one_of!(" \t\x0c") => { |_|() } | escaped_newline | newline)), |_| ())
);
named!(pub spaces_nonl<StrSpan, ()>,
map!(many0!(alt!(one_of!(" \t\x0c") => { |_| () }|escaped_newline)), |_| ())
);
然后您可以使用它来重写ws!
以使用这个新函数(我从nom复制粘贴代码并替换了sep!
参数的名称):
/// Like `ws!()`, but ignores comments as well
macro_rules! ws_comm (
($i:expr, $($args:tt)*) => (
{
use nom::Convert;
use nom::Err;
match sep!($i, spaces_nl, $($args)*) {
Err(e) => Err(e),
Ok((i1,o)) => {
match spaces_nl(i1) {
Err(e) => Err(Err::convert(e)),
Ok((i2,_)) => Ok((i2, o))
}
}
}
}
)
);