rustloclib 0.17.2-rc.2

Rust-aware LOC counter that separates production code from tests — even in the same file
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
//! Core data structures for LOC statistics.
//!
//! This module provides the fundamental types for representing line counts
//! in Rust source files. The design uses a single flat structure with 6 line types:
//!
//! - **code**: Logic lines in production code (src/, not in tests)
//! - **tests**: Logic lines in test code (#[test], #[cfg(test)], tests/)
//! - **examples**: Logic lines in example code (examples/)
//! - **docs**: Documentation comments (///, //!, /** */, /*! */) - anywhere
//! - **comments**: Regular comments (//, /* */) - anywhere
//! - **blanks**: Blank/whitespace-only lines - anywhere
//!
//! The key insight: only actual code lines need context (code/tests/examples),
//! because that's the meaningful distinction. A blank is a blank, a comment is
//! a comment - where they appear doesn't matter for most analysis.

use crate::query::options::LineTypes;
use serde::{Deserialize, Serialize};
use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::path::PathBuf;

/// Lines of code counts with 7 line types.
///
/// This is the fundamental unit of measurement in rustloc. Each field counts
/// a specific type of line:
///
/// - `code`, `tests`, `examples`: Actual executable/logic lines, distinguished by context
/// - `docs`, `comments`, `blanks`: Metadata lines, counted regardless of location
/// - `total`: Precomputed sum of all line types (total line count)
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Locs {
    /// Logic lines in production code (src/, not in test blocks)
    pub code: u64,
    /// Logic lines in test code (#[test], #[cfg(test)], tests/ directory)
    pub tests: u64,
    /// Logic lines in example code (examples/ directory)
    pub examples: u64,
    /// Documentation comment lines (///, //!, /** */, /*! */)
    pub docs: u64,
    /// Regular comment lines (//, /* */)
    pub comments: u64,
    /// Blank lines (whitespace only)
    pub blanks: u64,
    /// Total line count (sum of all types)
    pub total: u64,
}

impl Locs {
    /// Create a new Locs with all zeros.
    pub fn new() -> Self {
        Self::default()
    }

    /// Total lines (returns precomputed `total` field).
    pub fn total(&self) -> u64 {
        self.total
    }

    /// Total logic lines (code + tests + examples).
    pub fn total_logic(&self) -> u64 {
        self.code + self.tests + self.examples
    }

    /// Recompute the `total` field from individual line types.
    /// Call this after manually setting individual fields.
    pub fn recompute_total(&mut self) {
        self.total =
            self.code + self.tests + self.examples + self.docs + self.comments + self.blanks;
    }

    /// Return a filtered copy with only the specified line types included.
    /// Unselected types are zeroed out. The `total` field is always preserved.
    pub fn filter(&self, types: LineTypes) -> Self {
        Self {
            code: if types.code { self.code } else { 0 },
            tests: if types.tests { self.tests } else { 0 },
            examples: if types.examples { self.examples } else { 0 },
            docs: if types.docs { self.docs } else { 0 },
            comments: if types.comments { self.comments } else { 0 },
            blanks: if types.blanks { self.blanks } else { 0 },
            total: self.total, // Always preserved
        }
    }
}

impl Add for Locs {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            code: self.code + other.code,
            tests: self.tests + other.tests,
            examples: self.examples + other.examples,
            docs: self.docs + other.docs,
            comments: self.comments + other.comments,
            blanks: self.blanks + other.blanks,
            total: self.total + other.total,
        }
    }
}

impl AddAssign for Locs {
    fn add_assign(&mut self, other: Self) {
        self.code += other.code;
        self.tests += other.tests;
        self.examples += other.examples;
        self.docs += other.docs;
        self.comments += other.comments;
        self.blanks += other.blanks;
        self.total += other.total;
    }
}

impl Sub for Locs {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self {
            code: self.code.saturating_sub(other.code),
            tests: self.tests.saturating_sub(other.tests),
            examples: self.examples.saturating_sub(other.examples),
            docs: self.docs.saturating_sub(other.docs),
            comments: self.comments.saturating_sub(other.comments),
            blanks: self.blanks.saturating_sub(other.blanks),
            total: self.total.saturating_sub(other.total),
        }
    }
}

impl SubAssign for Locs {
    fn sub_assign(&mut self, other: Self) {
        self.code = self.code.saturating_sub(other.code);
        self.tests = self.tests.saturating_sub(other.tests);
        self.examples = self.examples.saturating_sub(other.examples);
        self.docs = self.docs.saturating_sub(other.docs);
        self.comments = self.comments.saturating_sub(other.comments);
        self.blanks = self.blanks.saturating_sub(other.blanks);
        self.total = self.total.saturating_sub(other.total);
    }
}

/// Statistics for a single file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileStats {
    /// Path to the file.
    pub path: PathBuf,
    /// LOC statistics for this file.
    pub stats: Locs,
}

impl FileStats {
    /// Create new file stats.
    pub fn new(path: PathBuf, stats: Locs) -> Self {
        Self { path, stats }
    }

    /// Return a filtered copy with only the specified line types included.
    pub fn filter(&self, types: LineTypes) -> Self {
        Self {
            path: self.path.clone(),
            stats: self.stats.filter(types),
        }
    }
}

/// Statistics for a Rust module.
///
/// A module aggregates files at the directory level. In Rust's module syntax:
/// - `foo/` directory and its sibling `foo.rs` file together form module "foo"
/// - `foo/bar.rs` is submodule "foo::bar"
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModuleStats {
    /// Module path (e.g., "foo", "foo::bar", or "" for root).
    pub name: String,
    /// Aggregated LOC statistics.
    pub stats: Locs,
    /// Files belonging to this module.
    pub files: Vec<PathBuf>,
}

impl ModuleStats {
    /// Create new module stats.
    pub fn new(name: String) -> Self {
        Self {
            name,
            stats: Locs::new(),
            files: Vec::new(),
        }
    }

    /// Add stats from a file to this module.
    pub fn add_file(&mut self, path: PathBuf, stats: Locs) {
        self.stats += stats;
        self.files.push(path);
    }

    /// Return a filtered copy with only the specified line types included.
    pub fn filter(&self, types: LineTypes) -> Self {
        Self {
            name: self.name.clone(),
            stats: self.stats.filter(types),
            files: self.files.clone(),
        }
    }
}

/// Statistics for a crate within a workspace.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CrateStats {
    /// Name of the crate.
    pub name: String,
    /// Root path of the crate.
    pub path: PathBuf,
    /// Aggregated LOC statistics.
    pub stats: Locs,
    /// Per-file statistics (for detailed output).
    pub files: Vec<FileStats>,
}

impl CrateStats {
    /// Create new crate stats.
    pub fn new(name: String, path: PathBuf) -> Self {
        Self {
            name,
            path,
            stats: Locs::new(),
            files: Vec::new(),
        }
    }

    /// Add file stats to this crate.
    pub fn add_file(&mut self, file_stats: FileStats) {
        self.stats += file_stats.stats;
        self.files.push(file_stats);
    }

    /// Return a filtered copy with only the specified line types included.
    pub fn filter(&self, types: LineTypes) -> Self {
        Self {
            name: self.name.clone(),
            path: self.path.clone(),
            stats: self.stats.filter(types),
            files: self.files.iter().map(|f| f.filter(types)).collect(),
        }
    }
}

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

    #[test]
    fn test_locs_default() {
        let locs = Locs::new();
        assert_eq!(locs.code, 0);
        assert_eq!(locs.tests, 0);
        assert_eq!(locs.examples, 0);
        assert_eq!(locs.docs, 0);
        assert_eq!(locs.comments, 0);
        assert_eq!(locs.blanks, 0);
        assert_eq!(locs.total, 0);
        assert_eq!(locs.total(), 0);
    }

    #[test]
    fn test_locs_total() {
        let locs = Locs {
            code: 100,
            tests: 50,
            examples: 20,
            docs: 30,
            comments: 10,
            blanks: 15,
            total: 225,
        };
        assert_eq!(locs.total(), 225);
        assert_eq!(locs.total_logic(), 170);
    }

    #[test]
    fn test_locs_add() {
        let a = Locs {
            code: 100,
            tests: 50,
            examples: 20,
            docs: 30,
            comments: 10,
            blanks: 15,
            total: 225,
        };
        let b = Locs {
            code: 50,
            tests: 25,
            examples: 10,
            docs: 15,
            comments: 5,
            blanks: 10,
            total: 115,
        };
        let sum = a + b;
        assert_eq!(sum.code, 150);
        assert_eq!(sum.tests, 75);
        assert_eq!(sum.examples, 30);
        assert_eq!(sum.docs, 45);
        assert_eq!(sum.comments, 15);
        assert_eq!(sum.blanks, 25);
        assert_eq!(sum.total, 340);
    }

    #[test]
    fn test_locs_filter() {
        let locs = Locs {
            code: 100,
            tests: 50,
            examples: 20,
            docs: 30,
            comments: 10,
            blanks: 15,
            total: 225,
        };

        // Filter to only code - total is preserved
        let code_only = locs.filter(LineTypes::new().with_code());
        assert_eq!(code_only.code, 100);
        assert_eq!(code_only.tests, 0);
        assert_eq!(code_only.examples, 0);
        assert_eq!(code_only.docs, 0);
        assert_eq!(code_only.comments, 0);
        assert_eq!(code_only.blanks, 0);
        assert_eq!(code_only.total, 225); // Preserved

        // Filter to code + tests
        let code_tests = locs.filter(LineTypes::new().with_code().with_tests());
        assert_eq!(code_tests.code, 100);
        assert_eq!(code_tests.tests, 50);
        assert_eq!(code_tests.examples, 0);
        assert_eq!(code_tests.total, 225); // Preserved
    }

    #[test]
    fn test_recompute_total() {
        let mut locs = Locs {
            code: 100,
            tests: 50,
            examples: 20,
            docs: 30,
            comments: 10,
            blanks: 15,
            total: 0, // Intentionally wrong
        };
        locs.recompute_total();
        assert_eq!(locs.total, 225);
    }

    #[test]
    fn test_locs_add_assign() {
        let mut a = Locs {
            code: 10,
            tests: 5,
            examples: 2,
            docs: 3,
            comments: 1,
            blanks: 4,
            total: 25,
        };
        a += Locs {
            code: 1,
            tests: 2,
            examples: 3,
            docs: 4,
            comments: 5,
            blanks: 6,
            total: 21,
        };
        assert_eq!(a.code, 11);
        assert_eq!(a.tests, 7);
        assert_eq!(a.examples, 5);
        assert_eq!(a.docs, 7);
        assert_eq!(a.comments, 6);
        assert_eq!(a.blanks, 10);
        assert_eq!(a.total, 46);
    }

    #[test]
    fn test_locs_sub_basic() {
        let a = Locs {
            code: 100,
            tests: 50,
            examples: 20,
            docs: 30,
            comments: 10,
            blanks: 15,
            total: 225,
        };
        let b = Locs {
            code: 40,
            tests: 10,
            examples: 5,
            docs: 10,
            comments: 4,
            blanks: 5,
            total: 74,
        };
        let diff = a - b;
        assert_eq!(diff.code, 60);
        assert_eq!(diff.tests, 40);
        assert_eq!(diff.examples, 15);
        assert_eq!(diff.docs, 20);
        assert_eq!(diff.comments, 6);
        assert_eq!(diff.blanks, 10);
        assert_eq!(diff.total, 151);
    }

    #[test]
    fn test_locs_sub_saturates_at_zero_no_panic() {
        // Subtraction must saturate, never underflow-panic: this invariant is what
        // lets diff computation subtract a larger "before" from a smaller "after"
        // per-field without crashing (fields move independently of the total).
        let small = Locs {
            code: 1,
            tests: 1,
            examples: 1,
            docs: 1,
            comments: 1,
            blanks: 1,
            total: 6,
        };
        let large = Locs {
            code: 100,
            tests: 100,
            examples: 100,
            docs: 100,
            comments: 100,
            blanks: 100,
            total: 600,
        };
        let diff = small - large;
        assert_eq!(diff, Locs::new()); // every field clamped to 0, including total
    }

    #[test]
    fn test_locs_sub_assign_saturates_at_zero() {
        let mut a = Locs {
            code: 5,
            tests: 0,
            examples: 3,
            docs: 0,
            comments: 2,
            blanks: 0,
            total: 10,
        };
        a -= Locs {
            code: 10, // larger than a.code -> clamps to 0
            tests: 0,
            examples: 1,
            docs: 7, // larger than a.docs -> clamps to 0
            comments: 2,
            blanks: 0,
            total: 20, // larger than a.total -> clamps to 0
        };
        assert_eq!(a.code, 0);
        assert_eq!(a.tests, 0);
        assert_eq!(a.examples, 2);
        assert_eq!(a.docs, 0);
        assert_eq!(a.comments, 0);
        assert_eq!(a.blanks, 0);
        assert_eq!(a.total, 0);
    }

    #[test]
    fn test_locs_filter_empty_zeros_all_but_total() {
        // `LineTypes::new()` selects no component types (code/tests/.../blanks all
        // off; its `total` flag is on by default but is irrelevant here, since
        // `Locs::filter` preserves `total` unconditionally). So filtering by it
        // zeros every component while still reporting the file's true size.
        let locs = Locs {
            code: 7,
            tests: 8,
            examples: 9,
            docs: 1,
            comments: 2,
            blanks: 3,
            total: 30,
        };
        let filtered = locs.filter(LineTypes::new());
        assert_eq!(filtered.code, 0);
        assert_eq!(filtered.tests, 0);
        assert_eq!(filtered.examples, 0);
        assert_eq!(filtered.docs, 0);
        assert_eq!(filtered.comments, 0);
        assert_eq!(filtered.blanks, 0);
        assert_eq!(filtered.total, 30); // preserved even with nothing selected
    }

    #[test]
    fn test_file_stats_filter_preserves_path_and_total() {
        let locs = Locs {
            code: 10,
            tests: 5,
            examples: 0,
            docs: 2,
            comments: 1,
            blanks: 3,
            total: 21,
        };
        let fs = FileStats::new(PathBuf::from("src/lib.rs"), locs);
        let filtered = fs.filter(LineTypes::new().with_tests());
        assert_eq!(filtered.path, PathBuf::from("src/lib.rs"));
        assert_eq!(filtered.stats.tests, 5);
        assert_eq!(filtered.stats.code, 0);
        assert_eq!(filtered.stats.total, 21); // total preserved through filter
    }

    #[test]
    fn test_module_stats_add_file_aggregates_and_tracks_files() {
        let mut module = ModuleStats::new("foo".to_string());
        assert_eq!(module.stats, Locs::new());
        assert!(module.files.is_empty());

        let a = Locs {
            code: 10,
            tests: 0,
            examples: 0,
            docs: 0,
            comments: 0,
            blanks: 2,
            total: 12,
        };
        let b = Locs {
            code: 5,
            tests: 4,
            examples: 0,
            docs: 1,
            comments: 0,
            blanks: 0,
            total: 10,
        };
        module.add_file(PathBuf::from("foo/a.rs"), a);
        module.add_file(PathBuf::from("foo/b.rs"), b);

        // Aggregated stats are the per-field sum.
        assert_eq!(module.stats.code, 15);
        assert_eq!(module.stats.tests, 4);
        assert_eq!(module.stats.blanks, 2);
        assert_eq!(module.stats.docs, 1);
        assert_eq!(module.stats.total, 22);
        // Both contributing files are tracked in order.
        assert_eq!(
            module.files,
            vec![PathBuf::from("foo/a.rs"), PathBuf::from("foo/b.rs")]
        );
    }

    #[test]
    fn test_crate_stats_add_file_aggregates_and_keeps_filestats() {
        let mut krate = CrateStats::new("mylib".to_string(), PathBuf::from("/work/mylib"));
        let f1 = FileStats::new(
            PathBuf::from("/work/mylib/src/lib.rs"),
            Locs {
                code: 20,
                tests: 0,
                examples: 0,
                docs: 5,
                comments: 0,
                blanks: 0,
                total: 25,
            },
        );
        let f2 = FileStats::new(
            PathBuf::from("/work/mylib/tests/it.rs"),
            Locs {
                code: 0,
                tests: 30,
                examples: 0,
                docs: 0,
                comments: 0,
                blanks: 0,
                total: 30,
            },
        );
        krate.add_file(f1);
        krate.add_file(f2);

        assert_eq!(krate.stats.code, 20);
        assert_eq!(krate.stats.tests, 30);
        assert_eq!(krate.stats.docs, 5);
        assert_eq!(krate.stats.total, 55);
        // The full FileStats records are retained for detailed output.
        assert_eq!(krate.files.len(), 2);
        assert_eq!(krate.files[1].stats.tests, 30);
    }

    #[test]
    fn test_crate_stats_filter_applies_to_aggregate_and_each_file() {
        // CrateStats::filter must filter both the rolled-up aggregate AND every
        // nested FileStats, while preserving each total — otherwise detailed and
        // summary views disagree.
        let mut krate = CrateStats::new("mylib".to_string(), PathBuf::from("/work/mylib"));
        krate.add_file(FileStats::new(
            PathBuf::from("/work/mylib/src/lib.rs"),
            Locs {
                code: 20,
                tests: 7,
                examples: 0,
                docs: 5,
                comments: 0,
                blanks: 0,
                total: 32,
            },
        ));
        let filtered = krate.filter(LineTypes::new().with_code());

        // Aggregate: only code survives, total preserved.
        assert_eq!(filtered.stats.code, 20);
        assert_eq!(filtered.stats.tests, 0);
        assert_eq!(filtered.stats.total, 32);
        // Nested file: same filtering, total preserved, path + crate metadata intact.
        assert_eq!(filtered.files[0].stats.code, 20);
        assert_eq!(filtered.files[0].stats.tests, 0);
        assert_eq!(filtered.files[0].stats.total, 32);
        assert_eq!(filtered.name, "mylib");
        assert_eq!(filtered.path, PathBuf::from("/work/mylib"));
    }
}