1use serde::{Deserialize, Serialize};
5use vvv_core::{Edit, LanguageId, RelPath, SymbolKind};
6
7use crate::change::Change;
8use crate::graph::Evidence;
9use crate::protocol::display::{Line, Role};
10use crate::protocol::vocabulary::{IntentLine, Plural};
11use crate::report::{Block, Document, ReferencePlan};
12use crate::{
13 Confidence, EngineError, FileChange, Intent, Match, Mutation, Occurrence, Planned, Selection,
14};
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21pub struct ReferencesQuery {
22 pub name: String,
23 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub symbol: Option<SymbolKind>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub language: Option<LanguageId>,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub declared_in: Option<RelPath>,
30}
31
32impl ReferencesQuery {
33 pub fn new(name: impl Into<String>) -> Self {
34 Self {
35 name: name.into(),
36 symbol: None,
37 language: None,
38 declared_in: None,
39 }
40 }
41
42 pub fn declared_in(mut self, path: impl Into<RelPath>) -> Self {
43 self.declared_in = Some(path.into());
44 self
45 }
46
47 pub fn of_symbol(mut self, symbol: SymbolKind) -> Self {
48 self.symbol = Some(symbol);
49 self
50 }
51
52 pub fn in_language(mut self, language: impl Into<LanguageId>) -> Self {
53 self.language = Some(language.into());
54 self
55 }
56
57 pub fn execute(self, engine: &crate::Engine) -> Result<References, EngineError> {
59 let _operation = engine.operation();
60 let mut graph = engine.graph()?;
61 self.execute_in(&mut graph)
62 }
63
64 pub fn definitions(self, engine: &crate::Engine) -> Result<Definitions, EngineError> {
68 let _operation = engine.operation();
69 let mut graph = engine.graph()?;
70 let declarations = graph.declarations(&self)?;
71 let mut queries = Vec::new();
72 for declaration in &declarations {
73 let Some(symbol) = &declaration.symbol else {
74 continue;
75 };
76 if declaration.address.is_none() {
77 continue;
78 }
79 let query = self
80 .clone()
81 .in_language(declaration.language.clone())
82 .of_symbol(symbol.kind)
83 .declared_in(declaration.path.clone());
84 if !queries.contains(&query) {
85 queries.push(query);
86 }
87 }
88 if queries.is_empty() {
89 queries.push(self);
90 }
91 Ok(Definitions {
92 candidates: queries
93 .into_iter()
94 .map(|query| query.execute_in(&mut graph))
95 .collect::<Result<_, _>>()?,
96 })
97 }
98
99 pub(crate) fn execute_in(
100 self,
101 graph: &mut crate::graph::Graph,
102 ) -> Result<References, EngineError> {
103 let query = &self;
104 let evidence = graph.references(query)?;
105 Ok(References {
106 name: query.name.clone(),
107 declarations: evidence.declarations,
108 occurrences: evidence.occurrences,
109 })
110 }
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
117pub struct References {
118 pub name: String,
119 pub declarations: Vec<Match>,
120 pub occurrences: Vec<Occurrence>,
121}
122
123impl References {
124 pub fn definition_of(&self, token: &Match) -> Option<&Match> {
129 if !self.occurrences.iter().any(|o| {
130 o.confidence == Confidence::Resolved
131 && o.m.language == token.language
132 && o.m.path == token.path
133 && o.m.span == token.span
134 }) {
135 return None;
136 }
137 let placed = self
138 .declarations
139 .iter()
140 .any(|d| d.language == token.language && d.address.is_some());
141 let mut declarations = self
142 .declarations
143 .iter()
144 .filter(|d| d.language == token.language && (!placed || d.address.is_some()));
145 let first = declarations.next()?;
146 declarations.next().is_none().then_some(first)
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
153pub struct Definitions {
154 pub candidates: Vec<References>,
155}
156
157impl Definitions {
158 pub fn definition_of(&self, token: &Match) -> Option<&Match> {
160 let mut definitions = self
161 .candidates
162 .iter()
163 .filter_map(|references| references.definition_of(token));
164 let first = definitions.next()?;
165 definitions.next().is_none().then_some(first)
166 }
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
176pub struct RenameIntent {
177 #[serde(flatten)]
178 pub references: ReferencesQuery,
179 pub to: String,
180 #[serde(default, skip_serializing_if = "Selection::is_all")]
181 pub selection: Selection,
182}
183
184impl RenameIntent {
185 pub fn new(name: impl Into<String>, to: impl Into<String>) -> Self {
186 Self {
187 references: ReferencesQuery::new(name),
188 to: to.into(),
189 selection: Selection::All,
190 }
191 }
192
193 pub fn declared_in(mut self, path: impl Into<RelPath>) -> Self {
194 self.references.declared_in = Some(path.into());
195 self
196 }
197
198 pub fn of_symbol(mut self, symbol: SymbolKind) -> Self {
199 self.references.symbol = Some(symbol);
200 self
201 }
202
203 pub fn in_language(mut self, language: impl Into<LanguageId>) -> Self {
204 self.references.language = Some(language.into());
205 self
206 }
207
208 pub fn selecting(mut self, selection: Selection) -> Self {
209 self.selection = selection;
210 self
211 }
212
213 pub fn plan(self, engine: &crate::Engine) -> Result<Planned<Rename>, EngineError> {
217 let _operation = engine.operation();
218 let mut graph = engine.graph()?;
219 self.plan_in(&mut graph, engine.workspace())
220 }
221
222 pub(crate) fn plan_in(
223 self,
224 graph: &mut crate::graph::Graph,
225 workspace: &crate::Workspace,
226 ) -> Result<Planned<Rename>, EngineError> {
227 let intent = &self;
228 let Evidence {
229 declarations,
230 occurrences,
231 ambiguous,
232 } = graph.references(&intent.references)?;
233
234 let default: Vec<Match> = occurrences
237 .iter()
238 .filter(|o| match o.confidence {
239 Confidence::Resolved => true,
240 Confidence::Unresolved => !ambiguous.contains(&o.m.language),
241 Confidence::Other => false,
242 })
243 .map(|o| o.m.clone())
244 .collect();
245 let chosen = if intent.selection.is_all() {
246 default
247 } else {
248 occurrences.iter().map(|o| o.m.clone()).collect()
249 };
250 let mut change = Change::new();
251 for m in intent.selection.narrow(chosen)? {
252 change.edit(
253 graph.file(&m.path)?.file().witness(),
254 Edit::replace(m.span, &intent.to),
255 )?;
256 }
257 Planned::of(
258 workspace,
259 change,
260 Intent::Rename(intent.clone()),
261 |_, files| Rename {
262 intent: intent.clone(),
263 state: crate::MutationState::Preview,
264 declarations,
265 occurrences,
266 files,
267 },
268 )
269 }
270}
271
272#[derive(Debug, Clone, Serialize, Deserialize)]
274#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
275pub struct Rename {
276 pub intent: RenameIntent,
277 #[serde(flatten)]
279 pub state: crate::MutationState,
280 pub declarations: Vec<Match>,
282 pub occurrences: Vec<Occurrence>,
285 pub files: Vec<FileChange>,
286}
287
288impl Mutation for Rename {
289 fn into_mutation(self) -> crate::MutationAnswer {
290 crate::MutationAnswer::Rename(self)
291 }
292
293 fn applied(&mut self, id: u64) {
294 self.state = crate::MutationState::Applied { history_id: id };
295 }
296}
297
298impl Document {
299 pub(crate) fn rename(result: &Rename) -> Self {
300 let mut report = Self::new();
301 report.title(IntentLine(&Intent::Rename(result.intent.clone())));
302 report.declarations(&result.declarations);
303 report.block_body(Block::Verdicts {
304 occurrences: result.occurrences.clone(),
305 plan: Some(ReferencePlan {
306 state: result.state,
307 files: result.files.clone(),
308 }),
309 });
310 let strip = Self::verdict_counts(&result.occurrences);
311 let edits = Self::edits_in(&result.files);
312 let plan = Line::single(
313 Role::Dim,
314 format!(
315 "→ {} in {}",
316 Plural(edits, "occurrence"),
317 Plural(result.files.len(), "file")
318 ),
319 );
320 if result.state.is_applied() {
321 report.block_note(Block::Summary(strip));
322 report.receipt(result.state, plan);
323 return report;
324 }
325 report.block_note(Block::Summary(strip.and(Role::Plain, " ").and_line(plan)));
326 report
327 }
328
329 pub(crate) fn references(result: &References) -> Self {
330 let mut report = Self::new();
331 report.declarations(&result.declarations);
332 report.block_body(Block::Verdicts {
333 occurrences: result.occurrences.clone(),
334 plan: None,
335 });
336 report.block_note(Block::Summary(Self::verdict_counts(&result.occurrences)));
337 report
338 }
339}