Skip to main content

vvv_engine/capabilities/
navigation.rs

1//! Navigation from a versioned occurrence, with source and metadata captured together.
2use crate::graph::Graph;
3use crate::protocol::display::{Line, Role};
4use crate::report::Document;
5use crate::{ContentId, Engine, EngineError, File, Match, SourceAnchor, SymbolRef};
6use serde::{Deserialize, Serialize};
7use vvv_core::{Address, Position, RelPath, Span};
8
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
11#[serde(tag = "kind", rename_all = "snake_case")]
12pub enum NavigationOrigin {
13    Position {
14        path: RelPath,
15        position: Position,
16        #[serde(default)]
17        expected_content: Option<ContentId>,
18    },
19    Occurrence {
20        anchor: SourceAnchor,
21    },
22    Symbol {
23        symbol: SymbolRef,
24    },
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
29pub struct NavigationQuery {
30    pub origin: NavigationOrigin,
31    #[serde(default, skip_serializing_if = "crate::Selection::is_all")]
32    pub selection: crate::Selection,
33}
34
35/// Opaque identity of captured source and project inputs; not a disk transaction.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
38#[serde(transparent)]
39pub struct SnapshotId(pub(crate) ContentId);
40
41impl From<ContentId> for SnapshotId {
42    fn from(content: ContentId) -> Self {
43        Self(content)
44    }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
49pub struct NavigationReply {
50    pub snapshot: SnapshotId,
51    #[serde(flatten)]
52    pub outcome: NavigationOutcome,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
57#[serde(tag = "outcome", rename_all = "snake_case")]
58pub enum NavigationOutcome {
59    Resolved {
60        target: SymbolRef,
61        evidence: ResolutionEvidence,
62        preview: Box<DefinitionPreview>,
63    },
64    Ambiguous {
65        candidates: Vec<DefinitionCandidate>,
66    },
67    Unavailable {
68        reason: UnavailableReason,
69    },
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
74pub struct DefinitionCandidate {
75    pub target: SymbolRef,
76    pub declaration: Match,
77    pub evidence: ResolutionEvidence,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
82pub struct ResolutionEvidence {
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub semantic: Option<crate::ProviderVersion>,
85    /// The binding's address followed by each re-export address, in order.
86    pub addresses: Vec<Address>,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
91pub struct DefinitionPreview {
92    pub container: SymbolRef,
93    pub declaration: Match,
94    /// Complete captured file. All spans remain absolute UTF-8 byte ranges.
95    pub source: File,
96    pub selection: Span,
97    pub identifiers: Vec<SourceAnchor>,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
101#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
102#[serde(rename_all = "snake_case")]
103pub enum UnavailableReason {
104    NoIdentifier,
105    Unresolved,
106    UnsupportedContext,
107    ExternalSourceUnavailable,
108    CyclicImports,
109}
110
111impl UnavailableReason {
112    pub fn message(self) -> &'static str {
113        match self {
114            Self::NoIdentifier => "Select an identifier",
115            Self::Unresolved => "Could not resolve this name",
116            Self::UnsupportedContext => "Cannot follow this reference yet",
117            Self::ExternalSourceUnavailable => "Source is outside this workspace",
118            Self::CyclicImports => "Could not resolve cyclic imports",
119        }
120    }
121}
122
123impl NavigationQuery {
124    pub fn at(path: impl Into<RelPath>, position: Position) -> Self {
125        Self {
126            selection: crate::Selection::All,
127            origin: NavigationOrigin::Position {
128                path: path.into(),
129                position,
130                expected_content: None,
131            },
132        }
133    }
134
135    pub fn occurrence(anchor: SourceAnchor) -> Self {
136        Self {
137            selection: crate::Selection::All,
138            origin: NavigationOrigin::Occurrence { anchor },
139        }
140    }
141
142    pub fn select(mut self, selection: crate::Selection) -> Self {
143        self.selection = selection;
144        self
145    }
146
147    pub fn execute(self, engine: &Engine) -> Result<NavigationReply, EngineError> {
148        let _operation = engine.operation();
149        self.execute_in(&mut *engine.graph()?)
150    }
151
152    /// Use a versioned host provider only where syntax cannot establish a target.
153    /// The provider runs under operation exclusion and must not re-enter the engine.
154    pub fn execute_with(
155        self,
156        engine: &Engine,
157        provider: &dyn crate::NavigationProvider,
158        cancellation: &crate::NavigationCancellation,
159    ) -> Result<NavigationReply, EngineError> {
160        cancellation.check()?;
161        let _operation = engine.operation();
162        cancellation.check()?;
163        engine.graph()?.navigate_with(
164            self,
165            Some(&super::semantic::SemanticNavigation {
166                provider,
167                cancellation,
168            }),
169        )
170    }
171
172    pub(crate) fn execute_in(self, graph: &mut Graph) -> Result<NavigationReply, EngineError> {
173        graph.navigate(self)
174    }
175}
176
177impl Document {
178    pub(crate) fn navigation(result: &NavigationReply) -> Self {
179        let mut report = Self::new();
180        match &result.outcome {
181            NavigationOutcome::Resolved { preview, .. } => {
182                report.declarations(std::slice::from_ref(&preview.declaration));
183                let span = preview.container.declaration.span;
184                if let Some(text) = preview.source.text.get(span.start..span.end) {
185                    report.body(text.lines().map(|line| Line::single(Role::Plain, line)));
186                }
187            }
188            NavigationOutcome::Ambiguous { candidates } => {
189                report.block_body(crate::report::Block::Matches(
190                    candidates
191                        .iter()
192                        .map(|c| c.declaration.clone())
193                        .collect::<Vec<_>>(),
194                ));
195                report.notes([Line::single(
196                    Role::Dim,
197                    "Several definitions match; use --select with a row number or match id",
198                )]);
199            }
200            NavigationOutcome::Unavailable { reason } => {
201                report.notes([Line::single(Role::Dim, reason.message())])
202            }
203        }
204        report
205    }
206}
207
208/// Compact resolution with the same origin and selection semantics as navigation.
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
211#[serde(transparent)]
212pub struct ResolutionQuery(pub NavigationQuery);
213
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
216pub struct ResolutionReply {
217    pub snapshot: SnapshotId,
218    #[serde(flatten)]
219    pub outcome: ResolutionOutcome,
220}
221
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
223#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
224#[serde(tag = "outcome", rename_all = "snake_case")]
225pub enum ResolutionOutcome {
226    Resolved {
227        #[serde(flatten)]
228        definition: Box<DefinitionLocation>,
229        container: SymbolRef,
230    },
231    Ambiguous {
232        candidates: Vec<DefinitionLocation>,
233    },
234    Unavailable {
235        reason: UnavailableReason,
236    },
237}
238
239/// Enough information to select, open, or request context for a declaration.
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
242pub struct DefinitionLocation {
243    pub target: SymbolRef,
244    pub id: crate::MatchId,
245    pub name: String,
246    pub start: Position,
247    pub evidence: ResolutionEvidence,
248}
249impl DefinitionLocation {
250    fn new(target: SymbolRef, declaration: Match, evidence: ResolutionEvidence) -> Self {
251        Self {
252            target,
253            id: declaration.id,
254            name: declaration.symbol.expect("navigation declaration").name,
255            start: declaration.start,
256            evidence,
257        }
258    }
259}
260impl ResolutionQuery {
261    pub fn execute(self, engine: &Engine) -> Result<ResolutionReply, EngineError> {
262        let _operation = engine.operation();
263        self.execute_in(&mut *engine.graph()?)
264    }
265    pub(crate) fn execute_in(self, graph: &mut Graph) -> Result<ResolutionReply, EngineError> {
266        let reply = self.0.execute_in(graph)?;
267        Ok(ResolutionReply {
268            snapshot: reply.snapshot,
269            outcome: match reply.outcome {
270                NavigationOutcome::Resolved {
271                    target,
272                    evidence,
273                    preview,
274                } => ResolutionOutcome::Resolved {
275                    definition: Box::new(DefinitionLocation::new(
276                        target,
277                        preview.declaration,
278                        evidence,
279                    )),
280                    container: preview.container,
281                },
282                NavigationOutcome::Ambiguous { candidates } => ResolutionOutcome::Ambiguous {
283                    candidates: candidates
284                        .into_iter()
285                        .map(|c| DefinitionLocation::new(c.target, c.declaration, c.evidence))
286                        .collect(),
287                },
288                NavigationOutcome::Unavailable { reason } => {
289                    ResolutionOutcome::Unavailable { reason }
290                }
291            },
292        })
293    }
294}
295impl Document {
296    pub(crate) fn resolution(reply: &ResolutionReply) -> Self {
297        let mut doc = Self::new();
298        let locations = match &reply.outcome {
299            ResolutionOutcome::Resolved { definition, .. } => {
300                std::slice::from_ref(definition.as_ref())
301            }
302            ResolutionOutcome::Ambiguous { candidates } => candidates,
303            ResolutionOutcome::Unavailable { reason } => {
304                doc.notes([Line::single(Role::Dim, reason.message())]);
305                return doc;
306            }
307        };
308        doc.block_body(crate::report::Block::Locations(locations.to_vec()));
309        doc
310    }
311}