从文件中读取字节并使用 `pom` 解析器库解析它们
Reading bytes from a file and parsing them with `pom` parser library
我正在尝试使用 pom 编写解析器,这很棒 - 编写解析器和输入字符串文字作为测试数据没有问题。但是,当我尝试 运行 它从文件中获取字节时,它会阻塞;
108 | fn parse_files() -> Result<(), Box<dyn Error>> {
109 | let byte_vec: Vec<u8> = std::fs::read("assets/valid_so_far.idl")?;
110 | let byte_slice: &[u8] = &byte_vec;
| ^^^^^^^^^ borrowed value does not live long enough
111 | let idl_parser = idl();
112 | let parse_result = idl_parser.parse(byte_slice)?;
| ---------------------------- argument requires that `byte_vec` is borrowed for `'static`
113 |
114 | Ok(())
115 | }
| - `byte_vec` dropped here while still borrowed
我看不出这里出了什么问题。我无法解释这里的编译器错误,我不明白为什么这里的生命周期不正常。
第 109 行的 parse
函数具有以下签名:
fn parse(&self, input: &'a [I]) -> Result<O>
pub type Result<O> = ::std::result::Result<O, Error>;
pom::Parser<I, O>
是 pom::parser::Parser<'static, I, O>
的别名。因此,如果您使用此别名,parse
函数中的 'a
生命周期实际上是 'static
。直接使用 pom::parser::Parser
结构与自定义(可能被省略 - 你不必写它)生命周期。
no problems writing the parsers and feeding in string literal as test data.
这是可行的,因为所有字符串文字都有 the 'static
lifetime。当您改为从文件读取时,潜在的 'static
消失了。代码的行为实际上发生了变化,因此它触发了错误。
问题是为什么您的解析器实现首先需要 'static
输入。我怀疑 pom
自述文件中给出的示例应该归咎于此。例如它有以下代码:
use pom::Parser;
fn space() -> Parser<u8, ()> {
one_of(b" \t\r\n").repeat(0..).discard()
}
pom::Parser<u8, ()>
实际上是pom::parser::Parser<'static, u8, ()>
的别名。如果写成:
use pom::parser::Parser;
fn space<'a>() -> Parser<'a, u8, ()> {
one_of(b" \t\r\n").repeat(0..).discard()
}
那么它应该能够处理 'static
和非 'static
输入。对您的解析器代码进行类似的更改,它将再次运行。
我正在尝试使用 pom 编写解析器,这很棒 - 编写解析器和输入字符串文字作为测试数据没有问题。但是,当我尝试 运行 它从文件中获取字节时,它会阻塞;
108 | fn parse_files() -> Result<(), Box<dyn Error>> {
109 | let byte_vec: Vec<u8> = std::fs::read("assets/valid_so_far.idl")?;
110 | let byte_slice: &[u8] = &byte_vec;
| ^^^^^^^^^ borrowed value does not live long enough
111 | let idl_parser = idl();
112 | let parse_result = idl_parser.parse(byte_slice)?;
| ---------------------------- argument requires that `byte_vec` is borrowed for `'static`
113 |
114 | Ok(())
115 | }
| - `byte_vec` dropped here while still borrowed
我看不出这里出了什么问题。我无法解释这里的编译器错误,我不明白为什么这里的生命周期不正常。
第 109 行的 parse
函数具有以下签名:
fn parse(&self, input: &'a [I]) -> Result<O>
pub type Result<O> = ::std::result::Result<O, Error>;
pom::Parser<I, O>
是 pom::parser::Parser<'static, I, O>
的别名。因此,如果您使用此别名,parse
函数中的 'a
生命周期实际上是 'static
。直接使用 pom::parser::Parser
结构与自定义(可能被省略 - 你不必写它)生命周期。
no problems writing the parsers and feeding in string literal as test data.
这是可行的,因为所有字符串文字都有 the 'static
lifetime。当您改为从文件读取时,潜在的 'static
消失了。代码的行为实际上发生了变化,因此它触发了错误。
问题是为什么您的解析器实现首先需要 'static
输入。我怀疑 pom
自述文件中给出的示例应该归咎于此。例如它有以下代码:
use pom::Parser;
fn space() -> Parser<u8, ()> {
one_of(b" \t\r\n").repeat(0..).discard()
}
pom::Parser<u8, ()>
实际上是pom::parser::Parser<'static, u8, ()>
的别名。如果写成:
use pom::parser::Parser;
fn space<'a>() -> Parser<'a, u8, ()> {
one_of(b" \t\r\n").repeat(0..).discard()
}
那么它应该能够处理 'static
和非 'static
输入。对您的解析器代码进行类似的更改,它将再次运行。