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
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
//! Flags a literal repeated inline in one file instead of being named once.

use crate::code_lint::ast::{self, AstNode, LiteralRole, LiteralValue, ParsedFile};
use crate::code_lint::contract::{CodeRule, RuleTarget};
use crate::code_lint::policy::is_trivial_literal;
use crate::diagnostic::{Diagnostic, Language, RuleName, ViolationTemplate, violation_template};
use crate::rule_declaration::{
    Classification, Consensus, CountOption, Declaration, Example, ImpactedQuality,
    LanguageDefaults, Precision, Reference, RuleDoc, RuleOptions, Topic,
};
use std::collections::HashMap;
use std::path::Path;

const MIN_OCCURRENCES: CountOption = CountOption {
    key: "min-occurrences",
    doc: "Minimum occurrences of a literal in a file, its constant definitions included, for it \
          to be flagged. Values below 2 behave as 2.",
    default: LanguageDefaults::new(2, &[]),
};

const TEMPLATE: ViolationTemplate = violation_template! {
    summary: "Literal `{expression}` appears {count} times in this file.",
    rationale: "A value copied inline has no name, and changing it means finding every copy: missing one silently desynchronizes the file.",
    suggestion: "Extract `{expression}` into one named constant (or reuse the existing one) and reference it at every site.",
};

/// The rule's declaration.
pub const RULE: CodeRule<CountOption> = CodeRule {
    declaration: Declaration {
        name: RuleName("repeated-literal"),
        template: &TEMPLATE,
        languages: &[Language::Python, Language::Rust],
        options: RuleOptions::code_rule(MIN_OCCURRENCES),
        classification: Classification {
            topics: &[Topic::LITERALS],
            precision: Precision::Heuristic,
            consensus: Consensus::Opinionated,
            impacted_quality: ImpactedQuality::Maintainability,
        },
        doc: RuleDoc {
            summary: "Flags a string or number literal repeated inline in one file instead of \
                      being named once.",
            what_it_does: indoc::indoc! {r#"
                Flags a string or number literal written inline several times in one file; equal
                values match whatever their spelling (`'id'` and `"id"`, `1_000` and `1000`), and
                trivial values such as `0`, `1` or `", "` are ignored. When a constant already
                holds the value, every inline use is flagged, otherwise every use after the first.
                Literals the language requires (such as `Literal[...]` values, `TypeVar` names,
                dictionary keys declared by an in-file `TypedDict` class, or Rust attributes),
                interpolated Python f-strings (outside their `{...}` expressions), arguments of
                formatting and assertion macros (`format!`, `assert_eq!`) and Rust `#[cfg(test)]`
                code are not checked."#},
            why_is_this_bad: indoc::indoc! {r#"
                A literal copied across a file is a value without a name: the reader must guess what
                `"primary-db"` or `30` stands for, and changing it means finding every copy. Missing
                one leaves the file silently inconsistent, and a search cannot tell the copies of
                this value from an unrelated literal that happens to be equal.

                Extract the value into one named constant and reference it at every site, or reuse
                the constant that already holds it. In a Python `case` pattern, match an `Enum`
                member or class constant by dotted name (`case Mode.READ:`): a bare name captures
                any value instead of comparing. For repeated dictionary keys in Python, declare a
                `TypedDict` class for the payload schema or extract a `Final` key constant
                (`PRICE_KEY: Final = "price"`)."#},
            known_problems: Some(indoc::indoc! {r"
                - A negative number written as a bare `-` token inside a Rust macro, such as
                  `vec![-42]`, is skipped.
                - Python constants defined by unpacking or chaining (`A, B = 3, 4`, `A = B = 3`)
                  are not recognized, so their values count as inline uses.
                - Keys of a Python `TypedDict` imported from another module or defined with the
                  functional `TypedDict('Name', {...})` call syntax are not resolved, so repeating
                  them as inline string keys is still flagged."}),
            references: &[
                Reference {
                    title: "SonarSource RSPEC-1192: String literals should not be duplicated",
                    url: "https://rules.sonarsource.com/python/RSPEC-1192/",
                },
                Reference {
                    title: "goconst: find repeated strings that could be constants",
                    url: "https://github.com/jgautheron/goconst",
                },
                Reference {
                    title: "Checkstyle: MultipleStringLiterals",
                    url: "https://checkstyle.sourceforge.io/checks/coding/multiplestringliterals.html",
                },
            ],
            examples: &[
                Example {
                    language: Language::Python,
                    flagged: indoc::indoc! {r#"
                        def fetch_orders(session):
                            return session.get("https://api.example.com/orders")

                        def create_order(session, order):
                            return session.post("https://api.example.com/orders", json=order)
                    "#},
                    flagged_span: "\"https://api.example.com/orders\"",
                    fixed: indoc::indoc! {r#"
                        ORDERS_URL = "https://api.example.com/orders"

                        def fetch_orders(session):
                            return session.get(ORDERS_URL)

                        def create_order(session, order):
                            return session.post(ORDERS_URL, json=order)
                    "#},
                },
                Example {
                    language: Language::Rust,
                    flagged: indoc::indoc! {r#"
                        fn read_config() -> io::Result<String> {
                            fs::read_to_string("omni.toml")
                        }

                        fn has_config() -> bool {
                            Path::new("omni.toml").exists()
                        }
                    "#},
                    flagged_span: "\"omni.toml\"",
                    fixed: indoc::indoc! {r#"
                        const CONFIG_FILE: &str = "omni.toml";

                        fn read_config() -> io::Result<String> {
                            fs::read_to_string(CONFIG_FILE)
                        }

                        fn has_config() -> bool {
                            Path::new(CONFIG_FILE).exists()
                        }
                    "#},
                },
            ],
        },
    },
    // Test files repeat self-contained literals across independent test cases (DAMP), so only
    // production files (and non-`#[cfg(test)]` Rust items) are checked.
    target: RuleTarget::SourceOnly,
    check: check_file,
};

fn check_file(
    rule: &CodeRule<CountOption>,
    path: &Path,
    file: &ParsedFile,
    min_occurrences: usize,
) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();
    for group in group_literals(file) {
        let count = (group.definitions + group.inline_uses.len()).to_string();
        for node in group.flagged_uses(min_occurrences) {
            diagnostics.push(rule.diagnostic_at_node(
                path,
                node,
                &[("expression", &node.text()), ("count", &count)],
            ));
        }
    }
    diagnostics
}

/// The occurrences of one literal value in a file.
///
/// Only direct scalar constant initializers (`X = "a"`) count toward `definitions`; composite
/// constant initializers (`HOSTS = ["a", "b"]`, `pub const RULE: CodeRule = ...`) are skipped by
/// the AST extractor so a single inline use of the same literal elsewhere in the file is not flagged.
struct LiteralGroup<'a> {
    definitions: usize,
    inline_uses: Vec<AstNode<'a>>,
}

impl<'a> LiteralGroup<'a> {
    /// The inline uses to flag: all of them once a constant holds the value, every use after
    /// the first otherwise. A group without definitions has at least one inline use.
    fn flagged_uses(&self, min_occurrences: usize) -> &[AstNode<'a>] {
        let inline_count = self.inline_uses.len();
        if self.definitions > 0 && self.definitions + inline_count >= min_occurrences {
            &self.inline_uses
        } else if self.definitions == 0 && inline_count >= min_occurrences {
            &self.inline_uses[1..]
        } else {
            &[]
        }
    }
}

/// Groups the file's non-trivial literals by value, in first-seen order. Rust test code is
/// left out so a test literal cannot pair with a production one.
fn group_literals(file: &ParsedFile) -> Vec<LiteralGroup<'_>> {
    let mut index_by_value: HashMap<LiteralValue, usize> = HashMap::new();
    let mut groups: Vec<LiteralGroup<'_>> = Vec::new();
    for occurrence in ast::collect_literal_occurrences(file) {
        if is_trivial_literal(&occurrence.value) || occurrence.node.is_in_rust_inline_test() {
            continue;
        }
        let index = *index_by_value.entry(occurrence.value).or_insert_with(|| {
            groups.push(LiteralGroup {
                definitions: 0,
                inline_uses: Vec::new(),
            });
            groups.len() - 1
        });
        let group = &mut groups[index];
        match occurrence.role {
            LiteralRole::ConstantDefinition => group.definitions += 1,
            LiteralRole::Inline => group.inline_uses.push(occurrence.node),
        }
    }
    groups
}

#[cfg(test)]
crate::test_utils::rule_test!(
    RULE,
    repeat: DistinctLiterals,
    {
        Python => {
            pass: [
                single_occurrence => r#"
                    connect("primary-db")
                "#,
                trivial_integers => r#"
                    f(0, 1, -1, 2)
                    g(0, 1, -1, 2)
                "#,
                trivial_floats => r#"
                    f(0.0, 1.0, -1.0, 2.0)
                    g(0.0, 1.0, -1.0, 2.0)
                "#,
                single_char_strings => r#"
                    f("a") + f("a")
                "#,
                non_alphanumeric_strings => r#"
                    ", ".join(a) + ", ".join(b)
                "#,
                constants_sharing_a_value => r#"
                    MAX_RETRIES = 3
                    TUPLE_ARITY = 3
                "#,
                composite_constant_does_not_pair_with_single_use => r#"
                    HOSTS = ["primary-db", "replica-db"]
                    connect("primary-db")
                "#,
                str_distinct_from_bytes => r#"
                    send("ping")
                    send(b"ping")
                "#,
                number_distinct_from_negation => r#"
                    shift(42)
                    shift(-42)
                "#,
                raw_string_with_backslash_distinct_from_plain => r#"
                    re.split(r"a\nb", text)
                    text.split("a\nb")
                "#,
                repeated_docstrings => r#"
                    def first():
                        """Return the value."""

                    def second():
                        """Return the value."""
                "#,
                repeated_string_annotations => r#"
                    def first(node: "Node"): ...
                    def second(node: "Node"): ...
                "#,
                repeated_literal_type_values => r#"
                    first = Literal["on"]
                    second = Literal["on"]
                "#,
                repeated_type_names_in_cast => r#"
                    first = cast("Node", a)
                    second = cast("Node", b)
                "#,
                repeated_typed_dict_keys_in_key_positions => r#"
                    class TradeFillPayload(TypedDict):
                        symbol: str
                        price: float

                    def build_fill(symbol: str, price: float) -> TradeFillPayload:
                        return {"symbol": symbol, "price": price}

                    def read_price(fill: TradeFillPayload) -> float:
                        if "symbol" in fill:
                            return fill.get("price", fill["price"])
                        return fill["price"]
                "#,
                repeated_interpolated_fstrings => r#"
                    log(f"user {name} logged in")
                    log(f"user {name} logged in")
                "#,
            ],
            fail: [
                negative_numbers_in_mapping_and_keyword_patterns => r#"
                    match response:
                        case {-404: _}:
                            pass
                        case Response(status=-404):
                            pass
                "# => "-404",
                repeated_string_flags_second_use => r#"
                    connect("primary-db")
                    reconnect("primary-db")
                "# => r#""primary-db""#,
                repeated_number_flags_second_use => r#"
                    retry(timeout=30)
                    wait(30)
                "# => "30",
                repeated_negative_number => r#"
                    offset(-42)
                    shift(-42)
                "# => "-42",
                constant_then_inline_use_flags_inline => r#"
                    MODE = "fast"
                    run("fast")
                "# => r#""fast""#,
                constant_after_inline_use_flags_inline => r#"
                    run('fast')
                    MODE = "fast"
                "# => "'fast'",
                constant_in_module_if_body_flags_inline_use => r#"
                    connect(mode='safe')
                    if sys.platform == "win32":
                        MODE = "safe"
                "# => "'safe'",
                parenthesized_constant_flags_inline_use => r#"
                    log('connection refused')
                    MESSAGE = (
                        "connection refused"
                    )
                "# => "'connection refused'",
                quote_styles_are_the_same_literal => r#"
                    open('data.csv')
                    read("data.csv")
                "# => r#""data.csv""#,
                raw_and_plain_string_are_the_same_literal => r#"
                    open(r"data.csv")
                    read("data.csv")
                "# => r#""data.csv""#,
                digit_separators_are_the_same_number => r#"
                    limit(1_000)
                    cap(1000)
                "# => "1000",
                literal_inside_interpolation_counts => r#"
                    print(f"{row['status']}")
                    check(row['status'])
                "# => "'status'",
                case_pattern_literal_counts => r#"
                    match command:
                        case "deploy":
                            run()
                        case _:
                            log("deploy")
                "# => r#""deploy""#,
                repeated_byte_string => r#"
                    send(b"ping")
                    expect(b"ping")
                "# => r#"b"ping""#,
                typed_dict_key_repeated_in_non_key_position => r#"
                    class TradeFillPayload(TypedDict):
                        symbol: str

                    log("symbol")
                    log("symbol")
                "# => r#""symbol""#,
            ],
        },
        Rust => {
            pass: [
                single_occurrence => r#"
                    fn f() { connect("primary-db"); }
                "#,
                trivial_integers => r#"
                    fn f() {
                        g(0, 1, -1, 2);
                        h(0, 1, -1, 2);
                    }
                "#,
                trivial_floats => r#"
                    fn f() {
                        g(0.0, 1.0, -1.0, 2.0);
                        h(0.0, 1.0, -1.0, 2.0);
                    }
                "#,
                single_char_strings => r#"
                    fn f() {
                        g("a");
                        g("a");
                    }
                "#,
                non_alphanumeric_strings => r#"
                    fn f() {
                        a.join(", ");
                        b.join(", ");
                    }
                "#,
                constants_sharing_a_value => r#"
                    const MAX_RETRIES: u32 = 3;
                    const TUPLE_ARITY: usize = 3;
                "#,
                composite_constant_does_not_pair_with_single_use => r#"
                    const HOSTS: &[&str] = &["primary-db", "replica-db"];
                    fn f() { connect("primary-db"); }
                "#,
                str_distinct_from_bytes => r#"
                    fn f() {
                        send("ping");
                        send(b"ping");
                    }
                "#,
                number_distinct_from_negation => r#"
                    fn f() {
                        shift(42);
                        shift(-42);
                    }
                "#,
                raw_string_with_backslash_distinct_from_plain => r#"
                    fn f() {
                        split(r"a\tb");
                        split("a\tb");
                    }
                "#,
                test_module_literals_are_ignored => r#"
                    #[cfg(test)]
                    mod integration {
                        fn t() { connect("primary-db"); }
                    }

                    fn f() { connect("primary-db"); }
                "#,
                repeated_attribute_arguments => r#"
                    #[deprecated(note = "use new_api")]
                    fn first() {}

                    #[deprecated(note = "use new_api")]
                    fn second() {}
                "#,
                repeated_format_macro_arguments => r#"
                    fn f() {
                        println!("invalid count");
                        println!("invalid count");
                    }
                "#,
                repeated_assert_macro_arguments => r#"
                    fn f(count: u32) {
                        assert!(count > 0, "invalid count");
                        assert!(count < 9, "invalid count");
                    }
                "#,
                tuple_field_positions_are_not_literals => r#"
                    fn f(t: (u32, u32, u32, u32)) -> u32 {
                        t.3 + t.3
                    }
                "#,
                tuple_field_positions_in_macros_are_not_literals => r#"
                    fn f(t: (u32, u32, u32, u32)) -> Vec<u32> {
                        vec![t.3, t.3]
                    }
                "#,
                repeated_extern_abi => r#"
                    extern "system" { fn first(); }
                    extern "system" { fn second(); }
                "#,
                known_gap_values_inside_exempt_macros => r#"
                    fn f(status: &str) {
                        assert_eq!(status, "expected");
                        assert_eq!(status, "expected");
                    }
                "#,
                known_gap_negative_numbers_in_macros => r#"
                    fn f() {
                        vec![-42];
                        vec![-42];
                    }
                "#,
            ],
            fail: [
                repeated_string_flags_second_use => r#"
                    fn f() {
                        connect("primary-db");
                        reconnect("primary-db");
                    }
                "# => r#""primary-db""#,
                repeated_number_flags_second_use => r#"
                    fn f() {
                        retry(30);
                        wait(30);
                    }
                "# => "30",
                repeated_negative_number => r#"
                    fn f() {
                        offset(-42);
                        shift(-42);
                    }
                "# => "-42",
                constant_then_inline_use_flags_inline => r#"
                    const JJ: &str = "jj";
                    fn is_jj(program: &str) -> bool { program != "jj" }
                "# => r#""jj""#,
                constant_after_inline_use_flags_inline => r#"
                    fn is_jj(program: &str) -> bool { program != r"jj" }
                    const JJ: &str = "jj";
                "# => r#"r"jj""#,
                static_after_inline_use_flags_inline => r#"
                    fn f() { greet(r"omni"); }
                    static NAME: &str = "omni";
                "# => r#"r"omni""#,
                enum_discriminant_after_inline_use_flags_inline => r#"
                    fn f() { reply(404u16); }
                    enum Status { NotFound = 404 }
                "# => "404u16",
                static_mut_initializer_is_an_inline_use => r#"
                    fn f() { wait(30u32); }
                    static mut LIMIT: u32 = 30;
                "# => "30",
                raw_and_plain_string_are_the_same_literal => r#"
                    fn f() {
                        open(r"data.csv");
                        read("data.csv");
                    }
                "# => r#""data.csv""#,
                digit_separators_are_the_same_number => r#"
                    fn f() {
                        limit(1_000);
                        cap(1000);
                    }
                "# => "1000",
                type_suffix_is_the_same_number => r#"
                    fn f() {
                        retry(30u64);
                        wait(30);
                    }
                "# => "30",
                match_arm_literal_counts => r#"
                    fn f(command: &str) {
                        match command {
                            "deploy" => run(),
                            _ => log("deploy"),
                        }
                    }
                "# => r#""deploy""#,
                matches_pattern_literal_counts => r#"
                    fn f(command: &str) -> bool {
                        matches!(command, "deploy") || command == "deploy"
                    }
                "# => r#""deploy""#,
                repeated_byte_string => r#"
                    fn f() {
                        send(b"ping");
                        expect(b"ping");
                    }
                "# => r#"b"ping""#,
            ],
        },
    }
);