rustqual 1.6.0

Comprehensive Rust code quality analyzer — seven dimensions: IOSP, Complexity, DRY, SRP, Coupling, Test Quality, Architecture
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
//! Unit tests for the Layer Rule.
//!
//! Covers the four axes the rule has to get right:
//!   1. Layer assignment by path glob (incl. `reexport_points` bypass).
//!   2. Import resolution (`crate::...`, `std/core/alloc`, `self`, external).
//!   3. Rank comparison (inner can import from inner; outer-from-inner is
//!      fine; inner-from-outer is a violation).
//!   4. `unmatched_behavior` = composition_root vs strict_error.

use crate::adapters::analyzers::architecture::layer_rule::{
    check_layer_rule, LayerDefinitions, LayerRuleInput, UnmatchedBehavior,
};
use crate::adapters::analyzers::architecture::{MatchLocation, ViolationKind};
use globset::{Glob, GlobMatcher, GlobSet, GlobSetBuilder};
use std::collections::HashMap;

// ── helpers ────────────────────────────────────────────────────────────

fn glob_set(patterns: &[&str]) -> GlobSet {
    let mut b = GlobSetBuilder::new();
    for p in patterns {
        b.add(Glob::new(p).expect("valid glob"));
    }
    b.build().expect("valid glob set")
}

fn glob_matcher(pattern: &str) -> GlobMatcher {
    Glob::new(pattern).expect("valid glob").compile_matcher()
}

fn default_layers() -> LayerDefinitions {
    LayerDefinitions::new(
        vec![
            "domain".to_string(),
            "port".to_string(),
            "application".to_string(),
            "adapter".to_string(),
        ],
        vec![
            ("domain".to_string(), glob_set(&["src/domain/**"])),
            ("port".to_string(), glob_set(&["src/ports/**"])),
            ("application".to_string(), glob_set(&["src/app/**"])),
            ("adapter".to_string(), glob_set(&["src/adapters/**"])),
        ],
    )
}

fn parse_file(src: &str) -> syn::File {
    syn::parse_str(src).expect("test fixture must parse")
}

struct Fixture {
    parsed: Vec<(String, syn::File)>,
}

impl Fixture {
    fn new(files: &[(&str, &str)]) -> Self {
        let parsed = files
            .iter()
            .map(|(p, s)| (p.to_string(), parse_file(s)))
            .collect();
        Self { parsed }
    }

    fn refs(&self) -> Vec<(String, &syn::File)> {
        self.parsed.iter().map(|(p, f)| (p.clone(), f)).collect()
    }
}

/// External-crate layer mappings for a layer-rule test run (exact + glob).
struct Externals<'a> {
    exact: &'a HashMap<String, String>,
    glob: &'a [(GlobMatcher, String)],
}

fn run(
    fixture: &Fixture,
    layers: &LayerDefinitions,
    reexport: &GlobSet,
    unmatched: UnmatchedBehavior,
    externals: Externals,
) -> Vec<MatchLocation> {
    let refs = fixture.refs();
    check_layer_rule(
        &refs,
        &LayerRuleInput {
            layers,
            reexport_points: reexport,
            unmatched_behavior: unmatched,
            external_exact: externals.exact,
            external_glob: externals.glob,
        },
    )
}

fn run_simple(fixture: &Fixture) -> Vec<MatchLocation> {
    run(
        fixture,
        &default_layers(),
        &glob_set(&[]),
        UnmatchedBehavior::CompositionRoot,
        Externals {
            exact: &HashMap::new(),
            glob: &[],
        },
    )
}

// ── basic cases ────────────────────────────────────────────────────────

#[test]
fn clean_file_no_violations() {
    let fx = Fixture::new(&[("src/domain/mod.rs", "pub struct Foo;")]);
    assert!(run_simple(&fx).is_empty());
}

#[test]
fn same_layer_import_allowed() {
    let fx = Fixture::new(&[
        ("src/domain/mod.rs", "pub struct Bar;"),
        ("src/domain/foo.rs", "use crate::domain::Bar;"),
    ]);
    assert!(run_simple(&fx).is_empty());
}

#[test]
fn outer_importing_inner_allowed() {
    // adapter (rank 3) importing from domain (rank 0) is fine
    let fx = Fixture::new(&[
        ("src/domain/mod.rs", "pub struct Bar;"),
        ("src/adapters/mod.rs", "use crate::domain::Bar;"),
    ]);
    assert!(run_simple(&fx).is_empty());
}

#[test]
fn inner_importing_outer_is_violation() {
    // domain (rank 0) importing from adapter (rank 3) is forbidden
    let fx = Fixture::new(&[
        ("src/adapters/mod.rs", "pub struct Bar;"),
        ("src/domain/bad.rs", "use crate::adapters::Bar;"),
    ]);
    let hits = run_simple(&fx);
    assert_eq!(hits.len(), 1, "{hits:?}");
    match &hits[0].kind {
        ViolationKind::LayerViolation {
            from_layer,
            to_layer,
            imported_path,
        } => {
            assert_eq!(from_layer, "domain");
            assert_eq!(to_layer, "adapter");
            assert!(
                imported_path.starts_with("crate::adapters"),
                "imported_path = {imported_path:?}"
            );
        }
        other => panic!("unexpected kind: {other:?}"),
    }
    assert_eq!(hits[0].file, "src/domain/bad.rs");
}

#[test]
fn port_importing_application_is_violation() {
    // port (rank 1) importing from application (rank 2) is forbidden
    let fx = Fixture::new(&[
        ("src/app/mod.rs", "pub fn run() {}"),
        ("src/ports/bad.rs", "use crate::app::run;"),
    ]);
    let hits = run_simple(&fx);
    assert_eq!(hits.len(), 1);
    match &hits[0].kind {
        ViolationKind::LayerViolation {
            from_layer,
            to_layer,
            ..
        } => {
            assert_eq!(from_layer, "port");
            assert_eq!(to_layer, "application");
        }
        other => panic!("unexpected kind: {other:?}"),
    }
}

#[test]
fn application_importing_port_allowed() {
    // application (rank 2) importing from port (rank 1) is fine
    let fx = Fixture::new(&[
        ("src/ports/mod.rs", "pub trait Service {}"),
        ("src/app/use_case.rs", "use crate::ports::Service;"),
    ]);
    assert!(run_simple(&fx).is_empty());
}

// ── special first segments ─────────────────────────────────────────────

#[test]
fn std_core_alloc_ignored() {
    let fx = Fixture::new(&[(
        "src/domain/foo.rs",
        "use std::collections::HashMap; use core::fmt; use alloc::vec::Vec;",
    )]);
    assert!(run_simple(&fx).is_empty());
}

#[test]
fn self_and_super_ignored() {
    // For the layer rule these are same-crate, same-tree references.
    let fx = Fixture::new(&[(
        "src/domain/foo.rs",
        "use self::inner::thing; use super::other;",
    )]);
    assert!(run_simple(&fx).is_empty());
}

#[test]
fn unresolved_crate_segment_ignored() {
    // `crate::unknown` — no file defines it — is skipped (conservative).
    let fx = Fixture::new(&[("src/domain/foo.rs", "use crate::unknown::thing;")]);
    assert!(run_simple(&fx).is_empty());
}

// ── grouped imports ────────────────────────────────────────────────────

#[test]
fn grouped_use_flags_each_bad_leaf() {
    let fx = Fixture::new(&[
        ("src/domain/mod.rs", "pub struct A;"),
        ("src/adapters/mod.rs", "pub struct X;"),
        ("src/app/mod.rs", "pub struct Y;"),
        (
            "src/domain/bad.rs",
            "use crate::{domain::A, adapters::X, app::Y};",
        ),
    ]);
    let hits = run_simple(&fx);
    let to_layers: Vec<String> = hits
        .iter()
        .filter_map(|h| match &h.kind {
            ViolationKind::LayerViolation { to_layer, .. } => Some(to_layer.clone()),
            _ => None,
        })
        .collect();
    assert_eq!(hits.len(), 2, "expected two violations: {hits:?}");
    assert!(to_layers.contains(&"adapter".to_string()));
    assert!(to_layers.contains(&"application".to_string()));
}

// ── external crates ────────────────────────────────────────────────────

#[test]
fn external_exact_match_enforced() {
    let mut ext = HashMap::new();
    ext.insert("adapter_only_crate".to_string(), "adapter".to_string());
    let fx = Fixture::new(&[("src/domain/bad.rs", "use adapter_only_crate::X;")]);
    let hits = run(
        &fx,
        &default_layers(),
        &glob_set(&[]),
        UnmatchedBehavior::CompositionRoot,
        Externals {
            exact: &ext,
            glob: &[],
        },
    );
    assert_eq!(hits.len(), 1, "{hits:?}");
    match &hits[0].kind {
        ViolationKind::LayerViolation {
            from_layer,
            to_layer,
            imported_path,
        } => {
            assert_eq!(from_layer, "domain");
            assert_eq!(to_layer, "adapter");
            assert!(imported_path.starts_with("adapter_only_crate"));
        }
        other => panic!("unexpected: {other:?}"),
    }
}

#[test]
fn external_glob_match_enforced() {
    let ext_glob = vec![(glob_matcher("adp_*"), "adapter".to_string())];
    let fx = Fixture::new(&[("src/domain/bad.rs", "use adp_sqlite::Pool;")]);
    let hits = run(
        &fx,
        &default_layers(),
        &glob_set(&[]),
        UnmatchedBehavior::CompositionRoot,
        Externals {
            exact: &HashMap::new(),
            glob: &ext_glob,
        },
    );
    assert_eq!(hits.len(), 1, "{hits:?}");
}

#[test]
fn external_exact_wins_over_glob() {
    let mut ext_exact = HashMap::new();
    ext_exact.insert("adp_special".to_string(), "domain".to_string());
    let ext_glob = vec![(glob_matcher("adp_*"), "adapter".to_string())];
    // domain file imports "adp_special" — exact says "domain" (same layer) → OK
    let fx = Fixture::new(&[("src/domain/ok.rs", "use adp_special::X;")]);
    let hits = run(
        &fx,
        &default_layers(),
        &glob_set(&[]),
        UnmatchedBehavior::CompositionRoot,
        Externals {
            exact: &ext_exact,
            glob: &ext_glob,
        },
    );
    assert!(hits.is_empty(), "exact must win: {hits:?}");
}

#[test]
fn external_unknown_ignored() {
    let fx = Fixture::new(&[("src/domain/foo.rs", "use some_unknown_crate::Thing;")]);
    assert!(run_simple(&fx).is_empty());
}

// ── reexport points and unmatched ──────────────────────────────────────

#[test]
fn reexport_point_bypasses_rule() {
    let reexport = glob_set(&["src/lib.rs"]);
    let fx = Fixture::new(&[
        ("src/adapters/mod.rs", "pub struct X;"),
        ("src/lib.rs", "pub use crate::adapters::X;"),
    ]);
    let hits = run(
        &fx,
        &default_layers(),
        &reexport,
        UnmatchedBehavior::CompositionRoot,
        Externals {
            exact: &HashMap::new(),
            glob: &[],
        },
    );
    assert!(hits.is_empty(), "re-export point must bypass: {hits:?}");
}

#[test]
fn unmatched_composition_root_bypasses() {
    // src/lib.rs matches no layer, but CompositionRoot means no violation.
    let fx = Fixture::new(&[
        ("src/adapters/mod.rs", "pub struct X;"),
        ("src/lib.rs", "use crate::adapters::X;"),
    ]);
    let hits = run(
        &fx,
        &default_layers(),
        &glob_set(&[]),
        UnmatchedBehavior::CompositionRoot,
        Externals {
            exact: &HashMap::new(),
            glob: &[],
        },
    );
    assert!(hits.is_empty(), "unmatched composition root: {hits:?}");
}

#[test]
fn unmatched_strict_error_emits_one_violation() {
    let fx = Fixture::new(&[("src/unorganized.rs", "fn foo() {}")]);
    let hits = run(
        &fx,
        &default_layers(),
        &glob_set(&[]),
        UnmatchedBehavior::StrictError,
        Externals {
            exact: &HashMap::new(),
            glob: &[],
        },
    );
    assert_eq!(hits.len(), 1);
    match &hits[0].kind {
        ViolationKind::UnmatchedLayer { file } => {
            assert_eq!(file, "src/unorganized.rs");
        }
        other => panic!("unexpected kind: {other:?}"),
    }
}

#[test]
fn strict_error_does_not_flag_reexport_points() {
    let reexport = glob_set(&["src/lib.rs"]);
    let fx = Fixture::new(&[("src/lib.rs", "fn main() {}")]);
    let hits = run(
        &fx,
        &default_layers(),
        &reexport,
        UnmatchedBehavior::StrictError,
        Externals {
            exact: &HashMap::new(),
            glob: &[],
        },
    );
    assert!(hits.is_empty(), "{hits:?}");
}

// ── file paths with backslashes (windows-style) ────────────────────────

#[test]
fn windows_style_separators_work() {
    // rustqual normalizes to forward slashes before the architecture analyzer
    // sees the path. The layer rule relies on this — globs use `/`.
    let fx = Fixture::new(&[
        ("src/domain/mod.rs", "pub struct Bar;"),
        ("src/adapters/bad.rs", "use crate::domain::Bar;"),
    ]);
    assert!(run_simple(&fx).is_empty());
}