J-F-Liu / pom

PEG parser combinators using operator overloading without macros.
MIT License
500 stars 31 forks source link

Function parser parse input from IO cause lifetime issues #33

Closed hulufei closed 5 years ago

hulufei commented 5 years ago

Hi, I write a parser that can parse the raw string correctly, but can't parse content read from file, to simplify the code, here is an example:

fn crlf() -> Parser<u8, ()> {
    one_of(b"\r\n").repeat(0..).discard()
}
fn main() {
    let input = fs::read("test.txt").unwrap();

    let outputOk = crlf().parse("test".as_bytes());
    let outputErr = crlf().parse(&input);
}

The line with outputErr cause the error: input does not live long enough

J-F-Liu commented 5 years ago

Use use pom::parser::Parser instead of use pom::Parser.

hulufei commented 5 years ago

@J-F-Liu thanks, I changed to use pom::parser::Parser, but I still got the error

use pom::parser::*;
use pom::parser::Parser;

fn crlf() -> Parser<'static, u8, ()> {
    one_of(b"\r\n").repeat(0..).discard()
}
fn main() {
    let input = fs::read("test.txt").unwrap();

    let outputOk = crlf().parse("test".as_bytes());
    let outputErr = crlf().parse(&input);
}
J-F-Liu commented 5 years ago

Should be

fn crlf<'a>() -> Parser<'a, u8, ()> {
    one_of(b"\r\n").repeat(0..).discard()
}
hulufei commented 5 years ago

Thank you, it works

shonfeder commented 4 years ago

Wah, it took me quite a long time to find this. It would be helpful to have a line or two about reading from files, and the need for using parser::Parser to do so, in the docs and tutorials. I had to go puzzling through the benchmarks and digging through issues to figure this out.

@J-F-Liu would it be OK if I make a PR to document this more prominently, or perhaps just open an issue detailing the kind of documentation that would have helped me?

J-F-Liu commented 4 years ago

Yes, PR is welcome.

joshmarinacci commented 4 years ago

I found this issue as well. I just created a PR with a new example and some doc changes to address this.

https://github.com/J-F-Liu/pom/pull/41