fallow-config 2.36.0

Configuration types for the fallow TypeScript/JavaScript codebase analyzer
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
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

const fn default_true() -> bool {
    true
}

const fn default_min_tokens() -> usize {
    50
}

const fn default_min_lines() -> usize {
    5
}

/// Configuration for code duplication detection.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct DuplicatesConfig {
    /// Whether duplication detection is enabled.
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Detection mode: strict, mild, weak, or semantic.
    #[serde(default)]
    pub mode: DetectionMode,

    /// Minimum number of tokens for a clone.
    #[serde(default = "default_min_tokens")]
    pub min_tokens: usize,

    /// Minimum number of lines for a clone.
    #[serde(default = "default_min_lines")]
    pub min_lines: usize,

    /// Maximum allowed duplication percentage (0 = no limit).
    #[serde(default)]
    pub threshold: f64,

    /// Additional ignore patterns for duplication analysis.
    #[serde(default)]
    pub ignore: Vec<String>,

    /// Only report cross-directory duplicates.
    #[serde(default)]
    pub skip_local: bool,

    /// Enable cross-language clone detection by stripping type annotations.
    ///
    /// When enabled, TypeScript type annotations (parameter types, return types,
    /// generics, interfaces, type aliases) are stripped from the token stream,
    /// allowing detection of clones between `.ts` and `.js` files.
    #[serde(default)]
    pub cross_language: bool,

    /// Exclude ES `import` declarations from clone detection.
    ///
    /// When enabled, all `import` statements (value imports, type imports, and
    /// side-effect imports) are stripped from the token stream before clone
    /// detection. This reduces noise from sorted import blocks that naturally
    /// look similar across files. Only affects ES `import` declarations;
    /// CommonJS `require()` calls are not filtered.
    #[serde(default)]
    pub ignore_imports: bool,

    /// Fine-grained normalization overrides on top of the detection mode.
    #[serde(default)]
    pub normalization: NormalizationConfig,
}

impl Default for DuplicatesConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            mode: DetectionMode::default(),
            min_tokens: default_min_tokens(),
            min_lines: default_min_lines(),
            threshold: 0.0,
            ignore: vec![],
            skip_local: false,
            cross_language: false,
            ignore_imports: false,
            normalization: NormalizationConfig::default(),
        }
    }
}

/// Fine-grained normalization overrides.
///
/// Each option, when set to `Some(true)`, forces that normalization regardless of
/// the detection mode. When set to `Some(false)`, it forces preservation. When
/// `None`, the detection mode's default behavior applies.
#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct NormalizationConfig {
    /// Blind all identifiers (variable names, function names, etc.) to the same hash.
    /// Default in `semantic` mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ignore_identifiers: Option<bool>,

    /// Blind string literal values to the same hash.
    /// Default in `weak` and `semantic` modes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ignore_string_values: Option<bool>,

    /// Blind numeric literal values to the same hash.
    /// Default in `semantic` mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ignore_numeric_values: Option<bool>,
}

/// Resolved normalization flags: mode defaults merged with user overrides.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedNormalization {
    pub ignore_identifiers: bool,
    pub ignore_string_values: bool,
    pub ignore_numeric_values: bool,
}

impl ResolvedNormalization {
    /// Resolve normalization from a detection mode and optional overrides.
    #[must_use]
    pub fn resolve(mode: DetectionMode, overrides: &NormalizationConfig) -> Self {
        let (default_ids, default_strings, default_numbers) = match mode {
            DetectionMode::Strict | DetectionMode::Mild => (false, false, false),
            DetectionMode::Weak => (false, true, false),
            DetectionMode::Semantic => (true, true, true),
        };

        Self {
            ignore_identifiers: overrides.ignore_identifiers.unwrap_or(default_ids),
            ignore_string_values: overrides.ignore_string_values.unwrap_or(default_strings),
            ignore_numeric_values: overrides.ignore_numeric_values.unwrap_or(default_numbers),
        }
    }
}

/// Detection mode controlling how aggressively tokens are normalized.
///
/// Since fallow uses AST-based tokenization (not lexer-based), whitespace and
/// comments are inherently absent from the token stream. The `Strict` and `Mild`
/// modes are currently equivalent. `Weak` mode additionally blinds string
/// literals. `Semantic` mode blinds all identifiers and literal values for
/// Type-2 (renamed variable) clone detection.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum DetectionMode {
    /// All tokens preserved including identifier names and literal values (Type-1 only).
    Strict,
    /// Default mode -- equivalent to strict for AST-based tokenization.
    #[default]
    Mild,
    /// Blind string literal values (structure-preserving).
    Weak,
    /// Blind all identifiers and literal values for structural (Type-2) detection.
    Semantic,
}

impl std::fmt::Display for DetectionMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Strict => write!(f, "strict"),
            Self::Mild => write!(f, "mild"),
            Self::Weak => write!(f, "weak"),
            Self::Semantic => write!(f, "semantic"),
        }
    }
}

impl std::str::FromStr for DetectionMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "strict" => Ok(Self::Strict),
            "mild" => Ok(Self::Mild),
            "weak" => Ok(Self::Weak),
            "semantic" => Ok(Self::Semantic),
            other => Err(format!("unknown detection mode: '{other}'")),
        }
    }
}

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

    // ── DuplicatesConfig defaults ────────────────────────────────────

    #[test]
    fn duplicates_config_defaults() {
        let config = DuplicatesConfig::default();
        assert!(config.enabled);
        assert_eq!(config.mode, DetectionMode::Mild);
        assert_eq!(config.min_tokens, 50);
        assert_eq!(config.min_lines, 5);
        assert!((config.threshold - 0.0).abs() < f64::EPSILON);
        assert!(config.ignore.is_empty());
        assert!(!config.skip_local);
        assert!(!config.cross_language);
        assert!(!config.ignore_imports);
    }

    // ── DetectionMode FromStr ────────────────────────────────────────

    #[test]
    fn detection_mode_from_str_all_variants() {
        assert_eq!(
            "strict".parse::<DetectionMode>().unwrap(),
            DetectionMode::Strict
        );
        assert_eq!(
            "mild".parse::<DetectionMode>().unwrap(),
            DetectionMode::Mild
        );
        assert_eq!(
            "weak".parse::<DetectionMode>().unwrap(),
            DetectionMode::Weak
        );
        assert_eq!(
            "semantic".parse::<DetectionMode>().unwrap(),
            DetectionMode::Semantic
        );
    }

    #[test]
    fn detection_mode_from_str_case_insensitive() {
        assert_eq!(
            "STRICT".parse::<DetectionMode>().unwrap(),
            DetectionMode::Strict
        );
        assert_eq!(
            "Weak".parse::<DetectionMode>().unwrap(),
            DetectionMode::Weak
        );
        assert_eq!(
            "SEMANTIC".parse::<DetectionMode>().unwrap(),
            DetectionMode::Semantic
        );
    }

    #[test]
    fn detection_mode_from_str_unknown() {
        let err = "foobar".parse::<DetectionMode>().unwrap_err();
        assert!(err.contains("unknown detection mode"));
        assert!(err.contains("foobar"));
    }

    // ── DetectionMode Display ────────────────────────────────────────

    #[test]
    fn detection_mode_display() {
        assert_eq!(DetectionMode::Strict.to_string(), "strict");
        assert_eq!(DetectionMode::Mild.to_string(), "mild");
        assert_eq!(DetectionMode::Weak.to_string(), "weak");
        assert_eq!(DetectionMode::Semantic.to_string(), "semantic");
    }

    // ── ResolvedNormalization::resolve ────────────────────────────────

    #[test]
    fn resolve_strict_mode_all_false() {
        let resolved =
            ResolvedNormalization::resolve(DetectionMode::Strict, &NormalizationConfig::default());
        assert!(!resolved.ignore_identifiers);
        assert!(!resolved.ignore_string_values);
        assert!(!resolved.ignore_numeric_values);
    }

    #[test]
    fn resolve_mild_mode_all_false() {
        let resolved =
            ResolvedNormalization::resolve(DetectionMode::Mild, &NormalizationConfig::default());
        assert!(!resolved.ignore_identifiers);
        assert!(!resolved.ignore_string_values);
        assert!(!resolved.ignore_numeric_values);
    }

    #[test]
    fn resolve_weak_mode_only_strings_true() {
        let resolved =
            ResolvedNormalization::resolve(DetectionMode::Weak, &NormalizationConfig::default());
        assert!(!resolved.ignore_identifiers);
        assert!(resolved.ignore_string_values);
        assert!(!resolved.ignore_numeric_values);
    }

    #[test]
    fn resolve_semantic_mode_all_true() {
        let resolved = ResolvedNormalization::resolve(
            DetectionMode::Semantic,
            &NormalizationConfig::default(),
        );
        assert!(resolved.ignore_identifiers);
        assert!(resolved.ignore_string_values);
        assert!(resolved.ignore_numeric_values);
    }

    #[test]
    fn resolve_override_forces_true() {
        // Strict mode defaults to all false, but override forces ignore_identifiers to true
        let overrides = NormalizationConfig {
            ignore_identifiers: Some(true),
            ignore_string_values: None,
            ignore_numeric_values: None,
        };
        let resolved = ResolvedNormalization::resolve(DetectionMode::Strict, &overrides);
        assert!(resolved.ignore_identifiers);
        assert!(!resolved.ignore_string_values);
        assert!(!resolved.ignore_numeric_values);
    }

    #[test]
    fn resolve_override_forces_false() {
        // Semantic mode defaults to all true, but override forces ignore_identifiers to false
        let overrides = NormalizationConfig {
            ignore_identifiers: Some(false),
            ignore_string_values: Some(false),
            ignore_numeric_values: None,
        };
        let resolved = ResolvedNormalization::resolve(DetectionMode::Semantic, &overrides);
        assert!(!resolved.ignore_identifiers);
        assert!(!resolved.ignore_string_values);
        assert!(resolved.ignore_numeric_values); // not overridden
    }

    #[test]
    fn resolve_all_overrides_on_weak() {
        let overrides = NormalizationConfig {
            ignore_identifiers: Some(true),
            ignore_string_values: Some(false), // override weak default (true -> false)
            ignore_numeric_values: Some(true),
        };
        let resolved = ResolvedNormalization::resolve(DetectionMode::Weak, &overrides);
        assert!(resolved.ignore_identifiers);
        assert!(!resolved.ignore_string_values); // overridden from true to false
        assert!(resolved.ignore_numeric_values);
    }

    // ── DuplicatesConfig deserialization ──────────────────────────────

    #[test]
    fn duplicates_config_json_all_fields() {
        let json = r#"{
            "enabled": false,
            "mode": "semantic",
            "minTokens": 100,
            "minLines": 10,
            "threshold": 5.0,
            "ignore": ["**/vendor/**"],
            "skipLocal": true,
            "crossLanguage": true,
            "ignoreImports": true
        }"#;
        let config: DuplicatesConfig = serde_json::from_str(json).unwrap();
        assert!(!config.enabled);
        assert_eq!(config.mode, DetectionMode::Semantic);
        assert_eq!(config.min_tokens, 100);
        assert_eq!(config.min_lines, 10);
        assert!((config.threshold - 5.0).abs() < f64::EPSILON);
        assert_eq!(config.ignore, vec!["**/vendor/**"]);
        assert!(config.skip_local);
        assert!(config.cross_language);
        assert!(config.ignore_imports);
    }

    #[test]
    fn duplicates_config_json_partial_uses_defaults() {
        let json = r#"{"mode": "weak"}"#;
        let config: DuplicatesConfig = serde_json::from_str(json).unwrap();
        assert!(config.enabled); // default
        assert_eq!(config.mode, DetectionMode::Weak);
        assert_eq!(config.min_tokens, 50); // default
        assert_eq!(config.min_lines, 5); // default
    }

    #[test]
    fn normalization_config_json_overrides() {
        let json = r#"{
            "ignoreIdentifiers": true,
            "ignoreStringValues": false
        }"#;
        let config: NormalizationConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.ignore_identifiers, Some(true));
        assert_eq!(config.ignore_string_values, Some(false));
        assert_eq!(config.ignore_numeric_values, None);
    }

    // ── TOML deserialization ────────────────────────────────────────

    #[test]
    fn duplicates_config_toml_all_fields() {
        let toml_str = r#"
enabled = false
mode = "weak"
minTokens = 75
minLines = 8
threshold = 3.0
ignore = ["vendor/**"]
skipLocal = true
crossLanguage = true
ignoreImports = true

[normalization]
ignoreIdentifiers = true
ignoreStringValues = true
ignoreNumericValues = false
"#;
        let config: DuplicatesConfig = toml::from_str(toml_str).unwrap();
        assert!(!config.enabled);
        assert_eq!(config.mode, DetectionMode::Weak);
        assert_eq!(config.min_tokens, 75);
        assert_eq!(config.min_lines, 8);
        assert!((config.threshold - 3.0).abs() < f64::EPSILON);
        assert_eq!(config.ignore, vec!["vendor/**"]);
        assert!(config.skip_local);
        assert!(config.cross_language);
        assert!(config.ignore_imports);
        assert_eq!(config.normalization.ignore_identifiers, Some(true));
        assert_eq!(config.normalization.ignore_string_values, Some(true));
        assert_eq!(config.normalization.ignore_numeric_values, Some(false));
    }

    #[test]
    fn duplicates_config_toml_defaults() {
        let toml_str = "";
        let config: DuplicatesConfig = toml::from_str(toml_str).unwrap();
        assert!(config.enabled);
        assert_eq!(config.mode, DetectionMode::Mild);
        assert_eq!(config.min_tokens, 50);
        assert_eq!(config.min_lines, 5);
    }

    // ── NormalizationConfig edge cases ──────────────────────────────

    #[test]
    fn normalization_config_default_all_none() {
        let config = NormalizationConfig::default();
        assert!(config.ignore_identifiers.is_none());
        assert!(config.ignore_string_values.is_none());
        assert!(config.ignore_numeric_values.is_none());
    }

    #[test]
    fn normalization_config_empty_json_object() {
        let config: NormalizationConfig = serde_json::from_str("{}").unwrap();
        assert!(config.ignore_identifiers.is_none());
        assert!(config.ignore_string_values.is_none());
        assert!(config.ignore_numeric_values.is_none());
    }

    // ── DetectionMode default ───────────────────────────────────────

    #[test]
    fn detection_mode_default_is_mild() {
        assert_eq!(DetectionMode::default(), DetectionMode::Mild);
    }

    // ── ResolvedNormalization equality ───────────────────────────────

    #[test]
    fn resolved_normalization_equality() {
        let a = ResolvedNormalization {
            ignore_identifiers: true,
            ignore_string_values: false,
            ignore_numeric_values: true,
        };
        let b = ResolvedNormalization {
            ignore_identifiers: true,
            ignore_string_values: false,
            ignore_numeric_values: true,
        };
        assert_eq!(a, b);

        let c = ResolvedNormalization {
            ignore_identifiers: false,
            ignore_string_values: false,
            ignore_numeric_values: true,
        };
        assert_ne!(a, c);
    }

    // ── Detection mode JSON deserialization ──────────────────────────

    #[test]
    fn detection_mode_json_deserialization() {
        let strict: DetectionMode = serde_json::from_str(r#""strict""#).unwrap();
        assert_eq!(strict, DetectionMode::Strict);

        let mild: DetectionMode = serde_json::from_str(r#""mild""#).unwrap();
        assert_eq!(mild, DetectionMode::Mild);

        let weak: DetectionMode = serde_json::from_str(r#""weak""#).unwrap();
        assert_eq!(weak, DetectionMode::Weak);

        let semantic: DetectionMode = serde_json::from_str(r#""semantic""#).unwrap();
        assert_eq!(semantic, DetectionMode::Semantic);
    }

    #[test]
    fn detection_mode_invalid_json() {
        let result: Result<DetectionMode, _> = serde_json::from_str(r#""aggressive""#);
        assert!(result.is_err());
    }

    // ── Serialize roundtrip ─────────────────────────────────────────

    #[test]
    fn duplicates_config_json_roundtrip() {
        let config = DuplicatesConfig {
            enabled: false,
            mode: DetectionMode::Semantic,
            min_tokens: 100,
            min_lines: 10,
            threshold: 5.5,
            ignore: vec!["test/**".to_string()],
            skip_local: true,
            cross_language: true,
            ignore_imports: true,
            normalization: NormalizationConfig {
                ignore_identifiers: Some(true),
                ignore_string_values: None,
                ignore_numeric_values: Some(false),
            },
        };
        let json = serde_json::to_string(&config).unwrap();
        let restored: DuplicatesConfig = serde_json::from_str(&json).unwrap();
        assert!(!restored.enabled);
        assert_eq!(restored.mode, DetectionMode::Semantic);
        assert_eq!(restored.min_tokens, 100);
        assert_eq!(restored.min_lines, 10);
        assert!((restored.threshold - 5.5).abs() < f64::EPSILON);
        assert!(restored.skip_local);
        assert!(restored.cross_language);
        assert!(restored.ignore_imports);
        assert_eq!(restored.normalization.ignore_identifiers, Some(true));
        assert!(restored.normalization.ignore_string_values.is_none());
        assert_eq!(restored.normalization.ignore_numeric_values, Some(false));
    }

    // ── NormalizationConfig skip_serializing_if ─────────────────────

    #[test]
    fn normalization_none_fields_not_serialized() {
        let config = NormalizationConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        assert!(
            !json.contains("ignoreIdentifiers"),
            "None fields should be skipped"
        );
        assert!(
            !json.contains("ignoreStringValues"),
            "None fields should be skipped"
        );
        assert!(
            !json.contains("ignoreNumericValues"),
            "None fields should be skipped"
        );
    }

    #[test]
    fn normalization_some_fields_serialized() {
        let config = NormalizationConfig {
            ignore_identifiers: Some(true),
            ignore_string_values: None,
            ignore_numeric_values: Some(false),
        };
        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("ignoreIdentifiers"));
        assert!(!json.contains("ignoreStringValues"));
        assert!(json.contains("ignoreNumericValues"));
    }
}