From 7ee4769e1ea9e03fc2cdee36254a173c2b8de218 Mon Sep 17 00:00:00 2001 From: Douglas Su Date: Tue, 8 Jun 2021 18:33:33 +0800 Subject: [PATCH] Refactor module parsing function. The logic of parsing a module macro is a little bit cumbersome and error-prone. Refactor this part to make it clear, concise, structural and extensible. Signed-off-by: Douglas Su --- rust/macros/module.rs | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/rust/macros/module.rs b/rust/macros/module.rs index 3db45aed16187d..632abc39ee3be5 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -313,17 +313,17 @@ impl ModuleInfo { fn parse(it: &mut token_stream::IntoIter) -> Self { let mut info = ModuleInfo::default(); - const EXPECTED_KEYS: &[&str] = &[ - "type", - "name", - "author", - "description", - "license", - "alias", - "alias_rtnl_link", - "params", + const ALL_KEYS: &[(bool, &str)] = &[ + //required: bool, key: &str + (true, "type"), + (true, "name"), + (false, "author"), + (false, "description"), + (true, "license"), + (false, "alias"), + (false, "alias_rtnl_link"), + (false, "params"), ]; - const REQUIRED_KEYS: &[&str] = &["type", "name", "license"]; let mut seen_keys = Vec::new(); loop { @@ -354,8 +354,9 @@ impl ModuleInfo { } "params" => info.params = Some(expect_group(it)), _ => panic!( - "Unknown key \"{}\". Valid keys are: {:?}.", - key, EXPECTED_KEYS + "Unknown key \"{}\". Valid keys are: \"{}\".", + key, + ALL_KEYS.iter().map(|e| e.1).collect::>().join(", ") ), } @@ -366,16 +367,15 @@ impl ModuleInfo { expect_end(it); - for key in REQUIRED_KEYS { - if !seen_keys.iter().any(|e| e == key) { - panic!("Missing required key \"{}\".", key); + let mut ordered_keys: Vec<&str> = Vec::new(); + for key in ALL_KEYS { + let has_key = seen_keys.iter().any(|e| e == key.1); + if key.0 && !has_key { + panic!("Missing required key \"{}\".", key.1); } - } - let mut ordered_keys: Vec<&str> = Vec::new(); - for key in EXPECTED_KEYS { - if seen_keys.iter().any(|e| e == key) { - ordered_keys.push(key); + if has_key { + ordered_keys.push(&key.1); } }