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
use std::collections::HashMap;
use brink_ir::FileId;
/// Tracks `INCLUDE` relationships between files.
pub(crate) struct IncludeGraph {
/// file → files it includes
forward: HashMap<FileId, Vec<FileId>>,
/// file → files that include it
reverse: HashMap<FileId, Vec<FileId>>,
}
impl IncludeGraph {
/// Files that `file` includes.
pub fn includes(&self, file: FileId) -> &[FileId] {
self.forward.get(&file).map_or(&[], Vec::as_slice)
}
/// All files reachable from `entry` via forward `INCLUDE` edges
/// (transitive), `entry` included. Returned as a [`BTreeSet`] so iteration
/// is deterministic regardless of internal graph storage.
pub fn reachable_from(&self, entry: FileId) -> std::collections::BTreeSet<FileId> {
let mut reachable = std::collections::BTreeSet::new();
let mut stack = vec![entry];
while let Some(node) = stack.pop() {
if !reachable.insert(node) {
continue;
}
for &child in self.includes(node) {
if !reachable.contains(&child) {
stack.push(child);
}
}
}
reachable
}
}
#[expect(dead_code, reason = "graph queries used by LSP")]
impl IncludeGraph {
pub fn new() -> Self {
Self {
forward: HashMap::new(),
reverse: HashMap::new(),
}
}
/// Replace the include set for `file`. Removes old edges and inserts new ones.
pub fn update(&mut self, file: FileId, includes: Vec<FileId>) {
// Remove old reverse edges
if let Some(old_includes) = self.forward.remove(&file) {
for target in &old_includes {
if let Some(rev) = self.reverse.get_mut(target) {
rev.retain(|&f| f != file);
}
}
}
// Insert new reverse edges
for &target in &includes {
self.reverse.entry(target).or_default().push(file);
}
self.forward.insert(file, includes);
}
/// Files that include `file`.
pub fn included_by(&self, file: FileId) -> &[FileId] {
self.reverse.get(&file).map_or(&[], Vec::as_slice)
}
/// Detect cycles in the include graph. Returns the first cycle found
/// as an ordered path of file IDs (the last includes the first).
pub fn find_cycle(&self) -> Option<Vec<FileId>> {
use std::collections::HashSet;
let mut visited = HashSet::new();
let mut on_stack = HashSet::new();
for &start in self.forward.keys() {
if visited.contains(&start) {
continue;
}
// DFS with explicit stack: (node, iter_index)
let mut stack: Vec<(FileId, usize)> = vec![(start, 0)];
let mut path: Vec<FileId> = vec![start];
on_stack.insert(start);
while let Some((node, idx)) = stack.last_mut() {
let children = self.includes(*node);
if *idx < children.len() {
let child = children[*idx];
*idx += 1;
if on_stack.contains(&child) {
// Found a cycle — extract from child back to child
let cycle_start = path.iter().position(|&f| f == child);
if let Some(pos) = cycle_start {
let mut cycle: Vec<_> = path[pos..].to_vec();
cycle.push(child);
return Some(cycle);
}
} else if !visited.contains(&child) {
on_stack.insert(child);
path.push(child);
stack.push((child, 0));
}
} else {
let finished = *node;
on_stack.remove(&finished);
visited.insert(finished);
path.pop();
stack.pop();
}
}
}
None
}
/// Return all file IDs reachable from `entry` in topological order
/// (included files before the files that include them).
///
/// Uses a post-order DFS: children (includes) are visited before their
/// parent, giving the correct "paste-before" order for ink `INCLUDE`.
pub fn topological_order(&self, entry: FileId, all_ids: &[FileId]) -> Vec<FileId> {
use std::collections::HashSet;
fn dfs(
node: FileId,
graph: &IncludeGraph,
visited: &mut HashSet<FileId>,
order: &mut Vec<FileId>,
) {
if !visited.insert(node) {
return;
}
for &child in graph.includes(node) {
dfs(child, graph, visited, order);
}
order.push(node);
}
let mut visited = HashSet::new();
let mut order = Vec::new();
dfs(entry, self, &mut visited, &mut order);
// Include any remaining files not reachable from entry
// (shouldn't happen in practice, but be safe).
let mut all_sorted: Vec<_> = all_ids.to_vec();
all_sorted.sort_by_key(|id| id.0);
for &id in &all_sorted {
if visited.insert(id) {
order.push(id);
}
}
order
}
/// Discover independent projects from include relationships.
///
/// A "project" is a root `.ink` file plus everything it transitively INCLUDEs.
/// Roots are files in `all_ids` that are not included by any other file.
/// Returns `(root, members)` pairs sorted by root `FileId`.
pub fn compute_projects(&self, all_ids: &[FileId]) -> Vec<(FileId, Vec<FileId>)> {
use std::collections::HashSet;
let all_set: HashSet<FileId> = all_ids.iter().copied().collect();
// Roots: files not included by any other file in the set
let mut roots: Vec<FileId> = all_ids
.iter()
.copied()
.filter(|&id| {
self.included_by(id)
.iter()
.all(|parent| !all_set.contains(parent))
})
.collect();
roots.sort_by_key(|id| id.0);
// For each root, DFS forward to collect members
let mut claimed: HashSet<FileId> = HashSet::new();
let mut projects: Vec<(FileId, Vec<FileId>)> = Vec::new();
for &root in &roots {
let mut members = Vec::new();
let mut stack = vec![root];
let mut visited = HashSet::new();
while let Some(node) = stack.pop() {
if !visited.insert(node) || !all_set.contains(&node) {
continue;
}
members.push(node);
claimed.insert(node);
for &child in self.includes(node) {
stack.push(child);
}
}
members.sort_by_key(|id| id.0);
projects.push((root, members));
}
// Any files not claimed by a root become single-file projects
let mut orphans: Vec<FileId> = all_ids
.iter()
.copied()
.filter(|id| !claimed.contains(id))
.collect();
orphans.sort_by_key(|id| id.0);
for orphan in orphans {
projects.push((orphan, vec![orphan]));
}
projects.sort_by_key(|(root, _)| root.0);
projects
}
/// Return root file IDs (files not included by any other file in `all_ids`).
pub fn roots(&self, all_ids: &[FileId]) -> Vec<FileId> {
use std::collections::HashSet;
let all_set: HashSet<FileId> = all_ids.iter().copied().collect();
let mut roots: Vec<FileId> = all_ids
.iter()
.copied()
.filter(|&id| {
self.included_by(id)
.iter()
.all(|parent| !all_set.contains(parent))
})
.collect();
roots.sort_by_key(|id| id.0);
roots
}
/// Remove a file from the graph entirely.
pub fn remove(&mut self, file: FileId) {
// Remove forward edges and their reverse entries
if let Some(includes) = self.forward.remove(&file) {
for target in &includes {
if let Some(rev) = self.reverse.get_mut(target) {
rev.retain(|&f| f != file);
}
}
}
// Remove reverse edges pointing to this file
if let Some(included_by) = self.reverse.remove(&file) {
for source in &included_by {
if let Some(fwd) = self.forward.get_mut(source) {
fwd.retain(|&f| f != file);
}
}
}
}
}