kevinmehall / rust-peg

Parsing Expression Grammar (PEG) parser generator for Rust
https://crates.io/crates/peg
MIT License
1.46k stars 106 forks source link

Allow any attributes on rules #383

Open Mingun opened 1 month ago

Mingun commented 1 month ago

I want to feature gate some rules in grammar, so tried to place #[cfg(feature = "...")] on it, but grammar! does not accept that. It would be nice if I could do that:

peg::parser! {
  /// Contains generated parser for Kaitai Struct expression language.
  grammar parser() for str {
    /// Entry point for parsing enum values (keys of `number: enum_variant_name`).
    // TODO: It is better to use integer() rule to parse that
    // See https://github.com/kaitai-io/kaitai_struct/issues/1132
    #[cfg(feature = "compatible")] //<<<<<<<<<<<<<<<<<<<<<< impossible
    pub rule parse_enum_value() -> BigInt
      = "0x" n:$(hex()+) {? to_int(n, 16) }
      / n:$(['0'..='9' | '_']+) {? to_int(n, 10) }
      ;
    #[cfg(not(feature = "compatible"))] //<<<<<<<<<<<<<<<<<<<<<< impossible
    pub rule parse_enum_value() -> BigInt
      = "-" n:integer() { -n }
      / integer()
      ;
  }
}
kevinmehall commented 5 days ago

cfg could definitely be propagated to the pub and internal functions that implement the rule plus things like the struct field used for #[cache]. For arbitrary attributes, it's not clear where they should be applied in the generated code, and are probably too much of a forwards-compatibility hazard, though.