howmany 3.0.0

A blazingly fast, intelligent code analysis tool with parallel processing, caching, and beautiful visualizations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use super::super::types::{FunctionInfo, StructureInfo, StructureType, Visibility};
use super::LanguageAnalyzer;
use crate::utils::errors::Result;

/// Elixir language complexity analyzer
pub struct ElixirAnalyzer;

impl ElixirAnalyzer {
    pub fn new() -> Self {
        Self
    }

    /// Extract function name from Elixir function definition
    fn extract_function_name(&self, line: &str) -> Option<String> {
        let trimmed = line.trim();

        // Skip comments and empty lines
        if trimmed.starts_with("#") || trimmed.is_empty() {
            return None;
        }

        // Look for "def " or "defp " patterns
        if let Some(start) = trimmed.find("def ").or_else(|| trimmed.find("defp ")) {
            let offset = if trimmed[start..].starts_with("defp ") {
                5
            } else {
                4
            };
            let after_def = &trimmed[start + offset..];

            // Handle function names with parameters
            let func_part = after_def.trim();

            // Find function name (before parentheses, comma, or do)
            let end_pos = func_part
                .find('(')
                .or_else(|| func_part.find(','))
                .or_else(|| func_part.find(" do"))
                .or_else(|| func_part.find(" when"))
                .unwrap_or(func_part.len());

            let func_name = &func_part[..end_pos].trim();

            if !func_name.is_empty()
                && func_name
                    .chars()
                    .all(|c| c.is_alphanumeric() || c == '_' || c == '?' || c == '!')
            {
                return Some(func_name.to_string());
            }
        }

        // Look for anonymous functions
        if trimmed.contains("fn ") {
            // This is an anonymous function, we'll count it but not extract a name
            return Some("anonymous".to_string());
        }

        None
    }

    /// Extract module/struct name from Elixir declaration
    fn extract_structure_name(&self, line: &str) -> Option<String> {
        let trimmed = line.trim();

        // Look for defmodule
        if let Some(start) = trimmed.find("defmodule ") {
            let after_defmodule = &trimmed[start + 10..];
            let parts: Vec<&str> = after_defmodule.split_whitespace().collect();

            if let Some(first_part) = parts.first() {
                // Handle module names with "do" at the end
                let name = if let Some(do_pos) = first_part.find(" do") {
                    &first_part[..do_pos]
                } else {
                    first_part
                };

                if !name.is_empty()
                    && name
                        .chars()
                        .all(|c| c.is_alphanumeric() || c == '_' || c == '.')
                {
                    return Some(name.to_string());
                }
            }
        }

        // Look for defstruct
        if trimmed.contains("defstruct ") {
            // Extract the module name from context (this is typically inside a module)
            return Some("struct".to_string());
        }

        // Look for defprotocol
        if let Some(start) = trimmed.find("defprotocol ") {
            let after_defprotocol = &trimmed[start + 12..];
            let parts: Vec<&str> = after_defprotocol.split_whitespace().collect();

            if let Some(first_part) = parts.first() {
                let name = if let Some(do_pos) = first_part.find(" do") {
                    &first_part[..do_pos]
                } else {
                    first_part
                };

                if !name.is_empty()
                    && name
                        .chars()
                        .all(|c| c.is_alphanumeric() || c == '_' || c == '.')
                {
                    return Some(name.to_string());
                }
            }
        }

        None
    }

    /// Count complexity keywords in Elixir code
    fn count_complexity_keywords(&self, line: &str) -> usize {
        let keywords = [
            "if", "unless", "cond", "case", "when", "for", "while", "until", "&&", "||", "and",
            "or", "not", "try", "rescue", "catch", "after", "receive", "with", "else", "->", "|>",
            "spawn", "send",
        ];
        keywords
            .iter()
            .map(|&keyword| line.matches(keyword).count())
            .sum()
    }

    /// Calculate cyclomatic complexity for a function
    fn calculate_cyclomatic_complexity(
        &self,
        lines: &[String],
        start_line: usize,
        end_line: usize,
    ) -> usize {
        let mut complexity = 1; // Base complexity

        for line in lines.iter().take(end_line + 1).skip(start_line) {
            complexity += self.count_complexity_keywords(line);
        }

        complexity
    }

    /// Find the end of a function definition
    fn find_function_end(&self, lines: &[String], start_line: usize) -> usize {
        let mut depth = 0;
        let mut in_function = false;

        for (i, line) in lines.iter().enumerate().skip(start_line) {
            let trimmed = line.trim();

            if trimmed.contains("def ") || trimmed.contains("defp ") {
                in_function = true;
            }

            if in_function {
                // Count do/end blocks
                if trimmed.contains(" do") || trimmed.ends_with(" do") {
                    depth += 1;
                }
                if trimmed == "end" || trimmed.starts_with("end ") {
                    depth -= 1;
                    if depth == 0 {
                        return i;
                    }
                }

                // Handle single-line functions
                if trimmed.contains(", do:") && depth == 0 {
                    return i;
                }
            }
        }

        lines.len().saturating_sub(1)
    }

    /// Determine visibility of a function
    fn determine_visibility(&self, line: &str) -> Visibility {
        if line.trim().contains("defp ") {
            Visibility::Private
        } else {
            Visibility::Public // Elixir's default, and what `def ` asks for
        }
    }

    /// Determine structure type
    fn determine_structure_type(&self, line: &str) -> StructureType {
        let trimmed = line.trim();

        if trimmed.contains("defmodule ") {
            StructureType::Module
        } else if trimmed.contains("defprotocol ") {
            StructureType::Interface
        } else if trimmed.contains("defstruct ") {
            StructureType::Struct
        } else {
            StructureType::Class // Default
        }
    }
}

impl LanguageAnalyzer for ElixirAnalyzer {
    fn analyze_functions(&self, lines: &[String]) -> Result<Vec<FunctionInfo>> {
        let mut functions = Vec::new();

        for (i, line) in lines.iter().enumerate() {
            if let Some(func_name) = self.extract_function_name(line) {
                let end_line = self.find_function_end(lines, i);
                let complexity = self.calculate_cyclomatic_complexity(lines, i, end_line);
                let _visibility = self.determine_visibility(line);

                functions.push(FunctionInfo {
                    name: func_name,
                    line_count: end_line.saturating_sub(i).max(1),
                    cyclomatic_complexity: complexity,
                    cognitive_complexity: complexity, // Use same value for now
                    nesting_depth: 0,                 // Calculate if needed
                    parameter_count: self.count_parameters(line),
                    return_path_count: 1, // Default value
                    start_line: i + 1,
                    end_line: end_line + 1,
                    is_method: false,
                    parent_class: None,
                    local_variable_count: 0,
                    has_recursion: false,
                    has_exception_handling: false,
                    visibility: Visibility::Public,
                });
            }
        }

        Ok(functions)
    }

    fn analyze_structures(&self, lines: &[String]) -> Result<Vec<StructureInfo>> {
        let mut structures = Vec::new();

        for (i, line) in lines.iter().enumerate() {
            if let Some(struct_name) = self.extract_structure_name(line) {
                let end_line = self.find_structure_end(lines, i);
                let structure_type = self.determine_structure_type(line);
                let _visibility = Visibility::Public; // Elixir modules are typically public

                structures.push(StructureInfo {
                    name: struct_name,
                    structure_type,
                    line_count: end_line.saturating_sub(i).max(1),
                    start_line: i + 1,
                    end_line: end_line + 1,
                    methods: self.collect_methods_in_structure(lines, i, end_line),
                    properties: self.count_fields_in_structure(lines, i, end_line),
                    visibility: Visibility::Public,
                    inheritance_depth: 0,
                    interface_count: 0,
                });
            }
        }

        Ok(structures)
    }
}

impl ElixirAnalyzer {
    /// Count parameters in a function definition
    fn count_parameters(&self, line: &str) -> usize {
        if let Some(start) = line.find('(') {
            if let Some(end) = line.find(')') {
                let params = &line[start + 1..end];
                if params.trim().is_empty() {
                    return 0;
                }
                return params.split(',').count();
            }
        }

        // Handle functions without parentheses
        if line.contains("def ") || line.contains("defp ") {
            let after_def = if let Some(pos) = line.find("def ") {
                &line[pos + 4..]
            } else if let Some(pos) = line.find("defp ") {
                &line[pos + 5..]
            } else {
                return 0;
            };

            // Count arguments separated by commas before "do" or "when"
            let args_part = if let Some(do_pos) = after_def.find(" do") {
                &after_def[..do_pos]
            } else if let Some(when_pos) = after_def.find(" when") {
                &after_def[..when_pos]
            } else {
                after_def
            };

            if args_part.trim().is_empty() {
                return 0;
            }

            return args_part.split(',').count();
        }

        0
    }

    /// Find the end of a structure definition
    fn find_structure_end(&self, lines: &[String], start_line: usize) -> usize {
        let mut depth = 0;
        let mut in_structure = false;

        for (i, line) in lines.iter().enumerate().skip(start_line) {
            let trimmed = line.trim();

            if trimmed.contains("defmodule ") || trimmed.contains("defprotocol ") {
                in_structure = true;
            }

            if in_structure {
                if trimmed.contains(" do") || trimmed.ends_with(" do") {
                    depth += 1;
                }
                if trimmed == "end" || trimmed.starts_with("end ") {
                    depth -= 1;
                    if depth == 0 {
                        return i;
                    }
                }
            }
        }

        lines.len().saturating_sub(1)
    }

    /// Collect methods within a structure
    fn collect_methods_in_structure(
        &self,
        lines: &[String],
        start_line: usize,
        end_line: usize,
    ) -> Vec<FunctionInfo> {
        let mut methods = Vec::new();

        for i in start_line..=end_line.min(lines.len().saturating_sub(1)) {
            if let Some(func_name) = self.extract_function_name(&lines[i]) {
                let func_end_line = self.find_function_end(lines, i);
                let complexity = self.calculate_cyclomatic_complexity(lines, i, func_end_line);

                methods.push(FunctionInfo {
                    name: func_name,
                    line_count: func_end_line.saturating_sub(i).max(1),
                    cyclomatic_complexity: complexity,
                    cognitive_complexity: complexity,
                    nesting_depth: 0,
                    parameter_count: self.count_parameters(&lines[i]),
                    return_path_count: 1,
                    start_line: i + 1,
                    end_line: func_end_line + 1,
                    is_method: true,
                    parent_class: None,
                    local_variable_count: 0,
                    has_recursion: false,
                    has_exception_handling: false,
                    visibility: Visibility::Public,
                });
            }
        }

        methods
    }

    /// Count fields within a structure
    fn count_fields_in_structure(
        &self,
        lines: &[String],
        start_line: usize,
        end_line: usize,
    ) -> usize {
        let mut count = 0;

        for line in lines.iter().take(end_line + 1).skip(start_line) {
            // Count defstruct fields
            if line.trim().contains("defstruct ") {
                if let Some(start) = line.find("[") {
                    if let Some(end) = line.find("]") {
                        let fields = &line[start + 1..end];
                        count += fields.split(',').count();
                    }
                }
            }

            // Count @spec and @type definitions
            if line.trim().starts_with("@") {
                count += 1;
            }
        }

        count
    }
}

impl Default for ElixirAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}