rust-bakery / nom

Rust parser combinator framework
MIT License
9.38k stars 804 forks source link

fold's param init func should be FnOnce instead of FnMut #1742

Closed sify21 closed 4 months ago

sify21 commented 5 months ago

Take this for example https://github.com/rust-bakery/nom/blob/90af84b2345c394e86f3d4e5b92466a73c2c4961/tests/arithmetic.rs#L60

You can't move the captured variable init out of the "init" func if it is a non-Copy type, even though init variable has been moved into the capturing "init" func. That's because FnMut means "init" can be called multiple times. This only works as a matter of fact that init variable is i64 in this case.

Since this func is called only once, FnOnce is more suitable here.

Geal commented 4 months ago

with the way the Parser trait is designed, it cannot be a FnOnce, because there's no guarantee that the parser would be called only once: you can take the result of fold and call parse on it with various inputs

sify21 commented 4 months ago

Got it! A Parser is reusable

TennyZhuang commented 4 months ago

Mirroring my reply here, how about make Init: Parser<Input, Result, Error>?

https://github.com/winnow-rs/winnow/issues/513#issuecomment-2124507540