Skip to main content

vvv_engine/
rewrite.rs

1//! `rewrite`: one edit per selected match, the template expanded with the
2//! match's captures from the same immutable source snapshot.
3
4use crate::protocol::display::{Line, Role};
5use crate::protocol::vocabulary::{IntentLine, Mark, Plural};
6use crate::report::{Block, Document};
7use crate::{Intent, Mutation, Selection, Template};
8use serde::{Deserialize, Serialize};
9
10use std::collections::{BTreeMap, btree_map::Entry};
11use vvv_core::{Edit, Query, RelPath};
12
13use crate::change::Change;
14use crate::graph::Graph;
15use crate::{Candidate, EngineError, FileChange, Match, Planned, Workspace};
16
17/// The rewrite `intent` makes of `matches` already found: a caller that
18/// keeps the matches supplies its selection; selected matches are revalidated
19/// against the source before their coordinates and captures are used.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct RewriteOf {
22    pub intent: RewriteIntent,
23    pub matches: Vec<crate::Match>,
24}
25
26/// Replace every selected match of `query` with `template`.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
29pub struct RewriteIntent {
30    pub query: Query,
31    pub template: Template,
32    #[serde(default, skip_serializing_if = "Selection::is_all")]
33    pub selection: Selection,
34}
35
36impl RewriteIntent {
37    pub fn new(query: Query, template: impl Into<Template>) -> Self {
38        Self {
39            query,
40            template: template.into(),
41            selection: Selection::All,
42        }
43    }
44
45    pub fn selecting(mut self, selection: Selection) -> Self {
46        self.selection = selection;
47        self
48    }
49
50    /// Plan a rewrite without writing files; see [`Apply`](crate::Apply).
51    pub fn plan(self, engine: &crate::Engine) -> Result<Planned<Rewrite>, EngineError> {
52        let _operation = engine.operation();
53        let mut graph = engine.graph()?;
54        self.plan_in(&mut graph, engine.workspace())
55    }
56
57    pub(crate) fn plan_in(
58        self,
59        graph: &mut crate::graph::Graph,
60        workspace: &crate::Workspace,
61    ) -> Result<Planned<Rewrite>, EngineError> {
62        let matches = graph.search(&self.query)?.matches;
63        RewriteMatches::new(self, matches, graph)?.plan(workspace)
64    }
65}
66
67/// `vvv rewrite`: one edit per selected match.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
70pub struct Rewrite {
71    pub intent: RewriteIntent,
72    /// Preview or successful application with its history entry.
73    #[serde(flatten)]
74    pub state: crate::MutationState,
75    pub files: Vec<FileChange>,
76}
77
78impl Mutation for Rewrite {
79    fn into_mutation(self) -> crate::MutationAnswer {
80        crate::MutationAnswer::Rewrite(self)
81    }
82
83    fn applied(&mut self, id: u64) {
84        self.state = crate::MutationState::Applied { history_id: id };
85    }
86}
87
88/// Retained matches are revalidated against their candidate snapshots before
89/// expansion. The intent's selection still narrows them.
90impl RewriteOf {
91    /// Plan without writing files.
92    pub fn plan(self, engine: &crate::Engine) -> Result<Planned<Rewrite>, EngineError> {
93        let _operation = engine.operation();
94        let mut graph = engine.graph()?;
95        self.plan_in(&mut graph, engine.workspace())
96    }
97
98    pub(crate) fn plan_in(
99        self,
100        graph: &mut crate::graph::Graph,
101        workspace: &crate::Workspace,
102    ) -> Result<Planned<Rewrite>, EngineError> {
103        let matched = RewriteMatches::new(self.intent, self.matches, graph)?;
104        for file in matched.files.values() {
105            file.candidate
106                .validate_matches(&matched.intent.query, &file.matches)?;
107        }
108        matched.plan(workspace)
109    }
110}
111
112/// Selected matches and the immutable candidates whose text supplies their
113/// captures and edit provenance.
114struct RewriteMatches {
115    intent: RewriteIntent,
116    files: BTreeMap<RelPath, FileMatches>,
117}
118
119struct FileMatches {
120    candidate: Candidate,
121    matches: Vec<Match>,
122}
123
124impl RewriteMatches {
125    fn new(intent: RewriteIntent, matches: Vec<Match>, graph: &Graph) -> Result<Self, EngineError> {
126        let mut files: BTreeMap<RelPath, FileMatches> = BTreeMap::new();
127        for m in intent.selection.narrow(matches)? {
128            let file = match files.entry(m.path.clone()) {
129                Entry::Occupied(entry) => entry.into_mut(),
130                Entry::Vacant(entry) => entry.insert(FileMatches {
131                    candidate: graph.file(&m.path)?,
132                    matches: Vec::new(),
133                }),
134            };
135            file.matches.push(m);
136        }
137        Ok(Self { intent, files })
138    }
139
140    fn plan(self, workspace: &Workspace) -> Result<Planned<Rewrite>, EngineError> {
141        let mut change = Change::new();
142        for file in self.files.values() {
143            file.edits(&self.intent, &mut change)?;
144        }
145        Planned::of(
146            workspace,
147            change,
148            crate::Intent::Rewrite(self.intent.clone()),
149            |_, files| Rewrite {
150                intent: self.intent,
151                state: crate::MutationState::Preview,
152                files,
153            },
154        )
155    }
156}
157
158impl FileMatches {
159    fn edits(&self, intent: &RewriteIntent, change: &mut Change) -> Result<(), EngineError> {
160        let file = self.candidate.file();
161        for m in &self.matches {
162            let replacement = intent.template.expand(m, file.source()).map_err(|source| {
163                EngineError::Template {
164                    path: m.path.clone(),
165                    line: m.start.line,
166                    source,
167                }
168            })?;
169            change.edit(file.witness(), Edit::replace(m.span, replacement))?;
170        }
171        Ok(())
172    }
173}
174
175impl Document {
176    pub(crate) fn rewrite(result: &Rewrite) -> Self {
177        let mut report = Self::new();
178        report.title(IntentLine(&Intent::Rewrite(result.intent.clone())));
179        report.block_body(Block::Changes {
180            state: result.state,
181            files: result.files.clone(),
182        });
183        let edits = Self::edits_in(&result.files);
184        if edits == 0 {
185            report.block_note(Block::Summary(
186                Line::mark(Mark::Nothing).and(Role::Plain, " no matches"),
187            ));
188            return report;
189        }
190        report.receipt(
191            result.state,
192            Line::mark(Mark::Rewrite)
193                .and(Role::Plain, format!(" {edits}   "))
194                .and(Role::Dim, Plural(result.files.len(), "file").to_string()),
195        );
196        report
197    }
198}