diff options
author | Nadrieril | 2019-04-15 18:03:06 +0200 |
---|---|---|
committer | Nadrieril | 2019-04-15 18:03:06 +0200 |
commit | 607b7535b369a3de91d87d4f6f8ec55a6c0d731f (patch) | |
tree | 7407c0ee6375f2eedfc8d4e0cff35ec19b7e8142 /abnf_to_pest/src/lib.rs | |
parent | 63aa21c581933a10b2b1ab96c632c72834cf2115 (diff) | |
parent | 2e6a2955e45e33aed285224eec291500375e5eb5 (diff) |
Merge branch 'publish-abnf-to-pest'
Diffstat (limited to 'abnf_to_pest/src/lib.rs')
-rw-r--r-- | abnf_to_pest/src/lib.rs | 35 |
1 files changed, 29 insertions, 6 deletions
diff --git a/abnf_to_pest/src/lib.rs b/abnf_to_pest/src/lib.rs index 1b8fc9c..625798b 100644 --- a/abnf_to_pest/src/lib.rs +++ b/abnf_to_pest/src/lib.rs @@ -1,6 +1,25 @@ -#![allow(clippy::implicit_hasher, clippy::or_fun_call)] +#![doc(html_root_url = "https://docs.rs/abnf_to_pest/0.1.1")] //! A tiny crate that helps convert ABNF grammars to [pest][pest]. +//! +//! Example usage: +//! ``` +//! let abnf_path = "src/grammar.abnf"; +//! let pest_path = "src/grammar.pest"; +//! +//! let mut file = File::open(abnf_path)?; +//! let mut data = Vec::new(); +//! file.read_to_end(&mut data)?; +//! data.push('\n' as u8); +//! +//! let mut rules = abnf_to_pest::parse_abnf(&data)?; +//! rules.remove("some_inconvenient_rule"); +//! +//! let mut file = File::create(pest_path)?; +//! writeln!(&mut file, "{}", render_rules_to_pest(rules).pretty(80))?; +//! ``` +//! +//! [pest]: https://pest.rs use abnf::abnf::Rule; pub use abnf::abnf::{ @@ -8,7 +27,7 @@ pub use abnf::abnf::{ }; use itertools::Itertools; use pretty::{BoxDoc, Doc}; -use std::collections::HashMap; +use indexmap::map::IndexMap; trait Pretty { fn pretty(&self) -> Doc<'static, BoxDoc<'static, ()>>; @@ -40,7 +59,7 @@ impl Pretty for Repetition { self.repeat .as_ref() .map(Repeat::pretty) - .unwrap_or(Doc::nil()), + .unwrap_or_else(Doc::nil), ) } } @@ -93,6 +112,10 @@ impl Pretty for Range { } } +/// Escape the rule name to be a valid Rust identifier. +/// +/// Replaces e.g. `if` with `if_`, and `rule-name` with `rule_name`. +/// Also changes `whitespace` to `whitespace_` because of https://github.com/pest-parser/pest/pull/374 pub fn escape_rulename(x: &str) -> String { let x = x.replace("-", "_"); if x == "if" @@ -110,8 +133,8 @@ pub fn escape_rulename(x: &str) -> String { } } -fn format_char(x: usize) -> String { - if x <= usize::from(u8::max_value()) { +fn format_char(x: u32) -> String { + if x <= u32::from(u8::max_value()) { let x: u8 = x as u8; if x.is_ascii_graphic() { let x: char = x as char; @@ -146,7 +169,7 @@ impl Pretty for (String, PestyRule) { /// Parse an abnf file. Returns a map of rules. pub fn parse_abnf( data: &[u8], -) -> Result<HashMap<String, PestyRule>, std::io::Error> { +) -> Result<IndexMap<String, PestyRule>, std::io::Error> { let make_err = |e| std::io::Error::new(std::io::ErrorKind::Other, format!("{}", e)); let rules: Vec<Rule> = |