omnicoach 0.3.0

Lightweight, high-signal static analysis and command linter for Python and Rust
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
//! Flags private helpers that are neither colocated right after their single public consumer nor
//! placed in the trailing helper section at the end of the scope.

use crate::code_lint::ast::{self, CallClusterRule, ParsedFile};
use crate::code_lint::contract::{CodeRule, RuleTarget};
use crate::diagnostic::{Diagnostic, Language, RuleName, ViolationTemplate, violation_template};
use crate::rule_declaration::{
    Classification, Consensus, Declaration, Example, ImpactedQuality, Precision, Reference,
    RuleDoc, RuleOptions, Topic,
};
use std::path::Path;

const TEMPLATE: ViolationTemplate = violation_template! {
    summary: "Private helper `{function}` is separated from the helper cluster of `{caller}`.",
    rationale: "Stranding `{function}` between unrelated public functions or splitting the helpers of `{caller}` between the inline cluster and the trailing helper section fractures the layout of the scope.",
    suggestion: "Move `{function}` to the helper cluster of `{caller}` or the end of the scope, for example below `{anchor}` (ends on line {line}).",
};

/// The rule's declaration.
pub const RULE: CodeRule = CodeRule {
    declaration: Declaration {
        name: RuleName("uncolocated-helper"),
        template: &TEMPLATE,
        languages: &[Language::Python, Language::Rust],
        options: RuleOptions::code_rule(()),
        classification: Classification {
            topics: &[Topic::DECLARATION_ORDER],
            precision: Precision::Exact,
            consensus: Consensus::Opinionated,
            impacted_quality: ImpactedQuality::Maintainability,
        },
        doc: RuleDoc {
            summary: "Flags private helpers that are neither colocated right after their single public consumer nor placed in the trailing helper section at the end of the scope.",
            what_it_does: indoc::indoc! {r"
                Flags a private helper function, method, or type declared below its public
                consumers that is neither right after its only public consumer nor in the trailing
                helper section after the last public declaration of the module, Python `class`, or
                Rust inherent `impl` block. Both `[pub_a, _a_helper, pub_b, _b_helper]` and
                `[pub_a, pub_b, _a_helper, _b_helper]` pass, but one consumer's helpers are not
                split between the two places. Helpers above their consumers and unreached private
                declarations are left to `private-before-public`."},
            why_is_this_bad: indoc::indoc! {r"
                A private helper belongs either directly underneath the single public entrypoint it
                implements (vertical slice) or in the trailing private implementation section at the
                bottom of the scope. Stranding a single-use or shared helper in the middle of a
                scope between unrelated public declarations forces readers to jump over internal
                helpers while scanning the public API and splits related helpers apart.

                Place each single-use helper either immediately after its consumer or in the
                trailing helper section at the end of the scope, and always place multi-use helpers
                at the end of the scope."},
            known_problems: Some(indoc::indoc! {r"
                - Module-level constants (`const`, `static`, `UPPER_CASE = ...`) and type aliases
                  are not ordered.
                - In Rust macro arguments, a pattern binding or named argument that shares a sibling
                  declaration's name counts as a reference."}),
            references: &[
                Reference {
                    title: "Robert C. Martin: Clean Code — Chapter 5: Formatting (Vertical Distance & Dependent Functions)",
                    url: "https://www.oreilly.com/library/view/clean-code-a/9780136083238/",
                },
                Reference {
                    title: "Hitz & Montazeri (1995): Measuring Coupling and Cohesion in Object-Oriented Systems (LCOM4)",
                    url: "https://www.researchgate.net/publication/242402032_Measuring_Coupling_and_Cohesion_in_Object-Oriented_Systems",
                },
            ],
            examples: &[
                Example {
                    language: Language::Python,
                    flagged: indoc::indoc! {r"
                        def parse_header(raw: str) -> str:
                            return _strip_prefix(raw)

                        def parse_body(raw: str) -> str:
                            return raw.strip()

                        def _strip_prefix(raw: str) -> str:
                            return raw.removeprefix('H:')

                        def parse_footer(raw: str) -> str:
                            return raw.rstrip()
                    "},
                    flagged_span: "_strip_prefix",
                    fixed: indoc::indoc! {r"
                        def parse_header(raw: str) -> str:
                            return _strip_prefix(raw)

                        def _strip_prefix(raw: str) -> str:
                            return raw.removeprefix('H:')

                        def parse_body(raw: str) -> str:
                            return raw.strip()

                        def parse_footer(raw: str) -> str:
                            return raw.rstrip()
                    "},
                },
                Example {
                    language: Language::Rust,
                    flagged: indoc::indoc! {r"
                        pub struct PacketDecoder;

                        impl PacketDecoder {
                            pub fn decode_header(&self, raw: &str) -> bool {
                                Self::is_non_empty(raw)
                            }

                            pub fn decode_body(&self, raw: &str) -> bool {
                                Self::is_non_empty(raw)
                            }

                            fn is_non_empty(raw: &str) -> bool {
                                !raw.is_empty()
                            }

                            pub fn decode_footer(&self, raw: &str) -> usize {
                                raw.len()
                            }
                        }
                    "},
                    flagged_span: "is_non_empty",
                    fixed: indoc::indoc! {r"
                        pub struct PacketDecoder;

                        impl PacketDecoder {
                            pub fn decode_header(&self, raw: &str) -> bool {
                                Self::is_non_empty(raw)
                            }

                            pub fn decode_body(&self, raw: &str) -> bool {
                                Self::is_non_empty(raw)
                            }

                            pub fn decode_footer(&self, raw: &str) -> usize {
                                raw.len()
                            }

                            fn is_non_empty(raw: &str) -> bool {
                                !raw.is_empty()
                            }
                        }
                    "},
                },
            ],
        },
    },
    target: RuleTarget::SourceOnly,
    check: check_file,
};

fn check_file(rule: &CodeRule, path: &Path, file: &ParsedFile, (): ()) -> Vec<Diagnostic> {
    ast::collect_call_cluster_findings(file, CallClusterRule::UncolocatedHelper)
        .iter()
        .map(|finding| {
            let line = finding.anchor.line.to_string();
            rule.diagnostic_at_node(
                path,
                &finding.name_node,
                &[
                    ("function", &finding.item),
                    ("caller", &finding.related),
                    ("anchor", &finding.anchor.name),
                    ("line", &line),
                ],
            )
        })
        .collect()
}

#[cfg(test)]
crate::test_utils::rule_test!(
    RULE,
    {
        Python => {
            pass: [
                helper_right_after_its_only_caller_allowed => r#"
                    def build_header(raw: str) -> str:
                        return _format_header(raw)

                    def _format_header(token: str) -> str:
                        return _wrap_brackets(token)

                    def _wrap_brackets(token: str) -> str:
                        return f"[{token}]"

                    def build_footer(raw: str) -> str:
                        return raw.strip()
                "#,
                cluster_of_last_public_function_before_shared_helper_allowed => r#"
                    def build_header(raw: str) -> str:
                        return _normalize_token(raw)

                    def build_footer(raw: str) -> str:
                        return _wrap_brackets(_normalize_token(raw))

                    def _wrap_brackets(token: str) -> str:
                        return f"[{token}]"

                    def _normalize_token(raw: str) -> str:
                        return raw.strip()
                "#,
                shared_helper_in_trailing_section_allowed => r#"
                    def build_header(raw: str) -> str:
                        return _normalize_token(raw)

                    def build_footer(raw: str) -> str:
                        return _normalize_token(raw)

                    def _normalize_token(raw: str) -> str:
                        return raw.strip()
                "#,
                public_caller_of_public_function_does_not_share_its_helpers => r#"
                    def build_footer(raw: str) -> str:
                        return build_header(raw)

                    def build_header(raw: str) -> str:
                        return _format_header(raw)

                    def _format_header(token: str) -> str:
                        return f"[{token}]"

                    def build_title(raw: str) -> str:
                        return raw.title()
                "#,
                all_private_helpers_at_end_of_scope => r#"
                    class Compiler:
                        def compile_all(self, source: str) -> str:
                            return self._prepare_batch(source)

                        def compile_unit(self, source: str) -> str:
                            return self._emit_bytecode(source)

                        def _prepare_batch(self, source: str) -> str:
                            return source.lstrip()

                        def _emit_bytecode(self, source: str) -> str:
                            return source.strip()
                "#,
                uncalled_private_function_exempt => r#"
                    class Session:
                        def connect(self) -> str:
                            return "connected"

                        def _unused_hook(self) -> None:
                            pass

                        def close(self) -> None:
                            pass
                "#,
                constructor_helper_after_constructor_cluster_allowed => r#"
                    class Session:
                        def __new__(cls, host: str) -> "Session":
                            return cls._allocate()

                        def __init__(self, host: str) -> None:
                            self.host = host

                        @classmethod
                        def _allocate(cls) -> "Session":
                            return super().__new__(cls)

                        def connect(self) -> str:
                            return self.host
                "#,
                second_constructor_keeps_trailing_section_valid => r#"
                    class Pool:
                        def __new__(cls, limit: int) -> "Pool":
                            cls._check_limit(limit)
                            return super().__new__(cls)

                        def __init__(self, limit: int) -> None:
                            self.limit = limit

                        def acquire(self) -> int:
                            return self.limit

                        @staticmethod
                        def _check_limit(limit: int) -> bool:
                            return limit > 0
                "#,
                class_method_local_binding_does_not_bridge_module_helper => r#"
                    class Formatter:
                        def render(self, _strip_header: str) -> str:
                            return _strip_header

                    def format_with_formatter(raw: str) -> str:
                        return Formatter().render(raw)

                    def format_header(raw: str) -> str:
                        return _strip_header(raw)

                    def _strip_header(raw: str) -> str:
                        return raw.strip()

                    def format_footer(raw: str) -> str:
                        return raw.rstrip()
                "#,
            ],
            fail: [
                single_use_helper_stranded_in_middle_of_module => r#"
                    def render_title(text: str) -> str:
                        return _clean_title(text)

                    def render_body(text: str) -> str:
                        return text

                    def _clean_title(text: str) -> str:
                        return text.strip()

                    def render_footer(text: str) -> str:
                        return text.rstrip()
                "# => "_clean_title",
                shared_helper_stranded_before_trailing_public_method => r#"
                    class Tracker:
                        def load(self, text: str) -> str:
                            return self._parse_line(text)

                        def reload(self, text: str) -> str:
                            return self._parse_line(text)

                        def _parse_line(self, text: str) -> str:
                            return text.strip()

                        def clear(self) -> None:
                            pass
                "# => "_parse_line",
                exclusive_helper_cluster_split_between_both_places => r#"
                    def export_json(raw: str) -> str:
                        return _serialize_json(_trim_input(raw))

                    def _serialize_json(clean: str) -> str:
                        return _quote_json(clean)

                    def export_yaml(raw: str) -> str:
                        return _trim_input(raw)

                    def _trim_input(raw: str) -> str:
                        return raw.strip()

                    def _quote_json(clean: str) -> str:
                        return f'"{clean}"'
                "# => "_quote_json",
                private_class_stranded_between_unrelated_public_classes => r#"
                    class OrderProcessor:
                        def process(self) -> object:
                            return _OrderReceipt()

                    class PaymentGateway:
                        def charge(self) -> bool:
                            return True

                    class _OrderReceipt:
                        pass

                    class AuditLogger:
                        def record(self) -> None:
                            pass
                "# => "_OrderReceipt",
            ],
        },
        Rust => {
            pass: [
                helper_right_after_its_only_caller_allowed => r#"
                    pub fn parse_header(input: &str) -> &str {
                        strip_header_prefix(input)
                    }

                    fn strip_header_prefix(input: &str) -> &str {
                        input.trim_start_matches("H:")
                    }

                    pub fn parse_footer(input: &str) -> &str {
                        input.trim()
                    }
                "#,
                shared_helper_in_trailing_section_allowed => r#"
                    pub fn parse_header(input: &str) -> &str {
                        trim_ascii(input)
                    }

                    pub fn parse_footer(input: &str) -> &str {
                        trim_ascii(input)
                    }

                    fn trim_ascii(input: &str) -> &str {
                        input.trim()
                    }
                "#,
                second_constructor_keeps_trailing_section_valid => r#"
                    pub struct FrameParser;

                    impl FrameParser {
                        pub fn new() -> Self {
                            Self::validate_seed();
                            Self
                        }

                        pub fn try_new() -> Option<Self> {
                            Some(Self)
                        }

                        pub fn parse(&self, raw: &str) -> usize {
                            raw.len()
                        }

                        fn validate_seed() {}
                    }
                "#,
                inline_test_fn_exempt => r#"
                    pub struct FrameParser;

                    impl FrameParser {
                        #[cfg(test)]
                        pub fn parse_for_test(raw: &str) -> bool {
                            Self::check(raw)
                        }

                        pub fn parse(&self, raw: &str) -> bool {
                            Self::check(raw)
                        }

                        fn check(raw: &str) -> bool {
                            !raw.is_empty()
                        }

                        pub fn len(&self) -> usize {
                            0
                        }
                    }
                "#,
            ],
            fail: [
                single_use_helper_stranded_in_middle_of_module => r#"
                    pub fn encode_key(key: &str) -> usize {
                        hash_key(key)
                    }

                    pub fn encode_value(value: &str) -> usize {
                        value.len()
                    }

                    fn hash_key(key: &str) -> usize {
                        key.len()
                    }

                    pub fn encode_footer(footer: &str) -> usize {
                        footer.len()
                    }
                "# => "hash_key",
                shared_helper_stranded_before_last_pub_method => r#"
                    pub struct Router;

                    impl Router {
                        pub fn route_get(&self, path: &str) -> bool {
                            self.is_valid_path(path)
                        }

                        pub fn route_post(&self, path: &str) -> bool {
                            self.is_valid_path(path)
                        }

                        fn is_valid_path(&self, path: &str) -> bool {
                            path.starts_with('/')
                        }

                        pub fn route_delete(&self, path: &str) -> bool {
                            !path.is_empty()
                        }
                    }
                "# => "is_valid_path",
                private_enum_stranded_before_trailing_pub_struct => r#"
                    pub fn summarize(input: &str) -> usize {
                        let role = if input.is_empty() {
                            UseRole::Read
                        } else {
                            UseRole::Write
                        };
                        match role {
                            UseRole::Read => 1,
                            UseRole::Write => 2,
                        }
                    }

                    pub fn validate(input: &str) -> bool {
                        !input.is_empty()
                    }

                    enum UseRole {
                        Read,
                        Write,
                    }

                    pub struct SummaryReport {
                        pub count: usize,
                    }
                "# => "UseRole",
            ],
        },
    }
);