tokmd-analysis 1.10.0

Analysis logic and enrichers for tokmd receipts.
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use anyhow::Result;
use tokmd_analysis_types::HalsteadMetrics;
use tokmd_types::{ExportData, FileKind, FileRow};

use tokmd_analysis_types::{AnalysisLimits, normalize_path};

const DEFAULT_MAX_FILE_BYTES: u64 = 128 * 1024;

/// Languages that support Halstead analysis.
pub(crate) fn is_halstead_lang(lang: &str) -> bool {
    matches!(
        lang.to_lowercase().as_str(),
        "rust"
            | "javascript"
            | "typescript"
            | "python"
            | "go"
            | "c"
            | "c++"
            | "java"
            | "c#"
            | "php"
            | "ruby"
    )
}

#[cfg(test)]
#[path = "tests.rs"]
mod moved_tests;

/// Operators for a given language.
pub(crate) fn operators_for_lang(lang: &str) -> &'static [&'static str] {
    match lang.to_lowercase().as_str() {
        "rust" => &[
            "fn", "let", "mut", "if", "else", "match", "while", "for", "loop", "return", "break",
            "continue", "struct", "enum", "impl", "trait", "pub", "use", "mod", "async", "await",
            "move", "ref", "self", "Self", "where", "type", "const", "static", "unsafe", "extern",
            "crate", "super", "as", "in", "->", "=>", "::", "=", "==", "!=", "<", ">", "<=", ">=",
            "+", "-", "*", "/", "%", "&", "|", "^", "!", "&&", "||", "<<", ">>", "+=", "-=", "*=",
            "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "..", "..=", "?",
        ],
        "javascript" | "typescript" => &[
            "function",
            "var",
            "let",
            "const",
            "if",
            "else",
            "switch",
            "case",
            "while",
            "for",
            "do",
            "return",
            "break",
            "continue",
            "class",
            "new",
            "this",
            "super",
            "import",
            "export",
            "default",
            "try",
            "catch",
            "finally",
            "throw",
            "async",
            "await",
            "yield",
            "typeof",
            "instanceof",
            "in",
            "of",
            "delete",
            "void",
            "=>",
            "=",
            "==",
            "===",
            "!=",
            "!==",
            "<",
            ">",
            "<=",
            ">=",
            "+",
            "-",
            "*",
            "/",
            "%",
            "&",
            "|",
            "^",
            "!",
            "&&",
            "||",
            "~",
            "<<",
            ">>",
            ">>>",
            "+=",
            "-=",
            "*=",
            "/=",
            "%=",
            "&=",
            "|=",
            "^=",
            "<<=",
            ">>=",
            ">>>=",
            "**",
            "**=",
            "?.",
            "??",
            "??=",
            "++",
            "--",
            "...",
        ],
        "python" => &[
            "def", "class", "if", "elif", "else", "while", "for", "return", "break", "continue",
            "import", "from", "as", "try", "except", "finally", "raise", "with", "yield", "lambda",
            "pass", "del", "global", "nonlocal", "assert", "async", "await", "and", "or", "not",
            "is", "in", "=", "==", "!=", "<", ">", "<=", ">=", "+", "-", "*", "/", "//", "%", "**",
            "&", "|", "^", "~", "<<", ">>", "+=", "-=", "*=", "/=", "//=", "%=", "**=", "&=", "|=",
            "^=", "<<=", ">>=", ":=",
        ],
        "go" => &[
            "func",
            "var",
            "const",
            "type",
            "struct",
            "interface",
            "if",
            "else",
            "switch",
            "case",
            "for",
            "range",
            "return",
            "break",
            "continue",
            "goto",
            "defer",
            "go",
            "select",
            "chan",
            "map",
            "package",
            "import",
            "fallthrough",
            ":=",
            "=",
            "==",
            "!=",
            "<",
            ">",
            "<=",
            ">=",
            "+",
            "-",
            "*",
            "/",
            "%",
            "&",
            "|",
            "^",
            "!",
            "&&",
            "||",
            "<<",
            ">>",
            "&^",
            "+=",
            "-=",
            "*=",
            "/=",
            "%=",
            "&=",
            "|=",
            "^=",
            "<<=",
            ">>=",
            "&^=",
            "++",
            "--",
            "<-",
        ],
        "c" | "c++" | "java" | "c#" | "php" => &[
            "if",
            "else",
            "switch",
            "case",
            "while",
            "for",
            "do",
            "return",
            "break",
            "continue",
            "class",
            "struct",
            "new",
            "delete",
            "try",
            "catch",
            "throw",
            "finally",
            "void",
            "static",
            "const",
            "public",
            "private",
            "protected",
            "virtual",
            "override",
            "abstract",
            "interface",
            "extends",
            "implements",
            "import",
            "include",
            "using",
            "namespace",
            "typedef",
            "template",
            "=",
            "==",
            "!=",
            "<",
            ">",
            "<=",
            ">=",
            "+",
            "-",
            "*",
            "/",
            "%",
            "&",
            "|",
            "^",
            "!",
            "&&",
            "||",
            "~",
            "<<",
            ">>",
            "+=",
            "-=",
            "*=",
            "/=",
            "%=",
            "&=",
            "|=",
            "^=",
            "<<=",
            ">>=",
            "++",
            "--",
            "->",
            "::",
            "sizeof",
            "typeof",
        ],
        "ruby" => &[
            "def",
            "class",
            "module",
            "if",
            "elsif",
            "else",
            "unless",
            "while",
            "until",
            "for",
            "do",
            "return",
            "break",
            "next",
            "begin",
            "rescue",
            "ensure",
            "raise",
            "yield",
            "require",
            "include",
            "extend",
            "attr_reader",
            "attr_writer",
            "attr_accessor",
            "self",
            "super",
            "end",
            "and",
            "or",
            "not",
            "=",
            "==",
            "!=",
            "<",
            ">",
            "<=",
            ">=",
            "+",
            "-",
            "*",
            "/",
            "%",
            "&",
            "|",
            "^",
            "!",
            "&&",
            "||",
            "~",
            "<<",
            ">>",
            "+=",
            "-=",
            "*=",
            "/=",
            "%=",
            "&=",
            "|=",
            "^=",
            "<<=",
            ">>=",
            "**",
            "**=",
            "<=>",
            "=~",
            "!~",
            "..",
            "...",
        ],
        _ => &[],
    }
}

/// Per-file Halstead token counts.
pub(crate) struct FileTokenCounts {
    pub operators: BTreeMap<String, usize>,
    pub operands: BTreeSet<String>,
    pub total_operators: usize,
    pub total_operands: usize,
}

/// Tokenize source code into operators and operands for Halstead analysis.
pub(crate) fn tokenize_for_halstead(text: &str, lang: &str) -> FileTokenCounts {
    let ops = operators_for_lang(lang);
    let op_set: BTreeSet<&str> = ops.iter().copied().collect();

    let mut operators: BTreeMap<String, usize> = BTreeMap::new();
    let mut operands: BTreeSet<String> = BTreeSet::new();
    let mut total_operators = 0usize;
    let mut total_operands = 0usize;

    for line in text.lines() {
        let trimmed = line.trim();
        // Skip comments and empty lines
        if trimmed.is_empty()
            || trimmed.starts_with("//")
            || trimmed.starts_with('#')
            || trimmed.starts_with("/*")
            || trimmed.starts_with('*')
        {
            continue;
        }

        // Extract words and symbols
        let mut chars = trimmed.chars().peekable();
        while let Some(&ch) = chars.peek() {
            if ch.is_whitespace() {
                chars.next();
                continue;
            }

            // Try to match multi-char operators (longest first)
            if ch.is_ascii_punctuation() && ch != '_' && ch != '"' && ch != '\'' {
                let remaining: String = chars.clone().take(4).collect();
                let mut matched = false;
                let char_count = remaining.chars().count();
                for len in (1..=char_count.min(4)).rev() {
                    let (byte_idx, _) = remaining
                        .char_indices()
                        .nth(len)
                        .unwrap_or((remaining.len(), '\0'));
                    let candidate = &remaining[..byte_idx];
                    if op_set.contains(candidate) {
                        *operators.entry(candidate.to_string()).or_insert(0) += 1;
                        total_operators += 1;
                        for _ in 0..len {
                            chars.next();
                        }
                        matched = true;
                        break;
                    }
                }
                if !matched {
                    chars.next();
                }
                continue;
            }

            // Identifiers/keywords
            if ch.is_alphanumeric() || ch == '_' {
                let mut word = String::new();
                while let Some(&c) = chars.peek() {
                    if c.is_alphanumeric() || c == '_' {
                        word.push(c);
                        chars.next();
                    } else {
                        break;
                    }
                }
                if op_set.contains(word.as_str()) {
                    *operators.entry(word).or_insert(0) += 1;
                    total_operators += 1;
                } else {
                    operands.insert(word);
                    total_operands += 1;
                }
                continue;
            }

            // String literals - skip
            if ch == '"' || ch == '\'' {
                chars.next();
                let quote = ch;
                while let Some(&c) = chars.peek() {
                    chars.next();
                    if c == '\\' {
                        chars.next(); // skip escaped char
                    } else if c == quote {
                        break;
                    }
                }
                total_operands += 1; // count the string literal as one operand
                operands.insert("<string>".to_string());
                continue;
            }

            chars.next();
        }
    }

    FileTokenCounts {
        operators,
        operands,
        total_operators,
        total_operands,
    }
}

/// Build aggregated Halstead metrics from source files.
pub(crate) fn build_halstead_report(
    root: &Path,
    files: &[PathBuf],
    export: &ExportData,
    limits: &AnalysisLimits,
) -> Result<HalsteadMetrics> {
    let mut row_map: BTreeMap<String, &FileRow> = BTreeMap::new();
    for row in export.rows.iter().filter(|r| r.kind == FileKind::Parent) {
        row_map.insert(normalize_path(&row.path, root), row);
    }

    let mut all_operators: BTreeMap<String, usize> = BTreeMap::new();
    let mut all_operands: BTreeSet<String> = BTreeSet::new();
    let mut total_ops = 0usize;
    let mut total_opds = 0usize;
    let mut total_bytes = 0u64;
    let max_total = limits.max_bytes;
    let per_file_limit = limits.max_file_bytes.unwrap_or(DEFAULT_MAX_FILE_BYTES) as usize;

    for rel in files {
        if max_total.is_some_and(|limit| total_bytes >= limit) {
            break;
        }
        let rel_str = rel.to_string_lossy().replace('\\', "/");
        let row = match row_map.get(&rel_str) {
            Some(r) => *r,
            None => continue,
        };
        if !is_halstead_lang(&row.lang) {
            continue;
        }

        let path = root.join(rel);
        let bytes = match crate::content::io::read_head(&path, per_file_limit) {
            Ok(b) => b,
            Err(_) => continue,
        };
        total_bytes += bytes.len() as u64;

        if !crate::content::io::is_text_like(&bytes) {
            continue;
        }

        let text = String::from_utf8_lossy(&bytes);
        let lang_lower = row.lang.to_lowercase();
        let counts = tokenize_for_halstead(&text, &lang_lower);

        for (op, count) in counts.operators {
            *all_operators.entry(op).or_insert(0) += count;
        }
        all_operands.extend(counts.operands);
        total_ops += counts.total_operators;
        total_opds += counts.total_operands;
    }

    let n1 = all_operators.len(); // distinct operators
    let n2 = all_operands.len(); // distinct operands
    let vocabulary = n1 + n2;
    let length = total_ops + total_opds;

    let volume = if vocabulary > 0 {
        length as f64 * (vocabulary as f64).log2()
    } else {
        0.0
    };

    let difficulty = if n2 > 0 {
        (n1 as f64 / 2.0) * (total_opds as f64 / n2 as f64)
    } else {
        0.0
    };

    let effort = difficulty * volume;
    let time_seconds = effort / 18.0;
    let estimated_bugs = volume / 3000.0;

    Ok(HalsteadMetrics {
        distinct_operators: n1,
        distinct_operands: n2,
        total_operators: total_ops,
        total_operands: total_opds,
        vocabulary,
        length,
        volume: round_f64(volume, 2),
        difficulty: round_f64(difficulty, 2),
        effort: round_f64(effort, 2),
        time_seconds: round_f64(time_seconds, 2),
        estimated_bugs: round_f64(estimated_bugs, 4),
    })
}

/// Round an f64 to a given number of decimal places.
pub(crate) fn round_f64(val: f64, decimals: u32) -> f64 {
    let factor = 10f64.powi(decimals as i32);
    (val * factor).round() / factor
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tokenize_rust() {
        let code = r#"
fn add(a: i32, b: i32) -> i32 {
    if a > b {
        a + b
    } else {
        a - b
    }
}
"#;
        let counts = tokenize_for_halstead(code, "rust");
        assert!(counts.total_operators > 0);
        assert!(counts.total_operands > 0);
        assert!(!counts.operators.is_empty());
        assert!(!counts.operands.is_empty());
    }

    #[test]
    fn test_tokenize_python() {
        let code = r#"
def add(a, b):
    if a > b:
        return a + b
    else:
        return a - b
"#;
        let counts = tokenize_for_halstead(code, "python");
        assert!(counts.total_operators > 0);
        assert!(counts.total_operands > 0);
    }

    #[test]
    fn test_halstead_computation() {
        // Known values: 2 distinct operators, 3 distinct operands
        // n1=2, n2=3, N1=4, N2=6
        // vocabulary = 5, length = 10
        // volume = 10 * log2(5) ≈ 23.22
        // difficulty = (2/2) * (6/3) = 2.0
        // effort = 2.0 * 23.22 ≈ 46.44
        let n1 = 2;
        let n2 = 3;
        let total_ops = 4;
        let total_opds = 6;
        let vocabulary = n1 + n2;
        let length = total_ops + total_opds;
        let volume = length as f64 * (vocabulary as f64).log2();
        let difficulty = (n1 as f64 / 2.0) * (total_opds as f64 / n2 as f64);
        let effort = difficulty * volume;

        assert!((volume - 23.22).abs() < 0.1);
        assert!((difficulty - 2.0).abs() < 0.01);
        assert!((effort - 46.44).abs() < 0.2);
    }

    #[test]
    fn test_empty_input() {
        let counts = tokenize_for_halstead("", "rust");
        assert_eq!(counts.total_operators, 0);
        assert_eq!(counts.total_operands, 0);
    }

    #[test]
    fn tokenize_handles_non_ascii_after_operator() {
        let counts = tokenize_for_halstead(r#"let locale = ("日本", "ja");"#, "rust");
        assert!(counts.total_operators > 0);
    }

    #[test]
    fn test_tokenize_cjk_panic() {
        // Ensure that slicing a multi-byte character does not panic.
        let code = "!你好";
        let counts = tokenize_for_halstead(code, "rust");
        // '!' is a known operator. '你好' should be captured as an operand.
        assert_eq!(counts.total_operators, 1);
        assert!(counts.operators.contains_key("!"));
    }
}