wdl-analysis 0.19.1

Analysis of Workflow Description Language (WDL) documents.
Documentation
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Representation of the analysis document graph.

use std::collections::HashSet;
use std::fs;
use std::panic;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;

use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use indexmap::IndexMap;
use indexmap::IndexSet;
use line_index::LineIndex;
use petgraph::Direction;
use petgraph::algo::has_path_connecting;
use petgraph::graph::NodeIndex;
use petgraph::stable_graph::StableDiGraph;
use petgraph::visit::Bfs;
use petgraph::visit::EdgeRef;
use petgraph::visit::Visitable;
use petgraph::visit::Walker;
use reqwest::Client;
use rowan::GreenNode;
use tokio::runtime::Handle;
use tracing::debug;
use tracing::trace;
use url::Url;
use wdl_ast::AstNode;
use wdl_ast::AstToken as _;
use wdl_ast::Diagnostic;
use wdl_ast::SupportedVersion;
use wdl_ast::SyntaxNode;

use crate::Config;
use crate::IncrementalChange;
use crate::document::Document;
use crate::rules::USING_FALLBACK_VERSION;

/// Represents space for a DFS search of a document graph.
pub type DfsSpace =
    petgraph::algo::DfsSpace<NodeIndex, <StableDiGraph<DocumentGraphNode, ()> as Visitable>::Map>;

/// Represents the parse state of a document graph node.
#[derive(Debug, Clone)]
pub enum ParseState {
    /// The document is not parsed.
    NotParsed,
    /// There was an error parsing the document.
    Error(Arc<anyhow::Error>),
    /// The document was parsed.
    Parsed {
        /// The monotonic version of the document that was parsed.
        ///
        /// This value comes from incremental changes to the file.
        ///
        /// If `None`, the parsed version had no incremental changes.
        version: Option<i32>,
        /// The WDL version of the document.
        ///
        /// This usually comes from the `version` statement in the parsed
        /// document, but can be overridden by
        /// [`Config::with_fallback_version()`].
        wdl_version: Option<SupportedVersion>,
        /// The root CST node of.
        root: GreenNode,
        /// The line index of the document.
        lines: Arc<LineIndex>,
        /// The diagnostics from the parse.
        diagnostics: Vec<Diagnostic>,
    },
}

impl ParseState {
    /// Gets the version of parsed document.
    pub fn version(&self) -> Option<i32> {
        match self {
            ParseState::Parsed { version, .. } => *version,
            _ => None,
        }
    }

    /// Gets the line index of parsed document.
    pub fn lines(&self) -> Option<&Arc<LineIndex>> {
        match self {
            ParseState::Parsed { lines, .. } => Some(lines),
            _ => None,
        }
    }
}

/// Represents a node in a document graph.
#[derive(Debug)]
pub struct DocumentGraphNode {
    /// The analyzer configuration.
    config: Config,
    /// The URI of the document.
    uri: Arc<Url>,
    /// The current incremental change to the document.
    ///
    /// If `None`, there is no pending incremental change applied to the node.
    change: Option<IncrementalChange>,
    /// The parse state of the document.
    parse_state: ParseState,
    /// The analyzed document for the node.
    ///
    /// If `None`, an analysis does not exist for the current state of the node.
    /// This will also be `None` if analysis panicked
    document: Option<Document>,
    /// An error that occurred during the analysis phase for this node
    analysis_error: Option<Arc<anyhow::Error>>,
}

impl DocumentGraphNode {
    /// Constructs a new unparsed document graph node.
    pub fn new(config: Config, uri: Arc<Url>) -> Self {
        Self {
            config,
            uri,
            change: None,
            parse_state: ParseState::NotParsed,
            document: None,
            analysis_error: None,
        }
    }

    /// Gets the URI of the document node.
    pub fn uri(&self) -> &Arc<Url> {
        &self.uri
    }

    /// Notifies the document node that there's been an incremental change.
    pub fn notify_incremental_change(&mut self, change: IncrementalChange) {
        trace!("document `{uri}` has incrementally changed", uri = self.uri);

        // Clear the analyzed document as there has been a change
        self.document = None;

        // Attempt to merge the edits of the change
        if let Some(IncrementalChange {
            version: existing_version,
            start: existing_start,
            edits: existing_edits,
        }) = &mut self.change
        {
            let IncrementalChange {
                version,
                start,
                edits,
            } = change;
            *existing_version = version;
            if start.is_some() {
                *existing_start = start;
                *existing_edits = edits;
            } else {
                existing_edits.extend(edits);
            }
        } else {
            self.change = Some(change)
        }
    }

    /// Notifies the document node that the document has fully changed.
    pub fn notify_change(&mut self, discard_pending: bool) {
        trace!("document `{uri}` has changed", uri = self.uri);

        // Clear the analyzed document as there has been a change
        self.document = None;
        self.analysis_error = None;

        if !matches!(
            self.parse_state,
            ParseState::Parsed {
                version: Some(_),
                ..
            }
        ) || discard_pending
        {
            self.parse_state = ParseState::NotParsed;
            self.change = None;
        }
    }

    /// Gets the parse state of the document node.
    pub fn parse_state(&self) -> &ParseState {
        &self.parse_state
    }

    /// Marks the parse as completed.
    pub fn parse_completed(&mut self, state: ParseState) {
        assert!(!matches!(state, ParseState::NotParsed));
        self.parse_state = state;
        self.analysis_error = None;

        // Clear any document change
        self.change = None;
    }

    /// Gets the analyzed document for the node.
    ///
    /// Returns `None` if the document hasn't been analyzed.
    pub fn document(&self) -> Option<&Document> {
        self.document.as_ref()
    }

    /// Gets the analysis error, if any
    pub fn analysis_error(&self) -> Option<&Arc<anyhow::Error>> {
        self.analysis_error.as_ref()
    }

    /// Marks the analysis as completed.
    pub fn analysis_completed(&mut self, document: Document) {
        self.document = Some(document);
        self.analysis_error = None;
    }

    /// Marks the analysis as failed with an error
    pub fn analysis_failed(&mut self, error: Arc<anyhow::Error>) {
        self.document = None;
        self.analysis_error = Some(error);
    }

    /// Marks the document node for reanalysis.
    ///
    /// This may occur when a dependency has changed.
    pub fn reanalyze(&mut self) {
        self.analysis_error = None;
        self.document = None;
    }

    /// Gets the root AST node of the document.
    ///
    /// Returns `None` if the document was not parsed.
    pub fn root(&self) -> Option<wdl_ast::Document> {
        if let ParseState::Parsed { root, .. } = &self.parse_state {
            return Some(
                wdl_ast::Document::cast(SyntaxNode::new_root(root.clone()))
                    .expect("node should cast"),
            );
        }

        None
    }

    /// Gets the WDL version of the document.
    ///
    /// Returns `None` if the document was not parsed or was missing a version
    /// statement.
    pub fn wdl_version(&self) -> Option<SupportedVersion> {
        if let ParseState::Parsed {
            wdl_version: Some(v),
            ..
        } = &self.parse_state
        {
            Some(*v)
        } else {
            None
        }
    }

    /// Determines if the document needs to be parsed.
    pub fn needs_parse(&self) -> bool {
        self.change.is_some() || matches!(self.parse_state, ParseState::NotParsed)
    }

    /// Parses the document.
    ///
    /// If a parse is not necessary, the current parse state is returned.
    ///
    /// Otherwise, the new parse state is returned.
    pub fn parse(&self, tokio: &Handle, client: &Client) -> Result<ParseState> {
        if !self.needs_parse() {
            return Ok(self.parse_state.clone());
        }

        // First attempt an incremental parse
        if let Some(state) = self.incremental_parse() {
            return Ok(state);
        }

        // Otherwise, fall back to a full parse.
        self.full_parse(tokio, client)
    }

    /// Performs an incremental parse of the document.
    ///
    /// Returns an error with the given change if the document needs a full
    /// parse.
    fn incremental_parse(&self) -> Option<ParseState> {
        match &self.change {
            None | Some(IncrementalChange { start: Some(_), .. }) => None,
            Some(IncrementalChange { start: None, .. }) => {
                // TODO: implement incremental parsing
                // For each edit:
                //   * determine if the edit is to a token; if so, replace it in the tree
                //   * otherwise, find a reparsable ancestor for the covering element and ask it
                //     to reparse; if one is found, reparse and replace the node
                //   * if a reparsable node can't be found, return an error to trigger a full
                //     reparse
                //   * incrementally update the parse diagnostics depending on the result
                None
            }
        }
    }

    /// Performs a full parse of the node.
    fn full_parse(&self, tokio: &Handle, client: &Client) -> Result<ParseState> {
        let (version, source, lines) = match &self.change {
            None => {
                // Fetch the source
                let result = match self.uri.to_file_path() {
                    Ok(path) => fs::read_to_string(path).map_err(Into::into),
                    Err(_) => match self.uri.scheme() {
                        "https" | "http" => Self::download_source(tokio, client, &self.uri),
                        scheme => Err(anyhow!("unsupported URI scheme `{scheme}`")),
                    },
                };

                match result {
                    Ok(source) => {
                        let lines = Arc::new(LineIndex::new(&source));
                        (None, source, lines)
                    }
                    Err(e) => return Ok(ParseState::Error(e.into())),
                }
            }
            Some(IncrementalChange {
                version,
                start,
                edits,
            }) => {
                // The document has been edited; if there is start source, apply the edits to it
                let (mut source, mut lines) = if let Some(start) = start {
                    let source = start.clone();
                    let lines = Arc::new(LineIndex::new(&source));
                    (source, lines)
                } else {
                    // Otherwise, apply the edits to the last parse
                    match &self.parse_state {
                        ParseState::Parsed { root, lines, .. } => (
                            SyntaxNode::new_root(root.clone()).text().to_string(),
                            lines.clone(),
                        ),
                        _ => panic!(
                            "cannot apply edits to a document that was not previously parsed"
                        ),
                    }
                };

                // We keep track of the last line we've processed so we only rebuild the line
                // index when there is a change that crosses a line
                let mut last_line = !0u32;
                for edit in edits {
                    let range = edit.range();
                    if last_line <= range.end.line {
                        // Only rebuild the line index if the edit has changed lines
                        lines = Arc::new(LineIndex::new(&source));
                    }

                    last_line = range.start.line;
                    edit.apply(&mut source, &lines)?;
                }

                if !edits.is_empty() {
                    // Rebuild the line index after all edits have been applied
                    lines = Arc::new(LineIndex::new(&source));
                }

                (Some(*version), source, lines)
            }
        };

        // Reparse from the source
        let start = Instant::now();
        let (document, mut diagnostics) = wdl_ast::Document::parse(&source);
        debug!(
            "parsing of `{uri}` completed in {elapsed:?}",
            uri = self.uri,
            elapsed = start.elapsed()
        );

        // Apply version fallback logic at this point, so that appropriate diagnostics
        // will prevent subsequent analysis from occurring on an unexpected
        // version
        let mut wdl_version = None;
        if let Some(version_token) = document.version_statement().map(|stmt| stmt.version()) {
            match (
                version_token.text().parse::<SupportedVersion>(),
                self.config.fallback_version(),
            ) {
                // The version in the document is supported, so there's no diagnostic to add
                (Ok(version), _) => {
                    wdl_version = Some(version);
                }
                // The version in the document is not supported, but fallback behavior is configured
                (Err(unrecognized), Some(fallback)) => {
                    if let Some(severity) = self.config.diagnostics_config().using_fallback_version
                    {
                        diagnostics.push(
                            Diagnostic::warning(format!(
                                "unsupported WDL version `{unrecognized}`; interpreting document \
                                 as version `{fallback}`"
                            ))
                            .with_rule(USING_FALLBACK_VERSION)
                            .with_severity(severity)
                            .with_label(
                                "this version of WDL is not supported",
                                version_token.span(),
                            ),
                        );
                    }
                    wdl_version = Some(fallback);
                }
                // Add an error diagnostic if the version is unsupported and don't overwrite
                // `wdl_version`
                (Err(unrecognized), None) => {
                    diagnostics.push(
                        Diagnostic::error(format!("unsupported WDL version `{unrecognized}`"))
                            .with_label(
                                "this version of WDL is not supported",
                                version_token.span(),
                            )
                            .with_fix(
                                "either use a supported WDL version or configure \
                                 `common.wdl.fallback_version` to set a fallback version",
                            ),
                    );
                }
            };
        }

        Ok(ParseState::Parsed {
            version,
            wdl_version,
            root: document.inner().green().into(),
            lines,
            diagnostics,
        })
    }

    /// Downloads the source of a `http` or `https` scheme URI.
    ///
    /// This makes a request on the provided tokio runtime to download the
    /// source.
    fn download_source(tokio: &Handle, client: &Client, uri: &Url) -> Result<String> {
        /// The timeout for downloading the source, in seconds.
        const TIMEOUT_IN_SECS: u64 = 30;

        debug!("downloading source from `{uri}`");

        tokio.block_on(async {
            let resp = client
                .get(uri.as_str())
                .timeout(Duration::from_secs(TIMEOUT_IN_SECS))
                .send()
                .await?;

            let code = resp.status();
            if !code.is_success() {
                bail!(
                    "server response for `{uri}` was {code} ({message})",
                    code = code.as_u16(),
                    message = code.canonical_reason().unwrap_or("unknown")
                );
            }

            resp.text()
                .await
                .with_context(|| format!("failed to read response body for `{uri}`"))
        })
    }
}

/// Represents a graph of WDL analyzed documents.
#[derive(Debug)]
pub struct DocumentGraph {
    /// The analyzer configuration.
    config: Config,
    /// The inner directional graph.
    ///
    /// Edges in the graph denote inverse dependency relationships (i.e. "is
    /// depended upon by").
    inner: StableDiGraph<DocumentGraphNode, ()>,
    /// Map from document URI to graph node index.
    indexes: IndexMap<Arc<Url>, NodeIndex>,
    /// The current set of rooted nodes in the graph.
    ///
    /// Rooted nodes are those that were explicitly added to the analyzer.
    ///
    /// A rooted node is one that will not be collected even if the node has no
    /// outgoing edges (i.e. is not depended upon by any other file).
    roots: IndexSet<NodeIndex>,
    /// Represents dependency edges that, if they were added to the document
    /// graph, would form a cycle.
    ///
    /// The first in the pair is the dependent node and the second is the
    /// depended node.
    ///
    /// This is used to break import cycles; when analyzing the document, if the
    /// import relationship exists in this set, a diagnostic will be added and
    /// the import otherwise ignored.
    cycles: HashSet<(NodeIndex, NodeIndex)>,
}

impl DocumentGraph {
    /// Make a new [`DocumentGraph`] with the given configuration.
    pub fn new(config: Config) -> Self {
        DocumentGraph {
            config,
            inner: StableDiGraph::new(),
            indexes: IndexMap::new(),
            roots: IndexSet::new(),
            cycles: HashSet::new(),
        }
    }

    /// Add a node to the document graph.
    pub fn add_node(&mut self, uri: Url, rooted: bool) -> NodeIndex {
        let index = match self.indexes.get(&uri) {
            Some(index) => *index,
            _ => {
                debug!("inserting `{uri}` into the document graph");
                let uri = Arc::new(uri);
                let index = self
                    .inner
                    .add_node(DocumentGraphNode::new(self.config.clone(), uri.clone()));
                self.indexes.insert(uri, index);
                index
            }
        };

        if rooted {
            self.roots.insert(index);
        }

        index
    }

    /// Removes a root from the document graph.
    ///
    /// Note that this does not remove any nodes, only removes the document from
    /// the set of rooted nodes.
    ///
    /// If the node has no outgoing edges, it will be removed on the next
    /// garbage collection.
    pub fn remove_root(&mut self, uri: &Url) {
        let base = match uri.to_file_path() {
            Ok(base) => base,
            Err(_) => return,
        };

        // As the URI might be a directory containing WDL files, look for prefixed files
        let mut removed = Vec::new();
        for (uri, index) in &self.indexes {
            let path = match uri.to_file_path() {
                Ok(path) => path,
                Err(_) => continue,
            };

            if path.starts_with(&base) {
                removed.push(*index);
            }
        }

        for index in removed {
            let node = &mut self.inner[index];

            // We don't actually remove nodes from the graph, just remove it as a root.
            // If the node has no outgoing edges, it will be collected in the next GC.
            if !self.roots.swap_remove(&index) {
                debug!(
                    "document `{uri}` is no longer rooted in the graph",
                    uri = node.uri
                );
            }

            node.parse_state = ParseState::NotParsed;
            node.document = None;
            node.change = None;

            // Do a BFS traversal to trigger re-analysis in dependent documents
            self.bfs_mut(index, |graph, dependent: NodeIndex| {
                let node = graph.get_mut(dependent);
                trace!("document `{uri}` needs to be reanalyzed", uri = node.uri);
                node.document = None;
            });
        }
    }

    /// Determines if the given node is rooted.
    pub fn is_rooted(&self, index: NodeIndex) -> bool {
        self.roots.contains(&index)
    }

    /// Gets the rooted nodes in the graph.
    pub fn roots(&self) -> &IndexSet<NodeIndex> {
        &self.roots
    }

    /// Determines if the given document node should be included in analysis
    /// results.
    pub fn include_result(&self, index: NodeIndex) -> bool {
        // Only consider rooted or parsed nodes that have been analyzed
        let node = self.get(index);
        node.document().is_some()
            && (self.roots.contains(&index)
                || matches!(node.parse_state(), ParseState::Parsed { .. }))
    }

    /// Gets a node from the graph.
    pub fn get(&self, index: NodeIndex) -> &DocumentGraphNode {
        &self.inner[index]
    }

    /// Gets a mutable node from the graph.
    pub fn get_mut(&mut self, index: NodeIndex) -> &mut DocumentGraphNode {
        &mut self.inner[index]
    }

    /// Gets the node index for the given document URI.
    ///
    /// Returns `None` if the document is not in the graph.
    pub fn get_index(&self, uri: &Url) -> Option<NodeIndex> {
        self.indexes.get(uri).copied()
    }

    /// Performs a breadth-first traversal of the graph starting at the given
    /// node.
    ///
    /// Mutations to the document nodes are permitted.
    pub fn bfs_mut(&mut self, index: NodeIndex, mut cb: impl FnMut(&mut Self, NodeIndex)) {
        let mut bfs = Bfs::new(&self.inner, index);
        while let Some(node) = bfs.next(&self.inner) {
            cb(self, node);
        }
    }

    /// Gets the direct dependencies of a node.
    pub fn dependencies(&self, index: NodeIndex) -> impl Iterator<Item = NodeIndex> + '_ {
        self.inner
            .edges_directed(index, Direction::Incoming)
            .map(|e| e.source())
    }

    /// Removes all dependency edges from the given node.
    pub fn remove_dependency_edges(&mut self, index: NodeIndex) {
        // Retain all edges where the target isn't the given node (i.e. an incoming
        // edge)
        self.inner.retain_edges(|g, e| {
            let (_, target) = g.edge_endpoints(e).expect("edge should be valid");
            target != index
        });
    }

    /// Adds a dependency edge from one document to another.
    ///
    /// If a dependency edge already exists, this is a no-op.
    pub fn add_dependency_edge(&mut self, from: NodeIndex, to: NodeIndex, space: &mut DfsSpace) {
        // Check to see if there is already a path between the nodes; if so, there's a
        // cycle
        if has_path_connecting(&self.inner, from, to, Some(space)) {
            // Adding the edge would cause a cycle, so record the cycle instead
            debug!(
                "an import cycle was detected between `{from}` and `{to}`",
                from = self.inner[from].uri,
                to = self.inner[to].uri
            );
            self.cycles.insert((from, to));
        } else if !self.inner.contains_edge(to, from) {
            debug!(
                "adding dependency edge from `{from}` to `{to}`",
                from = self.inner[from].uri,
                to = self.inner[to].uri
            );

            // Note that we store inverse dependency edges in the graph, so the relationship
            // is reversed
            self.inner.add_edge(to, from, ());
        }
    }

    /// Determines if there is a cycle between the given nodes.
    pub fn contains_cycle(&self, from: NodeIndex, to: NodeIndex) -> bool {
        self.cycles.contains(&(from, to))
    }

    /// Creates a subgraph of this graph for the given nodes to include.
    pub fn subgraph(&self, nodes: &IndexSet<NodeIndex>) -> StableDiGraph<NodeIndex, ()> {
        self.inner
            .filter_map(|i, _| nodes.contains(&i).then_some(i), |_, _| Some(()))
    }

    /// Performs a garbage collection on the graph.
    ///
    /// This removes any non-rooted nodes that have no outgoing edges (i.e. are
    /// not depended upon by another document).
    pub fn gc(&mut self) {
        let mut collected = HashSet::new();
        for node in self.inner.node_indices() {
            if self.roots.contains(&node) {
                continue;
            }

            if self
                .inner
                .edges_directed(node, Direction::Outgoing)
                .next()
                .is_none()
            {
                debug!(
                    "removing document `{uri}` from the graph",
                    uri = self.inner[node].uri
                );
                collected.insert(node);
            }
        }

        if collected.is_empty() {
            return;
        }

        for node in &collected {
            self.inner.remove_node(*node);
        }

        self.indexes.retain(|_, index| !collected.contains(index));

        self.cycles
            .retain(|(from, to)| !collected.contains(from) && !collected.contains(to));
    }

    /// Gets all nodes that have a dependency on the given node.
    pub fn transitive_dependents(
        &self,
        index: petgraph::graph::NodeIndex,
    ) -> impl Iterator<Item = NodeIndex> {
        Bfs::new(&self.inner, index).iter(&self.inner)
    }

    /// Gets the inner stable dependency graph.
    pub(crate) fn inner(&self) -> &StableDiGraph<DocumentGraphNode, ()> {
        &self.inner
    }
}