1

添加到 nom 的简单错误处理程序

第一个编译没有错误,第二个出错了

use nom::*;
use std::str;
// This works
named!(
    field<&str>,
    map!(
        complete!(add_return_error!(
            ErrorKind::Custom(1),
            preceded!(
                tag!("."),
                recognize!(many1!(
                    alt!(alphanumeric => { |_| true } | char!('_') => {|_| true})
                ))
            )
        )),
        |v| str::from_utf8(v).unwrap()
    )
);

// This doesn't compile
named!(
    entity<&str>,
    add_return_error!(
        ErrorKind::Custom(2),
        map!(
            recognize!(many1!(
                alt!(alphanumeric => { |_| true } | char!('_') => {|_| true})
            )),
            |v| str::from_utf8(v).unwrap()
        )
    )
);

错误是

cargo build
   Compiling pdl_parser v0.1.0 (file:///H:/parser)
error[E0282]: type annotations needed
  --> src\pdl_parser.rs:72:1
   |
72 | / named!(
73 | |     entity<&str>,
74 | |     add_return_error!(
75 | |         ErrorKind::Custom(2),
...  |
82 | |     )
83 | | );
   | |__^ cannot infer type for `E`
   |
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

为什么第一个有效而第二个无效?我能做些什么来解决它?我尝试将第二个签名更改为entity<&[u8],&str,ErrorKind>然后更改为i32u32没有成功。

4

1 回答 1

0

cannot infer type for E错误的解决方案是将解析步骤分开,这样编译器就不会那么混乱。

将解析器组合器重写为

named!(
    entity_name<Vec<u8>>,
    many1!(alt!(alphanumeric => { |x : &[u8]| x[0] } | char!('_') => {|_| b'_'}))
);
named!(
    entity<&[u8],&str,i32>,
    add_return_error!(
        ErrorKind::Custom(2),
        map!(recognize!(entity_name),|v| str::from_utf8(v).unwrap())
    )
);

以及相应的测试

#[test]
fn parse_pdl_error_test() {
    assert_eq!(entity(b"_error_stack").to_result(), Ok("_error_stack"));
    assert_eq!(entity(b"[];']").to_result(), Err(ErrorKind::Custom(2)));
}
于 2018-03-21T09:31:46.180 回答