Skip to main content

mortise_core/boundary/
links.rs

1//! Which module uses which: links between modules, worked out from the classes
2//! their PHP files name, and the circles among them.
3
4use std::collections::{BTreeMap, BTreeSet};
5
6use serde::{Deserialize, Serialize};
7
8use crate::boundary::rules::Rules;
9use crate::php::ClassRef;
10use crate::surface::AcceptedSurface;
11
12/// One file of a module that names one class of another module.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct Reference {
15    /// The file, as the user writes it: `Modules/Checkout/app/Services/InvoiceSync.php`.
16    pub file: String,
17    /// The first line of the file that names the class.
18    pub line: u32,
19    /// The class that is named: `Modules\Billing\Models\Invoice`.
20    pub class: String,
21    /// True when reading the class breaks the rule public surface only: the class is
22    /// not part of the public surface of its module, and both modules are on.
23    pub internal: bool,
24}
25
26/// One module uses another.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct Link {
29    /// The module that uses.
30    pub from: String,
31    /// The module that is used.
32    pub to: String,
33    /// What makes the link. References to internals first, then by file and line.
34    pub refs: Vec<Reference>,
35    /// True when the two modules are in one circle and every module of it is on.
36    pub circular: bool,
37    /// True when the link breaks the rule allowed use: the rule is on, both modules are
38    /// on, and `from` has a list that does not name `to`. Not in the push document,
39    /// which carries the finding.
40    #[serde(skip)]
41    pub outside_allowed: bool,
42}
43
44impl Link {
45    /// How many files of `from` make the link.
46    pub fn files(&self) -> usize {
47        self.refs
48            .iter()
49            .map(|reference| reference.file.as_str())
50            .collect::<BTreeSet<_>>()
51            .len()
52    }
53
54    /// How many files of `from` read internals of `to`.
55    pub fn internal_files(&self) -> usize {
56        self.refs
57            .iter()
58            .filter(|reference| reference.internal)
59            .map(|reference| reference.file.as_str())
60            .collect::<BTreeSet<_>>()
61            .len()
62    }
63
64    /// True when the link breaks a rule.
65    pub fn is_problem(&self, rules: &Rules) -> bool {
66        (rules.no_circular_use && self.circular)
67            || (rules.public_surface_only && self.internal_files() > 0)
68            || self.outside_allowed
69    }
70}
71
72/// Modules that are on and use each other, directly or through others.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74pub struct Cycle {
75    /// The modules of the circle, by name.
76    pub modules: Vec<String>,
77    /// The module the finding is counted on: the one with the fewest files in the
78    /// circle, because that is the cheaper side to cut.
79    pub carrier: String,
80    /// For each module of the circle, how many of its files use another module of it.
81    pub files: Vec<(String, usize)>,
82}
83
84/// The module of the circle of `module` that `module` uses directly. Every member of a
85/// circle uses another member, so no module of a circle is left without one.
86pub(crate) fn circle_neighbour<'a>(links: &'a [Link], module: &str) -> Option<&'a str> {
87    links
88        .iter()
89        .find(|link| link.circular && link.from == module)
90        .map(|link| link.to.as_str())
91}
92
93/// The PHP files of one module, as the links need them.
94pub(crate) struct ModuleSource<'a> {
95    pub(crate) name: &'a str,
96    /// False when the module is off. Its links then break no rule.
97    pub(crate) on: bool,
98    /// The namespace all classes of the module share: `Modules\Billing`.
99    pub(crate) namespace: &'a str,
100    /// The accepted public surface. Without one, the folder list of the rules counts.
101    pub(crate) surface: Option<&'a AcceptedSurface>,
102    /// Each file as the user writes it, with the classes it names. Test files
103    /// are left out: they make no links.
104    pub(crate) files: Vec<(String, &'a [ClassRef])>,
105    /// The classes, interfaces, traits and enums the module declares.
106    pub(crate) declared: BTreeSet<&'a str>,
107}
108
109/// Finds the links between modules and the circles among them.
110pub(crate) fn build(modules: &[ModuleSource<'_>], rules: &Rules) -> (Vec<Link>, Vec<Cycle>) {
111    // Longest namespace first, so that `Modules\Billing\Tax` wins over `Modules\Billing`.
112    let mut owners: Vec<&ModuleSource<'_>> = modules
113        .iter()
114        .filter(|module| !module.namespace.is_empty())
115        .collect();
116    owners.sort_by_key(|module| std::cmp::Reverse(module.namespace.len()));
117    let owner_of = |class: &str| -> Option<(&ModuleSource<'_>, String)> {
118        owners.iter().find_map(|module| {
119            let inside = class.strip_prefix(module.namespace)?.strip_prefix('\\')?;
120            Some((*module, inside.to_owned()))
121        })
122    };
123
124    let mut found: BTreeMap<(String, String), Vec<Reference>> = BTreeMap::new();
125    for module in modules {
126        for (file, refs) in &module.files {
127            for named in *refs {
128                let Some((owner, inside)) = owner_of(&named.class) else {
129                    continue;
130                };
131                // A module using itself is not a link.
132                if owner.name == module.name || inside.is_empty() {
133                    continue;
134                }
135                // `use Modules\Billing\Contracts;` names a namespace, not a class:
136                // nothing is declared under that name, but classes are declared inside it.
137                let as_namespace = format!("{}\\", named.class);
138                if !owner.declared.contains(named.class.as_str())
139                    && owner
140                        .declared
141                        .iter()
142                        .any(|declared| declared.starts_with(&as_namespace))
143                {
144                    continue;
145                }
146                found
147                    .entry((module.name.to_owned(), owner.name.to_owned()))
148                    .or_default()
149                    .push(Reference {
150                        file: file.clone(),
151                        line: named.line,
152                        class: named.class.clone(),
153                        internal: rules.public_surface_only
154                            && module.on
155                            && owner.on
156                            && !match owner.surface {
157                                Some(surface) => surface.has_class(&named.class),
158                                None => rules.is_public(&inside),
159                            },
160                    });
161            }
162        }
163    }
164
165    let edges: BTreeSet<(&str, &str)> = found
166        .keys()
167        .map(|(from, to)| (from.as_str(), to.as_str()))
168        .collect();
169    let names: Vec<&str> = modules.iter().map(|module| module.name).collect();
170    let is_on = |name: &str| {
171        modules
172            .iter()
173            .any(|module| module.name == name && module.on)
174    };
175    // A module that is off does not run, so the circles are found among the modules
176    // that are on. Owned, so that the links can be taken out of `found` below.
177    let running: BTreeSet<(&str, &str)> = edges
178        .iter()
179        .copied()
180        .filter(|(from, to)| is_on(from) && is_on(to))
181        .collect();
182    let circles: Vec<Vec<String>> = circles(&names, &running)
183        .into_iter()
184        .map(|circle| circle.into_iter().map(str::to_owned).collect())
185        .collect();
186    let circle_of = |name: &str| {
187        circles
188            .iter()
189            .position(|circle| circle.iter().any(|member| member == name))
190    };
191
192    let cycles = circles
193        .iter()
194        .map(|circle| {
195            let mut files: Vec<(String, usize)> = circle
196                .iter()
197                .map(|member| {
198                    let own: BTreeSet<&str> = found
199                        .iter()
200                        .filter(|((from, to), _)| from == member && circle.contains(to))
201                        .flat_map(|(_, refs)| refs.iter().map(|reference| reference.file.as_str()))
202                        .collect();
203                    (member.clone(), own.len())
204                })
205                .collect();
206            files.sort();
207            let carrier = files
208                .iter()
209                .min_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)))
210                .map(|(name, _)| name.clone())
211                .unwrap_or_default();
212            Cycle {
213                modules: files.iter().map(|(name, _)| name.clone()).collect(),
214                carrier,
215                files,
216            }
217        })
218        .collect();
219
220    let links = found
221        .into_iter()
222        .map(|((from, to), mut refs)| {
223            refs.sort_by(|a, b| {
224                b.internal
225                    .cmp(&a.internal)
226                    .then_with(|| a.file.cmp(&b.file))
227                    .then_with(|| a.line.cmp(&b.line))
228            });
229            let circular = circle_of(&from).is_some() && circle_of(&from) == circle_of(&to);
230            // A module that is off breaks no rule, and no link to it does.
231            let outside_allowed = rules
232                .allowed_use
233                .as_ref()
234                .is_some_and(|allowed| allowed.enabled && !allowed.allows(&from, &to))
235                && is_on(&from)
236                && is_on(&to);
237            Link {
238                from,
239                to,
240                refs,
241                circular,
242                outside_allowed,
243            }
244        })
245        .collect();
246    (links, cycles)
247}
248
249/// The groups of modules that can reach each other along the links, with two or
250/// more members each. Tarjan's algorithm, without recursion.
251fn circles<'a>(names: &[&'a str], edges: &BTreeSet<(&'a str, &'a str)>) -> Vec<Vec<&'a str>> {
252    let index_of: BTreeMap<&str, usize> = names
253        .iter()
254        .enumerate()
255        .map(|(i, name)| (*name, i))
256        .collect();
257    let mut next: Vec<Vec<usize>> = vec![Vec::new(); names.len()];
258    for (from, to) in edges {
259        if let (Some(&from), Some(&to)) = (index_of.get(from), index_of.get(to)) {
260            next[from].push(to);
261        }
262    }
263
264    const UNSEEN: usize = usize::MAX;
265    let mut order = vec![UNSEEN; names.len()];
266    let mut low = vec![0; names.len()];
267    let mut on_stack = vec![false; names.len()];
268    let mut stack: Vec<usize> = Vec::new();
269    let mut counter = 0;
270    let mut groups: Vec<Vec<&str>> = Vec::new();
271
272    for start in 0..names.len() {
273        if order[start] != UNSEEN {
274            continue;
275        }
276        // Each entry: a module and how many of its links were followed.
277        let mut work = vec![(start, 0)];
278        while let Some(&mut (node, ref mut followed)) = work.last_mut() {
279            if *followed == 0 {
280                order[node] = counter;
281                low[node] = counter;
282                counter += 1;
283                stack.push(node);
284                on_stack[node] = true;
285            }
286            if let Some(&target) = next[node].get(*followed) {
287                *followed += 1;
288                if order[target] == UNSEEN {
289                    work.push((target, 0));
290                } else if on_stack[target] {
291                    low[node] = low[node].min(order[target]);
292                }
293                continue;
294            }
295            work.pop();
296            if let Some(&(parent, _)) = work.last() {
297                low[parent] = low[parent].min(low[node]);
298            }
299            if low[node] == order[node] {
300                let mut group = Vec::new();
301                while let Some(member) = stack.pop() {
302                    on_stack[member] = false;
303                    group.push(names[member]);
304                    if member == node {
305                        break;
306                    }
307                }
308                if group.len() > 1 {
309                    group.sort_unstable();
310                    groups.push(group);
311                }
312            }
313        }
314    }
315    groups.sort();
316    groups
317}
318
319/// Places modules in columns from left to right: a module sits to the left of what
320/// it uses, and the modules of a circle share a column. A circle through a module
321/// that is off counts here too.
322pub fn columns(names: &[&str], links: &[Link]) -> Vec<Vec<String>> {
323    let edges: BTreeSet<(&str, &str)> = links
324        .iter()
325        .map(|link| (link.from.as_str(), link.to.as_str()))
326        .collect();
327    let circles = circles(names, &edges);
328    // A circle counts as one node.
329    let group = |name: &str| -> String {
330        circles
331            .iter()
332            .find(|circle| circle.contains(&name))
333            .map_or_else(|| name.to_owned(), |circle| circle[0].to_owned())
334    };
335    let mut users: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
336    for link in links {
337        let (from, to) = (group(&link.from), group(&link.to));
338        if from != to {
339            users.entry(to).or_default().insert(from);
340        }
341    }
342
343    // The column of a node: one more than the furthest right of the nodes that use it.
344    fn column(
345        node: &str,
346        users: &BTreeMap<String, BTreeSet<String>>,
347        known: &mut BTreeMap<String, usize>,
348    ) -> usize {
349        if let Some(&column) = known.get(node) {
350            return column;
351        }
352        // Circles are one node, so this cannot loop; the placeholder guards against bad input.
353        known.insert(node.to_owned(), 0);
354        let column = users.get(node).map_or(0, |users_of| {
355            users_of
356                .iter()
357                .map(|user| column(user, users, known) + 1)
358                .max()
359                .unwrap_or(0)
360        });
361        known.insert(node.to_owned(), column);
362        column
363    }
364
365    let mut known = BTreeMap::new();
366    let mut columns: Vec<Vec<String>> = Vec::new();
367    for name in names {
368        let at = column(&group(name), &users, &mut known);
369        if columns.len() <= at {
370            columns.resize(at + 1, Vec::new());
371        }
372        columns[at].push((*name).to_owned());
373    }
374    columns
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    fn named(class: &str, line: u32) -> ClassRef {
382        ClassRef {
383            class: class.to_owned(),
384            line,
385        }
386    }
387
388    fn source<'a>(
389        name: &'a str,
390        namespace: &'a str,
391        files: &'a [(&'a str, Vec<ClassRef>)],
392    ) -> ModuleSource<'a> {
393        ModuleSource {
394            name,
395            on: true,
396            namespace,
397            surface: None,
398            files: files
399                .iter()
400                .map(|(file, refs)| ((*file).to_owned(), refs.as_slice()))
401                .collect(),
402            declared: BTreeSet::new(),
403        }
404    }
405
406    #[test]
407    fn a_link_is_made_of_files_that_name_classes_of_another_module() {
408        let checkout = [
409            (
410                "Modules/Checkout/app/A.php",
411                vec![
412                    named(r"Modules\Billing\Models\Invoice", 5),
413                    named(r"Modules\Checkout\Models\Order", 6),
414                ],
415            ),
416            (
417                "Modules/Checkout/app/B.php",
418                vec![
419                    named(r"Modules\Billing\Contracts\Gateway", 7),
420                    named(r"Illuminate\Support\Str", 3),
421                ],
422            ),
423            (
424                "Modules/Checkout/app/C.php",
425                vec![
426                    named(r"Modules\Billing\Contracts", 4),
427                    named(r"Modules\BillingExtras\Thing", 4),
428                ],
429            ),
430        ];
431        let mut billing = source("Billing", r"Modules\Billing", &[]);
432        billing.declared = BTreeSet::from([
433            r"Modules\Billing\Contracts\Gateway",
434            r"Modules\Billing\Models\Invoice",
435        ]);
436        let modules = [source("Checkout", r"Modules\Checkout", &checkout), billing];
437        let (links, cycles) = build(&modules, &Rules::default());
438
439        assert_eq!(links.len(), 1);
440        let link = &links[0];
441        assert_eq!(
442            (link.from.as_str(), link.to.as_str()),
443            ("Checkout", "Billing")
444        );
445        assert!(!link.circular);
446        // The internal one first.
447        let refs: Vec<_> = link
448            .refs
449            .iter()
450            .map(|r| (r.file.as_str(), r.line, r.class.as_str(), r.internal))
451            .collect();
452        assert_eq!(
453            refs,
454            [
455                (
456                    "Modules/Checkout/app/A.php",
457                    5,
458                    r"Modules\Billing\Models\Invoice",
459                    true
460                ),
461                (
462                    "Modules/Checkout/app/B.php",
463                    7,
464                    r"Modules\Billing\Contracts\Gateway",
465                    false
466                ),
467            ]
468        );
469        assert_eq!((link.files(), link.internal_files()), (2, 1));
470        assert!(link.is_problem(&Rules::default()));
471        assert!(cycles.is_empty());
472    }
473
474    #[test]
475    fn an_accepted_surface_takes_the_place_of_the_folder_list() {
476        let checkout = [(
477            "a.php",
478            vec![
479                named(r"Modules\Billing\Models\Invoice", 5),
480                named(r"Modules\Billing\Contracts\Gateway", 6),
481            ],
482        )];
483        // Classes match in any case, as PHP names do.
484        let surface = AcceptedSurface {
485            classes: vec![r"Modules\Billing\models\invoice".to_owned()],
486            ..AcceptedSurface::default()
487        };
488        let mut billing = source("Billing", r"Modules\Billing", &[]);
489        billing.surface = Some(&surface);
490        let modules = [source("Checkout", r"Modules\Checkout", &checkout), billing];
491        let (links, _) = build(&modules, &Rules::default());
492        let internal: Vec<(&str, bool)> = links[0]
493            .refs
494            .iter()
495            .map(|r| (r.class.as_str(), r.internal))
496            .collect();
497        assert_eq!(
498            internal,
499            [
500                (r"Modules\Billing\Contracts\Gateway", true),
501                (r"Modules\Billing\Models\Invoice", false),
502            ]
503        );
504    }
505
506    #[test]
507    fn without_the_rule_nothing_is_internal() {
508        let checkout = [("a.php", vec![named(r"Modules\Billing\Models\Invoice", 5)])];
509        let modules = [
510            source("Checkout", r"Modules\Checkout", &checkout),
511            source("Billing", r"Modules\Billing", &[]),
512        ];
513        let rules = Rules {
514            public_surface_only: false,
515            ..Rules::default()
516        };
517        let (links, _) = build(&modules, &rules);
518        assert!(!links[0].refs[0].internal);
519        assert!(!links[0].is_problem(&rules));
520    }
521
522    #[test]
523    fn two_modules_that_use_each_other_are_a_circle_counted_on_the_smaller_side() {
524        let checkout = [
525            (
526                "c1.php",
527                vec![named(r"Modules\Shipping\Contracts\Rates", 7)],
528            ),
529            (
530                "c2.php",
531                vec![named(r"Modules\Shipping\Contracts\Requester", 6)],
532            ),
533        ];
534        let shipping = [
535            (
536                "s1.php",
537                vec![named(r"Modules\Checkout\Events\OrderPaid", 8)],
538            ),
539            (
540                "s2.php",
541                vec![named(r"Modules\Checkout\Contracts\Lookup", 10)],
542            ),
543            (
544                "s3.php",
545                vec![named(r"Modules\Checkout\Contracts\Lookup", 9)],
546            ),
547            (
548                "s4.php",
549                vec![named(r"Modules\Checkout\Events\OrderShipped", 11)],
550            ),
551        ];
552        let modules = [
553            source("Checkout", r"Modules\Checkout", &checkout),
554            source("Shipping", r"Modules\Shipping", &shipping),
555            source("Users", r"Modules\Users", &[]),
556        ];
557        let (links, cycles) = build(&modules, &Rules::default());
558        assert!(
559            links
560                .iter()
561                .all(|link| link.circular && link.is_problem(&Rules::default()))
562        );
563        assert_eq!(
564            cycles,
565            [Cycle {
566                modules: vec!["Checkout".into(), "Shipping".into()],
567                carrier: "Checkout".into(),
568                files: vec![("Checkout".into(), 2), ("Shipping".into(), 4)],
569            }]
570        );
571        // With the rule off, a circle is not a problem, but it is still known.
572        let rules = Rules {
573            no_circular_use: false,
574            ..Rules::default()
575        };
576        assert!(
577            links
578                .iter()
579                .all(|link| link.circular && !link.is_problem(&rules))
580        );
581    }
582
583    #[test]
584    fn a_circle_through_three_modules_is_found() {
585        let a = [("a.php", vec![named(r"M\B\Contracts\X", 1)])];
586        let b = [("b.php", vec![named(r"M\C\Contracts\X", 1)])];
587        let c = [
588            ("c.php", vec![named(r"M\A\Contracts\X", 1)]),
589            ("c2.php", vec![named(r"M\D\Contracts\X", 1)]),
590        ];
591        let modules = [
592            source("A", r"M\A", &a),
593            source("B", r"M\B", &b),
594            source("C", r"M\C", &c),
595            source("D", r"M\D", &[]),
596        ];
597        let (links, cycles) = build(&modules, &Rules::default());
598        assert_eq!(cycles.len(), 1);
599        assert_eq!(cycles[0].modules, ["A", "B", "C"]);
600        assert_eq!(cycles[0].carrier, "A");
601        let to_d = links.iter().find(|link| link.to == "D").unwrap();
602        assert!(!to_d.circular);
603        // B is shown with the member it uses, not the first other member by name.
604        assert_eq!(circle_neighbour(&links, "B"), Some("C"));
605        assert_eq!(circle_neighbour(&links, "D"), None);
606
607        // With C off the circle does not run: A and B are on, but their link is not circular.
608        let mut modules = modules;
609        modules[2].on = false;
610        let (links, cycles) = build(&modules, &Rules::default());
611        assert!(cycles.is_empty());
612        assert!(links.iter().all(|link| !link.circular));
613
614        // A and B use each other, B and C too, and C is off: A and B still make a circle.
615        let a = [("a.php", vec![named(r"M\B\Contracts\X", 1)])];
616        let b = [
617            ("b.php", vec![named(r"M\A\Contracts\X", 1)]),
618            ("b2.php", vec![named(r"M\C\Contracts\X", 1)]),
619        ];
620        let c = [("c.php", vec![named(r"M\B\Contracts\X", 1)])];
621        let mut modules = [
622            source("A", r"M\A", &a),
623            source("B", r"M\B", &b),
624            source("C", r"M\C", &c),
625        ];
626        modules[2].on = false;
627        let (links, cycles) = build(&modules, &Rules::default());
628        assert_eq!(cycles.len(), 1);
629        assert_eq!(cycles[0].modules, ["A", "B"]);
630        let circular: Vec<_> = links
631            .iter()
632            .map(|link| (link.from.as_str(), link.to.as_str(), link.circular))
633            .collect();
634        assert_eq!(
635            circular,
636            [
637                ("A", "B", true),
638                ("B", "A", true),
639                ("B", "C", false),
640                ("C", "B", false)
641            ]
642        );
643    }
644
645    #[test]
646    fn a_module_sits_left_of_what_it_uses_and_a_circle_shares_a_column() {
647        // The layout finds the circles itself: `circular` is not read.
648        let link = |from: &str, to: &str| Link {
649            from: from.into(),
650            to: to.into(),
651            refs: Vec::new(),
652            circular: false,
653            outside_allowed: false,
654        };
655        let links = [
656            link("Notifications", "Checkout"),
657            link("Checkout", "Shipping"),
658            link("Shipping", "Checkout"),
659            link("Checkout", "Billing"),
660            link("Billing", "Users"),
661            link("Inventory", "Catalog"),
662            link("Checkout", "Catalog"),
663        ];
664        let names = [
665            "Billing",
666            "Catalog",
667            "Checkout",
668            "Inventory",
669            "Notifications",
670            "Shipping",
671            "Users",
672            "Alone",
673        ];
674        assert_eq!(
675            columns(&names, &links),
676            [
677                vec!["Inventory", "Notifications", "Alone"],
678                vec!["Checkout", "Shipping"],
679                vec!["Billing", "Catalog"],
680                vec!["Users"],
681            ]
682        );
683    }
684}