vvv_engine/capabilities/moves/
selection.rs1use crate::graph::{Candidate, Graph, Namespace};
3use crate::{ContentId, Engine, EngineError, Match, RelPath, Selection, SourceFile};
4use serde::{Deserialize, Serialize};
5use vvv_core::{CompanionOwnership, RawMatch, Role, Symbol};
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
9#[serde(deny_unknown_fields)]
10pub struct SymbolMoveCandidatesQuery {
11 pub name: String,
12 pub from: RelPath,
13}
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
16pub struct SymbolMoveCandidates {
17 pub content: ContentId,
18 pub candidates: Vec<SymbolMoveCandidate>,
19}
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
22pub struct SymbolMoveCandidate {
23 pub declaration: Match,
24 pub pieces: Vec<SymbolMovePiece>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub unsupported: Option<SymbolMoveUnsupported>,
27}
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
30#[serde(rename_all = "snake_case")]
31pub enum SymbolMoveUnsupported {
32 MissingEvidence,
33 SameFile,
34 DestinationBindingConflict,
35 NestedDeclaration,
36 UnsupportedDeclarationKind,
37 CompetingBinding,
38 AmbiguousCompanion,
39 UnsupportedCompanionTarget,
40}
41impl SymbolMoveUnsupported {
42 pub fn message(self) -> &'static str {
43 match self {
44 Self::MissingEvidence => "language does not provide declaration ownership evidence",
45 Self::SameFile => "source and destination are the same file",
46 Self::DestinationBindingConflict => "destination already declares this name",
47 Self::UnsupportedDeclarationKind => {
48 "this declaration form cannot be moved independently"
49 }
50 Self::NestedDeclaration => "nested declarations cannot be moved independently",
51 Self::CompetingBinding => "several declarations share this module and name",
52 Self::AmbiguousCompanion => "companion has several possible owners",
53 Self::UnsupportedCompanionTarget => {
54 "companion target cannot be assigned to this declaration"
55 }
56 }
57 }
58}
59impl std::fmt::Display for SymbolMoveUnsupported {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 f.write_str(self.message())
62 }
63}
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
66pub struct SymbolMovePiece {
67 pub symbol: Symbol,
68 pub ownership: SymbolMoveOwnership,
69}
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
72#[serde(rename_all = "snake_case")]
73pub enum SymbolMoveOwnership {
74 Declaration,
75 SameScopeTarget,
76}
77impl SymbolMovePiece {
78 fn declaration(source: &SourceFile, symbol: &Symbol) -> Result<Self, EngineError> {
79 let text = source.text();
80 for span in [symbol.span, symbol.name_span, symbol.extent] {
81 if span.start > span.end
82 || span.end > text.len()
83 || !text.is_char_boundary(span.start)
84 || !text.is_char_boundary(span.end)
85 {
86 return Err(crate::ExtractionError::InvalidSpan {
87 path: source.path().into(),
88 span,
89 }
90 .into());
91 }
92 }
93 Ok(Self {
94 symbol: symbol.clone(),
95 ownership: SymbolMoveOwnership::Declaration,
96 })
97 }
98}
99impl SymbolMoveCandidate {
100 fn of(source: &Candidate, ns: &Namespace, symbol: &Symbol) -> Result<Self, EngineError> {
101 let declaration_piece = SymbolMovePiece::declaration(source.file(), symbol)?;
102 let mut raw = RawMatch::plain(
103 symbol.span,
104 symbol.kind.as_str(),
105 &source.text()[symbol.span.start..symbol.span.end],
106 );
107 raw.symbol = Some(symbol.clone());
108 raw.role = Role::Declaration;
109 let declaration = source.locate(raw);
110 let facts = source.facts()?;
111 let evidence = facts
112 .declaration_pieces
113 .iter()
114 .find(|pieces| pieces.declaration == symbol.span);
115 let mut unsupported = match evidence {
116 None => Some(SymbolMoveUnsupported::MissingEvidence),
117 Some(pieces) if !pieces.supported => {
118 Some(SymbolMoveUnsupported::UnsupportedDeclarationKind)
119 }
120 Some(pieces) if !pieces.top_level => Some(SymbolMoveUnsupported::NestedDeclaration),
121 _ => None,
122 };
123 if unsupported.is_none() && symbol.kind == crate::SymbolKind::Module {
124 unsupported = Some(SymbolMoveUnsupported::UnsupportedDeclarationKind);
125 }
126 if unsupported.is_none()
128 && facts
129 .symbols
130 .iter()
131 .filter(|peer| {
132 peer.name == symbol.name
133 && ns.is_addressable(peer.kind)
134 && facts
135 .declaration_pieces
136 .iter()
137 .any(|pieces| pieces.declaration == peer.span && pieces.top_level)
138 })
139 .count()
140 != 1
141 {
142 unsupported = Some(SymbolMoveUnsupported::CompetingBinding);
143 }
144 let mut pieces = vec![declaration_piece];
145 if let Some(evidence) = evidence {
146 for companion in &evidence.companions {
147 match companion.ownership {
148 CompanionOwnership::AmbiguousTarget => {
149 unsupported.get_or_insert(SymbolMoveUnsupported::AmbiguousCompanion);
150 }
151 CompanionOwnership::UnsupportedTarget => {
152 unsupported
153 .get_or_insert(SymbolMoveUnsupported::UnsupportedCompanionTarget);
154 }
155 CompanionOwnership::SameScopeTarget => {
156 let symbol = facts
157 .symbols
158 .iter()
159 .find(|symbol| symbol.span == companion.span)
160 .ok_or(EngineError::InvalidSymbolMoveEvidence)?;
161 let mut piece = SymbolMovePiece::declaration(source.file(), symbol)?;
162 piece.ownership = SymbolMoveOwnership::SameScopeTarget;
163 pieces.push(piece);
164 }
165 }
166 }
167 }
168 pieces.sort_by_key(|piece| piece.symbol.extent);
169 pieces.dedup_by_key(|piece| piece.symbol.extent);
170 Ok(Self {
171 declaration,
172 pieces,
173 unsupported,
174 })
175 }
176}
177impl SymbolMoveCandidatesQuery {
178 pub fn execute(self, engine: &Engine) -> Result<SymbolMoveCandidates, EngineError> {
179 let _operation = engine.operation();
180 self.execute_in(&mut *engine.graph()?, engine.workspace())
181 }
182 pub(crate) fn execute_in(
183 self,
184 graph: &mut Graph,
185 workspace: &crate::Workspace,
186 ) -> Result<SymbolMoveCandidates, EngineError> {
187 if self.from.as_os_str().is_empty()
188 || self.from.is_absolute()
189 || self.from.components().any(|part| {
190 !matches!(
191 part,
192 std::path::Component::Normal(_) | std::path::Component::CurDir
193 )
194 })
195 || !self
196 .from
197 .components()
198 .any(|part| matches!(part, std::path::Component::Normal(_)))
199 {
200 return Err(EngineError::InvalidMovePath { path: self.from });
201 }
202 let path = workspace.normalize(&self.from);
203 let source = graph.file(&path)?;
204 let ns = graph.namespace_of(&path)?;
205 SymbolMoveCandidates::of(&source, &ns, &self.name)
206 }
207}
208impl SymbolMoveCandidates {
209 pub(crate) fn of(source: &Candidate, ns: &Namespace, name: &str) -> Result<Self, EngineError> {
210 let mut candidates = source
211 .facts()?
212 .symbols
213 .iter()
214 .filter(|symbol| symbol.name == name && ns.is_addressable(symbol.kind))
215 .map(|symbol| SymbolMoveCandidate::of(source, ns, symbol))
216 .collect::<Result<Vec<_>, _>>()?;
217 candidates.sort_by_key(|candidate| candidate.declaration.span);
218 Ok(Self {
219 content: source.file().content_id(),
220 candidates,
221 })
222 }
223 pub(crate) fn select(
224 self,
225 name: &str,
226 selection: &Selection,
227 ) -> Result<SymbolMoveCandidate, EngineError> {
228 if self.candidates.is_empty() && selection.is_all() {
229 return Err(EngineError::NoSuchSymbol {
230 name: name.into(),
231 kind: None,
232 });
233 }
234 let matches = self
235 .candidates
236 .iter()
237 .map(|candidate| candidate.declaration.clone())
238 .collect();
239 let selected = selection.narrow(matches)?;
240 if selected.len() != 1 {
241 return Err(EngineError::SymbolMoveSelection {
242 candidates: self.candidates,
243 });
244 }
245 let candidate = self
246 .candidates
247 .into_iter()
248 .find(|candidate| candidate.declaration.id == selected[0].id)
249 .ok_or(EngineError::InvalidSymbolMoveEvidence)?;
250 if let Some(reason) = candidate.unsupported {
251 return Err(EngineError::UnsupportedSymbolMove {
252 declaration: Box::new(candidate.declaration),
253 reason,
254 });
255 }
256 Ok(candidate)
257 }
258}
259impl crate::report::Document {
260 pub(crate) fn symbol_move_candidates(result: &SymbolMoveCandidates) -> Self {
261 let mut document = Self::new();
262 document.block_body(crate::report::Block::SymbolMoveCandidates(
263 result.candidates.clone(),
264 ));
265 document
266 }
267}