fallow_types/results_cycles.rs
1//! Import and package cycle findings.
2
3use std::path::PathBuf;
4
5use serde::{Deserialize, Serialize};
6
7use crate::serde_path;
8
9/// One import hop in a circular dependency: the file containing the import
10/// and where that import statement sits.
11///
12/// `edges[i]` is the import in `path` (the hop source, equal to the cycle's
13/// `files[i]`) that points to the next file in the cycle
14/// (`files[(i + 1) % files.len()]`); the target is not repeated here to keep
15/// the wire compact. Enables a per-file diagnostic squiggly anchored under
16/// the offending import rather than a single squiggly on the first file.
17///
18/// `col` is a 0-based byte column, matching the cycle's top-level `col`;
19/// converting it to a UTF-16 code-unit column for LSP clients is a tracked
20/// follow-up shared with the existing field.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
23pub struct CircularDependencyEdge {
24 /// The file containing the import (the hop source; equal to `files[i]`).
25 #[serde(serialize_with = "serde_path::serialize")]
26 pub path: PathBuf,
27 /// 1-based line number of the import statement pointing to the next file.
28 pub line: u32,
29 /// 0-based byte column offset of the import statement.
30 pub col: u32,
31}
32
33/// A circular dependency chain detected in the module graph.
34///
35/// The `line` and `col` fields carry `#[serde(default)]` so callers reading
36/// historical baseline JSON without these fields can still deserialize the
37/// struct, but the JSON output layer always emits them (u32 always
38/// serializes, never via `skip_serializing_if`). The schemars derive sees
39/// the serde defaults and marks both fields optional in the generated
40/// schema; the explicit `extend("required" = ...)` override here keeps the
41/// schema's `required` array honest about what the JSON output actually
42/// contains.
43///
44/// `edges` is deliberately kept OUT of the `required` extend: it is
45/// `#[serde(default)]` (so historical baseline JSON without it still
46/// deserializes) and the output layer always emits it, but listing it in
47/// `required` would make pre-upgrade JSON fail validation against the new
48/// schema. It is a normal additive field: always present in current output,
49/// optional for backward compatibility.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
52#[cfg_attr(feature = "schema", schemars(extend("required" = ["files", "length", "line", "col"])))]
53pub struct CircularDependency {
54 /// Files forming the cycle, in import order.
55 #[serde(serialize_with = "serde_path::serialize_vec")]
56 pub files: Vec<PathBuf>,
57 /// Number of files in the cycle.
58 pub length: usize,
59 /// 1-based line number of the import that starts the cycle (in the first file).
60 #[serde(default)]
61 pub line: u32,
62 /// 0-based byte column offset of the import that starts the cycle.
63 #[serde(default)]
64 pub col: u32,
65 /// Per-file import anchors, one entry per hop in cycle order: `edges[i]`
66 /// is the import in `files[i]` pointing to `files[(i + 1) % len]`. Always
67 /// the same length as `files`. Drives the per-file LSP diagnostic
68 /// squiggly. `#[serde(default)]` so pre-`edges` baselines deserialize;
69 /// always emitted on output but intentionally not in the schema's
70 /// `required` set (see the struct doc).
71 #[serde(default)]
72 pub edges: Vec<CircularDependencyEdge>,
73 /// Whether this cycle crosses workspace package boundaries.
74 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
75 pub is_cross_package: bool,
76}
77
78/// A cycle or self-loop in the re-export edge subgraph, found by a Tarjan SCC
79/// pass in `crates/graph/src/graph/re_exports/`. Chain propagation through the
80/// loop is a no-op, so a symbol re-exported through it does not resolve.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
83pub struct ReExportCycle {
84 /// Member files, sorted lexicographically. A self-loop has one entry.
85 #[serde(serialize_with = "serde_path::serialize_vec")]
86 pub files: Vec<PathBuf>,
87 /// Which structural shape this finding describes.
88 pub kind: ReExportCycleKind,
89 /// 1-based line of the re-export in `files[0]` that closes the cycle, or `0` if unknown.
90 #[serde(default)]
91 pub line: u32,
92 /// 0-based byte column of that re-export.
93 #[serde(default)]
94 pub col: u32,
95}
96
97/// Discriminator for [`ReExportCycle`]: which structural shape was detected.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
99#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
100#[serde(rename_all = "kebab-case")]
101pub enum ReExportCycleKind {
102 /// Two or more barrel files re-export from each other in a loop
103 /// (SCC of size >= 2).
104 MultiNode,
105 /// A single barrel file re-exports from itself.
106 SelfLoop,
107}
108
109/// One package hop in a [`PackageCycle`]: `from_package` imports
110/// `to_package`, and `path` holds one example import for that hop.
111///
112/// The example import is the first runtime import by `(path, line)`. When
113/// every import on the hop is type-only, it is the first type-only import.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
116pub struct PackageCycleEdge {
117 /// Label of the importing workspace package, as in
118 /// [`PackageCycle::packages`].
119 pub from_package: String,
120 /// Label of the imported workspace package, as in
121 /// [`PackageCycle::packages`].
122 pub to_package: String,
123 /// File in `from_package` that holds the example import.
124 #[serde(serialize_with = "serde_path::serialize")]
125 pub path: PathBuf,
126 /// File in `to_package` that the example import resolves to.
127 #[serde(serialize_with = "serde_path::serialize")]
128 pub target_path: PathBuf,
129 /// 1-based line number of the example import.
130 pub line: u32,
131 /// 0-based byte column offset of the example import.
132 pub col: u32,
133 /// True when every import from `from_package` to `to_package` is
134 /// type-only. A type-only hop has no runtime effect, but it can still
135 /// force a build order (for example with declaration builds).
136 pub type_only: bool,
137}
138
139/// A dependency cycle between workspace packages.
140///
141/// Each workspace package is a node. A resolved import from a file in one
142/// package to a file in another package is an edge. Declared `package.json`
143/// dependencies are not edges, and imports from test, spec, story, fixture
144/// and tooling config files are not edges. A package cycle can exist when no
145/// file-level cycle exists.
146#[derive(Debug, Clone, Serialize, Deserialize)]
147#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
148pub struct PackageCycle {
149 /// Workspace package labels in cycle order. The first entry is the
150 /// lexicographically smallest label; the last entry imports the first.
151 /// A label is the package name. When two or more workspace packages
152 /// share a name, the label is `name (root)` with the project-relative
153 /// package root, so that each label names one package.
154 pub packages: Vec<String>,
155 /// Package root directories in cycle order: `package_roots[i]` is the
156 /// root of `packages[i]`.
157 #[serde(serialize_with = "serde_path::serialize_vec")]
158 pub package_roots: Vec<PathBuf>,
159 /// Number of packages in the cycle.
160 pub length: usize,
161 /// One example import per hop, in cycle order: `edges[i]` goes from
162 /// `packages[i]` to `packages[(i + 1) % length]`.
163 pub edges: Vec<PackageCycleEdge>,
164 /// True when the group of packages that holds this cycle has more
165 /// cycles than fallow lists. The listing stops at 20 cycles per group,
166 /// or earlier on a very dense package graph. Break a listed cycle and
167 /// run again to see the rest.
168 pub group_truncated: bool,
169}
170
171impl PackageCycle {
172 /// The note that every output format shows for a cycle with
173 /// [`PackageCycle::group_truncated`] set.
174 pub const GROUP_TRUNCATED_NOTE: &'static str = "this package group has more cycles than listed";
175
176 /// The package labels in cycle order, with the first label repeated at
177 /// the end, joined with `separator`.
178 #[must_use]
179 pub fn chain(&self, separator: &str) -> String {
180 let mut chain: Vec<&str> = self.packages.iter().map(String::as_str).collect();
181 if let Some(first) = chain.first().copied() {
182 chain.push(first);
183 }
184 chain.join(separator)
185 }
186}