Skip to content

Commit 50bd08b

Browse files
committed
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: d0u9 <[email protected]>
1 parent 66893e3 commit 50bd08b

File tree

1 file changed

+23
-19
lines changed

1 file changed

+23
-19
lines changed

rust/macros/module.rs

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -313,17 +313,17 @@ impl ModuleInfo {
313313
fn parse(it: &mut token_stream::IntoIter) -> Self {
314314
let mut info = ModuleInfo::default();
315315

316-
const EXPECTED_KEYS: &[&str] = &[
317-
"type",
318-
"name",
319-
"author",
320-
"description",
321-
"license",
322-
"alias",
323-
"alias_rtnl_link",
324-
"params",
316+
const ALL_KEYS: &[(bool, &str)] = &[
317+
//required: bool, key: &str
318+
(true, "type"),
319+
(true, "name"),
320+
(false, "author"),
321+
(false, "description"),
322+
(true, "license"),
323+
(false, "alias"),
324+
(false, "alias_rtnl_link"),
325+
(false, "params"),
325326
];
326-
const REQUIRED_KEYS: &[&str] = &["type", "name", "license"];
327327
let mut seen_keys = Vec::new();
328328

329329
loop {
@@ -355,7 +355,12 @@ impl ModuleInfo {
355355
"params" => info.params = Some(expect_group(it)),
356356
_ => panic!(
357357
"Unknown key \"{}\". Valid keys are: {:?}.",
358-
key, EXPECTED_KEYS
358+
key,
359+
ALL_KEYS
360+
.iter()
361+
.map(|e| e.1.to_string())
362+
.collect::<Vec<String>>()
363+
.join(", ")
359364
),
360365
}
361366

@@ -366,16 +371,15 @@ impl ModuleInfo {
366371

367372
expect_end(it);
368373

369-
for key in REQUIRED_KEYS {
370-
if !seen_keys.iter().any(|e| e == key) {
371-
panic!("Missing required key \"{}\".", key);
374+
let mut ordered_keys: Vec<&str> = Vec::new();
375+
for key in ALL_KEYS {
376+
let has_key = seen_keys.iter().any(|e| e == key.1);
377+
if key.0 && !has_key {
378+
panic!("Missing required key \"{}\".", key.1);
372379
}
373-
}
374380

375-
let mut ordered_keys: Vec<&str> = Vec::new();
376-
for key in EXPECTED_KEYS {
377-
if seen_keys.iter().any(|e| e == key) {
378-
ordered_keys.push(key);
381+
if has_key {
382+
ordered_keys.push(&key.1);
379383
}
380384
}
381385

0 commit comments

Comments
 (0)