tinymist_query/
rename.rs

1use lsp_types::{
2    DocumentChangeOperation, DocumentChanges, OneOf, OptionalVersionedTextDocumentIdentifier,
3    RenameFile, TextDocumentEdit,
4};
5use rustc_hash::FxHashSet;
6use tinymist_std::path::{PathClean, unix_slash};
7use typst::{
8    foundations::{Repr, Str},
9    syntax::Span,
10};
11
12use crate::adt::interner::Interned;
13use crate::{
14    analysis::{LinkObject, LinkTarget, get_link_exprs},
15    find_references,
16    prelude::*,
17    prepare_renaming,
18    syntax::{Decl, RefExpr, SyntaxClass, first_ancestor_expr, get_index_info, node_ancestors},
19};
20
21/// The [`textDocument/rename`] request is sent from the client to the server to
22/// ask the server to compute a workspace change so that the client can perform
23/// a workspace-wide rename of a symbol.
24///
25/// [`textDocument/rename`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_rename
26#[derive(Debug, Clone)]
27pub struct RenameRequest {
28    /// The path of the document to request for.
29    pub path: PathBuf,
30    /// The source code position to request for.
31    pub position: LspPosition,
32    /// The new name to rename to.
33    pub new_name: String,
34}
35
36impl SemanticRequest for RenameRequest {
37    type Response = WorkspaceEdit;
38
39    fn request(self, ctx: &mut LocalContext) -> Option<Self::Response> {
40        let source = ctx.source_by_path(&self.path).ok()?;
41        let syntax = ctx.classify_for_decl(&source, self.position)?;
42
43        let def = ctx.def_of_syntax(&source, syntax.clone())?;
44
45        prepare_renaming(&syntax, &def)?;
46
47        match syntax {
48            // todo: abs path
49            SyntaxClass::ImportPath(path) | SyntaxClass::IncludePath(path) => {
50                let ref_path_str = path.cast::<ast::Str>()?.get();
51                let new_path_str = if !self.new_name.ends_with(".typ") {
52                    self.new_name + ".typ"
53                } else {
54                    self.new_name
55                };
56
57                let def_fid = def.file_id()?;
58                // todo: rename in untitled files
59                let old_path = ctx.path_for_id(def_fid).ok()?.to_err().ok()?;
60
61                let new_path = Path::new(new_path_str.as_str());
62                let rename_loc = Path::new(ref_path_str.as_str());
63                let diff = tinymist_std::path::diff(new_path, rename_loc)?;
64                if diff.is_absolute() {
65                    log::info!(
66                        "bad rename: absolute path, base: {rename_loc:?}, new: {new_path:?}, diff: {diff:?}"
67                    );
68                    return None;
69                }
70
71                let new_path = old_path.join(&diff).clean();
72
73                let old_uri = path_to_url(&old_path).ok()?;
74                let new_uri = path_to_url(&new_path).ok()?;
75
76                let mut edits: HashMap<Url, Vec<TextEdit>> = HashMap::new();
77                do_rename_file(ctx, def_fid, diff, &mut edits);
78
79                let mut document_changes = edits_to_document_changes(edits);
80
81                document_changes.push(lsp_types::DocumentChangeOperation::Op(
82                    lsp_types::ResourceOp::Rename(RenameFile {
83                        old_uri,
84                        new_uri,
85                        options: None,
86                        annotation_id: None,
87                    }),
88                ));
89
90                // todo: validate: workspace.workspaceEdit.resourceOperations
91                Some(WorkspaceEdit {
92                    document_changes: Some(DocumentChanges::Operations(document_changes)),
93                    ..Default::default()
94                })
95            }
96            _ => {
97                let references = find_references(ctx, &source, syntax)?;
98
99                let mut edits = HashMap::new();
100
101                for loc in references {
102                    let uri = loc.uri;
103                    let range = loc.range;
104                    let edits = edits.entry(uri).or_insert_with(Vec::new);
105                    edits.push(TextEdit {
106                        range,
107                        new_text: self.new_name.clone(),
108                    });
109                }
110
111                log::info!("rename edits: {edits:?}");
112
113                Some(WorkspaceEdit {
114                    changes: Some(edits),
115                    ..Default::default()
116                })
117            }
118        }
119    }
120}
121
122pub(crate) fn do_rename_file(
123    ctx: &mut LocalContext,
124    def_fid: TypstFileId,
125    diff: PathBuf,
126    edits: &mut HashMap<Url, Vec<TextEdit>>,
127) -> Option<()> {
128    let def_path = def_fid
129        .vpath()
130        .as_rooted_path()
131        .file_name()
132        .unwrap_or_default()
133        .to_str()
134        .unwrap_or_default()
135        .into();
136    let mut ctx = RenameFileWorker {
137        ctx,
138        def_fid,
139        def_path,
140        diff,
141        inserted: FxHashSet::default(),
142    };
143    ctx.work(edits)
144}
145
146struct RenameFileWorker<'a> {
147    ctx: &'a mut LocalContext,
148    def_fid: TypstFileId,
149    def_path: Interned<str>,
150    diff: PathBuf,
151    inserted: FxHashSet<Span>,
152}
153
154impl RenameFileWorker<'_> {
155    pub(crate) fn work(&mut self, edits: &mut HashMap<Url, Vec<TextEdit>>) -> Option<()> {
156        let dep = self.ctx.module_dependencies().get(&self.def_fid).cloned();
157        if let Some(dep) = dep {
158            for ref_fid in dep.dependents.iter() {
159                self.refs_in_file(*ref_fid, edits);
160            }
161        }
162
163        for ref_fid in self.ctx.source_files().clone() {
164            self.links_in_file(ref_fid, edits);
165        }
166
167        Some(())
168    }
169
170    fn refs_in_file(
171        &mut self,
172        ref_fid: TypstFileId,
173        edits: &mut HashMap<Url, Vec<TextEdit>>,
174    ) -> Option<()> {
175        let ref_src = self.ctx.source_by_id(ref_fid).ok()?;
176        let uri = self.ctx.uri_for_id(ref_fid).ok()?;
177
178        let import_info = self.ctx.expr_stage(&ref_src);
179
180        let edits = edits.entry(uri).or_default();
181        for (span, r) in &import_info.resolves {
182            if !matches!(
183                r.decl.as_ref(),
184                Decl::ImportPath(..) | Decl::IncludePath(..) | Decl::PathStem(..)
185            ) {
186                continue;
187            }
188
189            if let Some(edit) = self.rename_module_path(*span, r, &ref_src) {
190                edits.push(edit);
191            }
192        }
193
194        Some(())
195    }
196
197    fn links_in_file(
198        &mut self,
199        ref_fid: TypstFileId,
200        edits: &mut HashMap<Url, Vec<TextEdit>>,
201    ) -> Option<()> {
202        let ref_src = self.ctx.source_by_id(ref_fid).ok()?;
203
204        let index = get_index_info(&ref_src);
205        if !index.paths.contains(&self.def_path) {
206            return Some(());
207        }
208
209        let uri = self.ctx.uri_for_id(ref_fid).ok()?;
210
211        let link_info = get_link_exprs(&ref_src);
212        let root = LinkedNode::new(ref_src.root());
213        let edits = edits.entry(uri).or_default();
214        for obj in &link_info.objects {
215            if !matches!(&obj.target,
216                LinkTarget::Path(file_id, _) if *file_id == self.def_fid
217            ) {
218                continue;
219            }
220            if let Some(edit) = self.rename_resource_path(obj, &root, &ref_src) {
221                edits.push(edit);
222            }
223        }
224
225        Some(())
226    }
227
228    fn rename_resource_path(
229        &mut self,
230        obj: &LinkObject,
231        root: &LinkedNode,
232        src: &Source,
233    ) -> Option<TextEdit> {
234        let r = root.find(obj.span)?;
235        self.rename_path_expr(r.clone(), r.cast()?, src, false)
236    }
237
238    fn rename_module_path(&mut self, span: Span, r: &RefExpr, src: &Source) -> Option<TextEdit> {
239        let importing = r.root.as_ref()?.file_id();
240
241        if importing != Some(self.def_fid) {
242            return None;
243        }
244        crate::log_debug_ct!("import: {span:?} -> {importing:?} v.s. {:?}", self.def_fid);
245        // rename_importer(self.ctx, &ref_src, *span, &self.diff, edits);
246
247        let root = LinkedNode::new(src.root());
248        let import_node = root.find(span).and_then(first_ancestor_expr)?;
249        let (import_path, has_path_var) = node_ancestors(&import_node).find_map(|import_node| {
250            match import_node.cast::<ast::Expr>()? {
251                ast::Expr::ModuleImport(import) => Some((
252                    import.source(),
253                    import.new_name().is_none() && import.imports().is_none(),
254                )),
255                ast::Expr::ModuleInclude(include) => Some((include.source(), false)),
256                _ => None,
257            }
258        })?;
259
260        self.rename_path_expr(import_node.clone(), import_path, src, has_path_var)
261    }
262
263    fn rename_path_expr(
264        &mut self,
265        node: LinkedNode,
266        path: ast::Expr,
267        src: &Source,
268        has_path_var: bool,
269    ) -> Option<TextEdit> {
270        let new_text = match path {
271            ast::Expr::Str(s) => {
272                if !self.inserted.insert(s.span()) {
273                    return None;
274                }
275
276                let old_str = s.get();
277                let old_path = Path::new(old_str.as_str());
278                let new_path = old_path.join(&self.diff).clean();
279                let new_str = unix_slash(&new_path);
280
281                let path_part = Str::from(new_str).repr();
282                let need_alias = new_path.file_name() != old_path.file_name();
283
284                if has_path_var && need_alias {
285                    let alias = old_path.file_stem()?.to_str()?;
286                    format!("{path_part} as {alias}")
287                } else {
288                    path_part.to_string()
289                }
290            }
291            _ => return None,
292        };
293
294        let import_path_range = node.find(path.span())?.range();
295        let range = self.ctx.to_lsp_range(import_path_range, src);
296
297        Some(TextEdit { range, new_text })
298    }
299}
300
301pub(crate) fn edits_to_document_changes(
302    edits: HashMap<Url, Vec<TextEdit>>,
303) -> Vec<DocumentChangeOperation> {
304    let mut document_changes = vec![];
305
306    for (uri, edits) in edits {
307        document_changes.push(lsp_types::DocumentChangeOperation::Edit(TextDocumentEdit {
308            text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
309            edits: edits.into_iter().map(OneOf::Left).collect(),
310        }));
311    }
312
313    document_changes
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use crate::tests::*;
320
321    #[test]
322    fn test() {
323        snapshot_testing("rename", &|ctx, path| {
324            let source = ctx.source_by_path(&path).unwrap();
325
326            let request = RenameRequest {
327                path: path.clone(),
328                position: find_test_position(&source),
329                new_name: "new_name".to_string(),
330            };
331
332            let mut result = request.request(ctx);
333            // sort the edits to make the snapshot stable
334            if let Some(r) = result.as_mut().and_then(|r| r.changes.as_mut()) {
335                for edits in r.values_mut() {
336                    edits.sort_by(|a, b| {
337                        a.range
338                            .start
339                            .cmp(&b.range.start)
340                            .then(a.range.end.cmp(&b.range.end))
341                    });
342                }
343            };
344
345            assert_snapshot!(JsonRepr::new_redacted(result, &REDACT_LOC));
346        });
347    }
348}