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
//! Abstraction graph of one declaration scope (ADR 011): typed ordering edges, public-root
//! ownership, recursion groups, and levels.

use super::{ScopeItem, ScopeItemKind, Visibility};
use std::collections::BTreeMap;

/// A syntactic reference from one declaration in a scope to a sibling declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RelationFact {
    /// Index of the declaration that contains the reference.
    pub source: usize,
    /// Index of the referenced sibling declaration.
    pub target: usize,
    /// Where in `source` the reference appears.
    pub kind: RelationKind,
}

/// Which syntactic region of a declaration contains a reference to a sibling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RelationKind {
    /// A callable's parameter type annotation.
    Parameter,
    /// A callable's return type annotation.
    Return,
    /// A callable's body expression or statement.
    Body,
    /// A type's own fields, variants, base classes, or target type.
    Composition,
    /// A type's methods or `impl` blocks.
    Behavior,
}

/// Why an ordering edge places its higher item above its lower item (ADR 011 ยง3.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OrderingReason {
    /// `Callable -> Callable`: the higher callable calls the lower one.
    Call,
    /// `Type -> Type`: the higher type's own fields, variants, or bases contain the lower one.
    Containment,
    /// `Type -> Callable` or `Type -> Type`: the higher type's methods or `impl` blocks use the
    /// lower item.
    ImplBehavior,
    /// `Callable -> Type`: the higher callable uses the lower type only inside its body.
    Encapsulation,
    /// `Type -> Callable`: the lower callable names the higher type in its parameter or return
    /// types, so the type is the vocabulary of its contract.
    SignatureContract,
}

/// A downward abstraction edge: `items[higher]` reads before `items[lower]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OrderingEdge {
    /// Index of the item that reads first (caller, composite type, or contract type).
    pub higher: usize,
    /// Index of the item that reads after it (callee, component, or encapsulated detail).
    pub lower: usize,
    /// Why `higher` sits above `lower`.
    pub reason: OrderingReason,
}

/// Which public entrypoint unit an item belongs to.
///
/// A unit is a public item, except that all constructors of a scope form one unit identified by
/// the first constructor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(super) enum Ownership {
    /// A public item of unit `unit`, or a private item reached only from that unit.
    Owner(usize),
    /// A private item reached from two or more units.
    Shared,
    /// A private item reached from no public item.
    Unowned,
}

/// The abstraction graph of one declaration scope, indexed like its items.
pub struct ScopeGraph {
    /// Downward ordering edges, sorted.
    pub edges: Vec<OrderingEdge>,
    /// `Roots(f)`: sorted public items that reach `f` through private references only.
    pub(super) roots: Vec<Vec<usize>>,
    /// Sorted public entrypoint unit indices of each item (`Roots(f)` with constructors collapsed
    /// to the first constructor).
    pub unit_owners: Vec<Vec<usize>>,
    /// Strongly connected component of each item over `edges`.
    pub recursion_group: Vec<usize>,
    /// Strongly connected component of each item over the `edges` between private items: items
    /// that recurse into each other without going through a public entrypoint.
    pub(super) private_recursion_group: Vec<usize>,
    /// Level of each item over `edges`: `0` for leaves, one above the highest group below.
    pub level: Vec<usize>,
    /// Earliest sibling index before which each item (or a caller that reaches it through
    /// [`RelationKind::Body`]) is referenced when the scope body runs.
    pub(super) evaluated_before: Vec<Option<usize>>,
}

impl ScopeGraph {
    /// Builds the abstraction graph of a scope's items.
    pub fn new(items: &[ScopeItem<'_>]) -> Self {
        let edges = ordering_edges(items);
        let is_private = |idx: usize| items[idx].visibility == Visibility::Private;
        let mut lowers = vec![Vec::new(); items.len()];
        let mut private_lowers = vec![Vec::new(); items.len()];
        for edge in &edges {
            lowers[edge.higher].push(edge.lower);
            if is_private(edge.higher) && is_private(edge.lower) {
                private_lowers[edge.higher].push(edge.lower);
            }
        }
        let recursion_group = strongly_connected_components(&lowers);
        let private_recursion_group = strongly_connected_components(&private_lowers);
        let level = levels(&lowers, &recursion_group);
        let roots = public_roots(items);
        let unit_owners = unit_owners(items, &roots);
        let evaluated_before = evaluated_before(items);
        Self {
            edges,
            roots,
            unit_owners,
            recursion_group,
            private_recursion_group,
            level,
            evaluated_before,
        }
    }

    /// Returns the [`Ownership`] of item `idx`, derived from [`Self::unit_owners`].
    pub(super) fn ownership(&self, idx: usize) -> Ownership {
        match self.unit_owners[idx].as_slice() {
            [] => Ownership::Unowned,
            [unit] => Ownership::Owner(*unit),
            _ => Ownership::Shared,
        }
    }
}

/// Computes strongly connected component ids over `successors` with Tarjan's algorithm.
#[must_use]
pub fn strongly_connected_components(successors: &[Vec<usize>]) -> Vec<usize> {
    struct Tarjan<'a> {
        successors: &'a [Vec<usize>],
        next_index: usize,
        index: Vec<Option<usize>>,
        low_link: Vec<usize>,
        on_stack: Vec<bool>,
        stack: Vec<usize>,
        component: Vec<usize>,
        next_component: usize,
    }

    impl Tarjan<'_> {
        fn visit(&mut self, node: usize) {
            self.index[node] = Some(self.next_index);
            self.low_link[node] = self.next_index;
            self.next_index += 1;
            self.stack.push(node);
            self.on_stack[node] = true;
            for &next in &self.successors[node] {
                match self.index[next] {
                    None => {
                        self.visit(next);
                        self.low_link[node] = self.low_link[node].min(self.low_link[next]);
                    }
                    Some(next_index) if self.on_stack[next] => {
                        self.low_link[node] = self.low_link[node].min(next_index);
                    }
                    Some(_) => {}
                }
            }
            if Some(self.low_link[node]) == self.index[node] {
                while let Some(member) = self.stack.pop() {
                    self.on_stack[member] = false;
                    self.component[member] = self.next_component;
                    if member == node {
                        break;
                    }
                }
                self.next_component += 1;
            }
        }
    }

    let count = successors.len();
    let mut tarjan = Tarjan {
        successors,
        next_index: 0,
        index: vec![None; count],
        low_link: vec![0; count],
        on_stack: vec![false; count],
        stack: Vec::new(),
        component: vec![0; count],
        next_component: 0,
    };
    for node in 0..count {
        if tarjan.index[node].is_none() {
            tarjan.visit(node);
        }
    }
    tarjan.component
}

/// Levelizes `successors`: each component of `component` is one unit, at level `0` when nothing
/// is below it, otherwise one above the highest component below it.
#[must_use]
pub fn levels(successors: &[Vec<usize>], component: &[usize]) -> Vec<usize> {
    let component_count = component.iter().copied().max().map_or(0, |max| max + 1);
    let mut component_level = vec![0; component_count];
    // Tarjan numbers components in reverse topological order: every component below another
    // has a smaller id, so one pass in id order sees lower components first.
    let mut members = vec![Vec::new(); component_count];
    for (node, &id) in component.iter().enumerate() {
        members[id].push(node);
    }
    for id in 0..component_count {
        component_level[id] = members[id]
            .iter()
            .flat_map(|&node| &successors[node])
            .filter(|&&lower| component[lower] != id)
            .map(|&lower| component_level[component[lower]] + 1)
            .max()
            .unwrap_or(0);
    }
    component.iter().map(|&id| component_level[id]).collect()
}

/// Labels every downward abstraction edge between `items` with its ADR 011 ยง3.4 reason.
fn ordering_edges(items: &[ScopeItem<'_>]) -> Vec<OrderingEdge> {
    let is_type = |idx: usize| items[idx].kind == ScopeItemKind::Type;
    let mut reasons = BTreeMap::new();
    for (higher, item) in items.iter().enumerate() {
        match item.kind {
            ScopeItemKind::Type => {
                for &(lower, _) in &item.references {
                    let reason =
                        if is_type(lower) && item.has_reference(lower, RelationKind::Composition) {
                            OrderingReason::Containment
                        } else {
                            OrderingReason::ImplBehavior
                        };
                    reasons.entry((higher, lower)).or_insert(reason);
                }
            }
            ScopeItemKind::Callable => {
                for &(lower, _) in &item.references {
                    if !is_type(lower) {
                        reasons
                            .entry((higher, lower))
                            .or_insert(OrderingReason::Call);
                    }
                }
                for lower in encapsulated_types(items, item) {
                    reasons
                        .entry((higher, lower))
                        .or_insert(OrderingReason::Encapsulation);
                }
            }
        }
    }
    for (callable, item) in items.iter().enumerate() {
        if item.kind == ScopeItemKind::Callable {
            for signature_type in
                item.references_in(&[RelationKind::Parameter, RelationKind::Return])
            {
                if is_type(signature_type) {
                    reasons.insert(
                        (signature_type, callable),
                        OrderingReason::SignatureContract,
                    );
                }
            }
        }
    }
    reasons
        .into_iter()
        .filter(|&((higher, lower), _)| higher != lower)
        .map(|((higher, lower), reason)| OrderingEdge {
            higher,
            lower,
            reason,
        })
        .collect()
}

/// Types that `callable` uses in its body (directly or through the return type of a sibling it
/// calls) without exposing them through its signature or the fields of its signature types.
fn encapsulated_types(items: &[ScopeItem<'_>], callable: &ScopeItem<'_>) -> Vec<usize> {
    let is_type = |idx: usize| items[idx].kind == ScopeItemKind::Type;
    let mut signature = vec![false; items.len()];
    let mut stack: Vec<usize> = callable
        .references_in(&[RelationKind::Parameter, RelationKind::Return])
        .filter(|&idx| is_type(idx))
        .collect();
    while let Some(current) = stack.pop() {
        if !std::mem::replace(&mut signature[current], true) {
            stack.extend(
                items[current]
                    .references
                    .iter()
                    .map(|&(target, _)| target)
                    .filter(|&idx| is_type(idx)),
            );
        }
    }
    (0..items.len())
        .filter(|&candidate| is_type(candidate) && !signature[candidate])
        .filter(|&candidate| {
            callable.has_reference(candidate, RelationKind::Body)
                || callable.references_in(&[RelationKind::Body]).any(|callee| {
                    !is_type(callee) && items[callee].has_reference(candidate, RelationKind::Return)
                })
        })
        .collect()
}

/// Computes `Roots(f)` for every item: the sorted public items that reach it through private
/// references only.
fn public_roots(items: &[ScopeItem<'_>]) -> Vec<Vec<usize>> {
    let is_public = |idx: usize| items[idx].visibility == Visibility::Public;
    let mut callers = vec![Vec::new(); items.len()];
    for (caller, item) in items.iter().enumerate() {
        for &(callee, _) in &item.references {
            if callee != caller && !callers[callee].contains(&caller) {
                callers[callee].push(caller);
            }
        }
    }
    (0..items.len())
        .map(|idx| {
            if is_public(idx) {
                return vec![idx];
            }
            let mut visited = vec![false; items.len()];
            let mut stack = vec![idx];
            let mut roots = Vec::new();
            while let Some(current) = stack.pop() {
                if std::mem::replace(&mut visited[current], true) {
                    continue;
                }
                for &caller in &callers[current] {
                    if is_public(caller) {
                        roots.push(caller);
                    } else {
                        stack.push(caller);
                    }
                }
            }
            roots.sort_unstable();
            roots.dedup();
            roots
        })
        .collect()
}

/// Maps each item's roots to their sorted entrypoint unit indices.
fn unit_owners(items: &[ScopeItem<'_>], roots: &[Vec<usize>]) -> Vec<Vec<usize>> {
    let first_constructor = items.iter().position(|item| item.is_constructor);
    let unit_of = |root: usize| {
        if items[root].is_constructor {
            first_constructor.unwrap_or(root)
        } else {
            root
        }
    };
    roots
        .iter()
        .map(|item_roots| {
            let mut units: Vec<usize> = item_roots.iter().map(|&root| unit_of(root)).collect();
            units.sort_unstable();
            units.dedup();
            units
        })
        .collect()
}

/// Propagates each item's direct `evaluated_before` bound through [`RelationKind::Body`]
/// edges: if `u` must be defined before `bound`, any sibling `v < bound` reachable through
/// callable bodies from `u` must also be defined before `bound`.
fn evaluated_before(items: &[ScopeItem<'_>]) -> Vec<Option<usize>> {
    let count = items.len();
    let mut bounds: Vec<Option<usize>> = items.iter().map(|item| item.evaluated_before).collect();
    for start in 0..count {
        let Some(bound) = bounds[start] else {
            continue;
        };
        let mut stack = vec![start];
        let mut visited = vec![false; count];
        while let Some(current) = stack.pop() {
            if std::mem::replace(&mut visited[current], true) {
                continue;
            }
            for callee in items[current].references_in(&[RelationKind::Body]) {
                if callee < bound {
                    bounds[callee] = Some(bounds[callee].map_or(bound, |prev| prev.min(bound)));
                    stack.push(callee);
                }
            }
        }
    }
    bounds
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::code_lint::ast::call_clusters::{DeclarationScopeKind, collect_declaration_scopes};
    use crate::code_lint::ast::tree::ParsedFile;
    use crate::diagnostic::Language;
    use std::collections::HashMap;

    #[test]
    fn test_evaluated_before_propagates_body_edges_and_skips_behavior_and_signatures() {
        let source = indoc::indoc! {r"
            from __future__ import annotations

            def _cycle_a() -> int:
                return _cycle_b()

            def _cycle_b() -> int:
                return _cycle_a() + _shared()

            def _shared() -> int:
                return 1

            def _param_type() -> int:
                return 2

            def _method_helper() -> int:
                return 3

            def _early_caller(x: _param_type) -> None:
                _shared()

            X = _early_caller(0)

            class _PinnedBase:
                def method(self) -> int:
                    return _method_helper()

            class FirstPublic(_PinnedBase):
                pass

            def _late_caller() -> int:
                return _cycle_a()

            Y = _late_caller()

            class SecondPublic:
                pass
        "};
        let file = ParsedFile::new(source, Language::Python);
        let scopes = collect_declaration_scopes(&file);
        let module_scope = scopes
            .iter()
            .find(|scope| matches!(scope.kind, DeclarationScopeKind::Module))
            .expect("module scope");
        let graph = ScopeGraph::new(&module_scope.items);
        let bounds: HashMap<&str, Option<usize>> = module_scope
            .items
            .iter()
            .zip(&graph.evaluated_before)
            .map(|(item, &bound)| (item.name.as_str(), bound))
            .collect();

        let expected = vec![
            ("_early_caller", Some(6)),
            ("_late_caller", Some(9)),
            ("_cycle_a", Some(9)),
            ("_cycle_b", Some(9)),
            ("_shared", Some(6)),
            ("_param_type", None),
            ("_PinnedBase", Some(7)),
            ("_method_helper", None),
        ];
        let actual: Vec<(&str, Option<usize>)> = expected
            .iter()
            .map(|&(name, _)| (name, bounds.get(name).copied().flatten()))
            .collect();
        assert_eq!(actual, expected);
    }
}