gpt4 book ai didi

rust - nom 解析器借用检查器问题

转载 作者:行者123 更新时间:2023-11-29 08:04:44 26 4
gpt4 key购买 nike

我有这个使用 nom 4.2.2 的 Rust 程序。 (我冒昧地扩展了 nom 解析器功能。)

extern crate failure;
extern crate nom;

use failure::Error;
use std::fs::File;
use std::io::Read;

fn nom_parser(i: &[u8]) -> ::nom::IResult<&[u8], String, u32> {
{ ::nom::lib::std::result::Result::Ok((i, ("foo".to_owned()))) }
}

fn my_parser(buf: &[u8]) -> Result<(&[u8], String), Error> {
Ok((buf, "foo".to_owned()))
}

fn main() -> Result<(), Error> {
let handler = |mut entries: String| { entries.clear() };
loop {
let mut buf = Vec::new();
File::open("/etc/hosts")?.read_to_end(&mut buf)?;
let res = nom_parser(&buf)?.1;
// let res = my_parser(&buf)?.1;
handler(res);
}
}

使用 rustc 1.33.0 (2aa4c46cf 2019-02-28) 编译此程序会产生以下问题:

error[E0597]: `buf` does not live long enough
--> nom-parsing/src/main.rs:21:26
|
21 | let res = nom_parser(&buf)?.1;
| -----------^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `buf` is borrowed for `'static`
...
24 | }
| - `buf` dropped here while still borrowed

切换到注释掉的解析器版本编译就好了。 my_parsernom_parser 有何不同?谁在借buf?我应该如何更改程序才能安抚借阅检查员?

最佳答案

let res = nom_parser(&buf)?.1;
^ here

您正在使用 ?运算符将错误传播出 main . IResult<&[u8], String, u32> = Result<(&[u8], String), nom::Err<&[u8], u32>> .所以如果出现错误 &buf作为它的一部分返回,所以即使在 main 之后它也必须保持事件状态函数退出,但不会因为 bufmain里面的局部变量.

在你的例子中是 nom_parser从不返回错误,但验证只关心类型和函数签名。

要修复它,您应该在向上传播之前以某种方式处理错误。例如:

let res = nom_parser(&buf).map_err(|_| failure::format_err!("Parsing failed!"))?.1;

请注意 ErrIResult并不总是硬错误。可能是 nom::Err::Incomplete ,这意味着如果提供更多数据,解析可能会成功,或者 nom::Err::Error这意味着输入与解析器不匹配(因此 alt! 中的另一个解析器可能会成功),或者 nom::Err::Failure ,这意味着在解析过程中确实出了点问题。根据情况,您可以将它们都视为失败,或者以不同的方式处理它们。

关于rust - nom 解析器借用检查器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55184864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com