hemtt_preprocessor/
defines.rs

1use std::collections::HashMap;
2
3use hemtt_tokens::Token;
4use strsim::levenshtein;
5
6use crate::Definition;
7
8/// `HashMap` of all current defines
9pub type Defines = HashMap<String, (Token, Definition)>;
10
11/// Helper functions for Defines
12pub trait DefinitionLibrary {
13    /// Find similar functions with a certain number of args
14    ///
15    /// Args can be Some(1) to only find macros that take 1 argument
16    /// or None to check any number of arguments
17    fn similar_function(&self, search: &str, args: Option<usize>) -> Vec<&str>;
18}
19
20impl DefinitionLibrary for Defines {
21    fn similar_function(&self, search: &str, args: Option<usize>) -> Vec<&str> {
22        let mut similar = self
23            .iter()
24            .filter(|(_, (_, def))| {
25                let Definition::Function(func) = def else {
26                    return false;
27                };
28                args.map_or(true, |args| func.parameters().len() == args)
29            })
30            .map(|(name, _)| (name.as_str(), levenshtein(name, search)))
31            .collect::<Vec<_>>();
32        similar.sort_by_key(|(_, v)| *v);
33        similar.retain(|s| s.1 <= 3);
34        if similar.len() > 3 {
35            similar.truncate(3);
36        }
37        similar.into_iter().map(|(n, _)| n).collect::<Vec<_>>()
38    }
39}