archunit/common/extraction/
dependency.rs

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
use std::slice;

use super::ImportKind;
use super::ignore_directive::DeclarationSpan;

/// The category of a non-fatal source extraction diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ExtractionDiagnosticKind {
    /// A source file could not be read.
    ReadFile,
    /// `syn` could not parse a source file.
    ParseFile,
    /// An outlined module declaration had no matching source file.
    MissingModule,
    /// Both supported outlined module layouts matched one declaration.
    AmbiguousModule,
    /// Following module declarations would revisit a file in the same module ancestry.
    ModuleCycle,
    /// A `#[path]` attribute was not a literal string.
    InvalidPathAttribute,
    /// A qualified path matched more than one viable internal or Cargo-visible target.
    AmbiguousReference,
    /// A path's first segment matched neither an internal module nor Cargo's external prelude.
    UnknownReference,
}

impl ExtractionDiagnosticKind {
    /// Returns the stable report spelling for this diagnostic category.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ReadFile => "read-file",
            Self::ParseFile => "parse-file",
            Self::MissingModule => "missing-module",
            Self::AmbiguousModule => "ambiguous-module",
            Self::ModuleCycle => "module-cycle",
            Self::InvalidPathAttribute => "invalid-path-attribute",
            Self::AmbiguousReference => "ambiguous-reference",
            Self::UnknownReference => "unknown-reference",
        }
    }
}

/// The classified destination of one extracted Rust dependency reference.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum DependencyTarget {
    /// A normalized workspace-relative Rust source file.
    Internal(String),
    /// A Cargo-visible crate name, including dependency renames.
    External(String),
}

impl DependencyTarget {
    /// Returns the internal file or external Cargo-visible crate name.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Internal(target) | Self::External(target) => target,
        }
    }

    /// Returns whether this target is outside the analyzed workspace.
    #[must_use]
    pub const fn is_external(&self) -> bool {
        matches!(self, Self::External(_))
    }
}

/// One non-fatal limitation encountered while extracting Rust dependencies.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct ExtractionDiagnostic {
    source: String,
    line: Option<usize>,
    kind: ExtractionDiagnosticKind,
    subject: Option<String>,
    candidates: Vec<String>,
    detail: Option<String>,
}

impl ExtractionDiagnostic {
    pub(crate) fn new(
        source: impl Into<String>,
        line: Option<usize>,
        kind: ExtractionDiagnosticKind,
        subject: Option<String>,
        mut candidates: Vec<String>,
        detail: Option<String>,
    ) -> Self {
        candidates.sort();
        candidates.dedup();
        Self {
            source: source.into(),
            line,
            kind,
            subject,
            candidates,
            detail,
        }
    }

    /// Returns the normalized file identifier where extraction was limited.
    #[must_use]
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Returns the one-based source line when syntax identified one.
    #[must_use]
    pub const fn line(&self) -> Option<usize> {
        self.line
    }

    /// Returns this diagnostic's stable category.
    #[must_use]
    pub const fn kind(&self) -> ExtractionDiagnosticKind {
        self.kind
    }

    /// Returns the module or path involved, when one exists.
    #[must_use]
    pub fn subject(&self) -> Option<&str> {
        self.subject.as_deref()
    }

    /// Returns every viable target for an ambiguity in deterministic order.
    #[must_use]
    pub fn candidates(&self) -> &[String] {
        &self.candidates
    }

    /// Returns parser or I/O detail intended for extraction reports.
    #[must_use]
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_deref()
    }
}

/// One dependency syntax occurrence extracted from a Rust source file.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct DependencyReference {
    source: String,
    referenced_path: String,
    target: Option<DependencyTarget>,
    kind: ImportKind,
    line: usize,
}

impl DependencyReference {
    pub(crate) fn new(
        source: impl Into<String>,
        referenced_path: impl Into<String>,
        target: Option<DependencyTarget>,
        kind: ImportKind,
        line: usize,
    ) -> Self {
        Self {
            source: source.into(),
            referenced_path: referenced_path.into(),
            target,
            kind,
            line,
        }
    }

    /// Returns the normalized workspace-relative file containing the syntax.
    #[must_use]
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Returns the Rust path before Cargo-aware external classification.
    #[must_use]
    pub fn referenced_path(&self) -> &str {
        &self.referenced_path
    }

    /// Returns the classified destination, or `None` when a diagnostic prevented classification.
    #[must_use]
    pub const fn target(&self) -> Option<&DependencyTarget> {
        self.target.as_ref()
    }

    /// Returns the resolved workspace file when the target is internal.
    #[must_use]
    pub fn internal_target(&self) -> Option<&str> {
        match &self.target {
            Some(DependencyTarget::Internal(target)) => Some(target),
            Some(DependencyTarget::External(_)) | None => None,
        }
    }

    /// Returns the Cargo-visible crate name when the target is external.
    #[must_use]
    pub fn external_target(&self) -> Option<&str> {
        match &self.target {
            Some(DependencyTarget::External(target)) => Some(target),
            Some(DependencyTarget::Internal(_)) | None => None,
        }
    }

    /// Returns the Rust syntax category that produced the reference.
    #[must_use]
    pub const fn kind(&self) -> ImportKind {
        self.kind
    }

    /// Returns the one-based source line of the dependency syntax.
    #[must_use]
    pub const fn line(&self) -> usize {
        self.line
    }
}

/// The deterministic result of Rust dependency extraction before graph-edge merging.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct DependencyExtraction {
    references: Vec<DependencyReference>,
    diagnostics: Vec<ExtractionDiagnostic>,
}

impl DependencyExtraction {
    pub(crate) fn new(
        mut references: Vec<DependencyReference>,
        mut diagnostics: Vec<ExtractionDiagnostic>,
    ) -> Self {
        references.sort();
        references.dedup();
        diagnostics.sort();
        diagnostics.dedup();
        Self {
            references,
            diagnostics,
        }
    }

    /// Returns extracted dependency syntax in deterministic order.
    #[must_use]
    pub fn references(&self) -> &[DependencyReference] {
        &self.references
    }

    /// Returns non-fatal extraction diagnostics in deterministic order.
    #[must_use]
    pub fn diagnostics(&self) -> &[ExtractionDiagnostic] {
        &self.diagnostics
    }

    /// Iterates over extracted dependency references.
    pub fn iter(&self) -> slice::Iter<'_, DependencyReference> {
        self.references.iter()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct LogicalModule {
    pub package: String,
    pub dependency_scope: super::cargo_project::CargoDependencyScope,
    pub target: String,
    pub segments: Vec<String>,
}

#[derive(Debug, Clone)]
pub(crate) struct RawReference {
    pub source: String,
    pub module: LogicalModule,
    pub segments: Vec<String>,
    pub leading_colon: bool,
    pub kind: ImportKind,
    pub line: usize,
    pub binding: Option<String>,
    pub declaration: Option<DeclarationSpan>,
    pub ignored: bool,
}

impl RawReference {
    pub fn rendered_path(&self) -> String {
        let path = self.segments.join("::");
        if self.leading_colon {
            format!("::{path}")
        } else {
            path
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct InternalResolution {
    pub source: String,
    pub module_segments: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::{
        DependencyExtraction, DependencyReference, DependencyTarget, ExtractionDiagnostic,
        ExtractionDiagnosticKind,
    };
    use crate::common::ImportKind;

    #[test]
    fn extraction_results_sort_and_deduplicate_data() {
        let reference = DependencyReference::new(
            "src/lib.rs",
            "crate::api::Handler",
            Some(DependencyTarget::Internal("src/api.rs".to_owned())),
            ImportKind::PathReference,
            4,
        );
        let diagnostic = ExtractionDiagnostic::new(
            "src/lib.rs",
            Some(3),
            ExtractionDiagnosticKind::MissingModule,
            Some("missing".to_owned()),
            Vec::new(),
            None,
        );

        let result = DependencyExtraction::new(
            vec![reference.clone(), reference],
            vec![diagnostic.clone(), diagnostic],
        );

        assert_eq!(result.references().len(), 1);
        assert_eq!(result.diagnostics().len(), 1);
        assert_eq!(result.diagnostics()[0].kind().as_str(), "missing-module");
    }
}