tinymist_query/
rename.rs

1use lsp_types::{
2    AnnotatedTextEdit, ChangeAnnotation, DocumentChangeOperation, DocumentChanges, OneOf,
3    OptionalVersionedTextDocumentIdentifier, 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, None);
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 is_label = matches!(def.decl.kind(), DefKind::Reference);
98                let references = find_references(ctx, &source, syntax)?;
99
100                let mut edits = HashMap::new();
101
102                for loc in references {
103                    let uri = loc.uri;
104                    let range = loc.range;
105                    let edits = edits.entry(uri).or_insert_with(Vec::new);
106                    edits.push(TextEdit {
107                        range,
108                        new_text: self.new_name.clone(),
109                    });
110                }
111
112                crate::log_debug_ct!("rename edits: {edits:?}");
113
114                if !is_label {
115                    Some(WorkspaceEdit {
116                        changes: Some(edits),
117                        ..Default::default()
118                    })
119                } else {
120                    let change_id = "Typst Rename Labels";
121
122                    let document_changes = edits_to_document_changes(edits, Some(change_id));
123
124                    let change_annotations = Some(create_change_annotation(
125                        change_id,
126                        true,
127                        Some("The language server fuzzy searched the labels".to_string()),
128                    ));
129
130                    Some(WorkspaceEdit {
131                        document_changes: Some(DocumentChanges::Operations(document_changes)),
132                        change_annotations,
133                        ..Default::default()
134                    })
135                }
136            }
137        }
138    }
139}
140
141pub(crate) fn do_rename_file(
142    ctx: &mut LocalContext,
143    def_fid: TypstFileId,
144    diff: PathBuf,
145    edits: &mut HashMap<Url, Vec<TextEdit>>,
146) -> Option<()> {
147    let def_path = def_fid
148        .vpath()
149        .as_rooted_path()
150        .file_name()
151        .unwrap_or_default()
152        .to_str()
153        .unwrap_or_default()
154        .into();
155    let mut worker = RenameFileWorker {
156        ctx,
157        def_fid,
158        def_path,
159        diff,
160        inserted: FxHashSet::default(),
161    };
162    worker.work(edits)
163}
164
165fn link_path_matches_def(def_fid: TypstFileId, file_id: TypstFileId, path: &str) -> bool {
166    // Compare package and vpath so we avoid allocating a joined file id while
167    // still distinguishing package files that share the same internal path.
168    file_id.package() == def_fid.package() && file_id.vpath().join(path) == *def_fid.vpath()
169}
170
171struct RenameFileWorker<'a> {
172    ctx: &'a mut LocalContext,
173    def_fid: TypstFileId,
174    def_path: Interned<str>,
175    diff: PathBuf,
176    inserted: FxHashSet<Span>,
177}
178
179impl RenameFileWorker<'_> {
180    pub(crate) fn work(&mut self, edits: &mut HashMap<Url, Vec<TextEdit>>) -> Option<()> {
181        let dep = self.ctx.module_dependencies().get(&self.def_fid).cloned();
182        if let Some(dep) = dep {
183            for ref_fid in dep.dependents.iter() {
184                self.refs_in_file(*ref_fid, edits);
185            }
186        }
187
188        for ref_fid in self.ctx.source_files().clone() {
189            self.links_in_file(ref_fid, edits);
190        }
191
192        Some(())
193    }
194
195    fn refs_in_file(
196        &mut self,
197        ref_fid: TypstFileId,
198        edits: &mut HashMap<Url, Vec<TextEdit>>,
199    ) -> Option<()> {
200        let ref_src = self.ctx.source_by_id(ref_fid).ok()?;
201        let uri = self.ctx.uri_for_id(ref_fid).ok()?;
202
203        let import_info = self.ctx.expr_stage(&ref_src);
204
205        let edits = edits.entry(uri).or_default();
206        for (span, r) in &import_info.resolves {
207            if !matches!(
208                r.decl.as_ref(),
209                Decl::ImportPath(..) | Decl::IncludePath(..) | Decl::PathStem(..)
210            ) {
211                continue;
212            }
213
214            if let Some(edit) = self.rename_module_path(*span, r, &ref_src) {
215                edits.push(edit);
216            }
217        }
218
219        Some(())
220    }
221
222    fn links_in_file(
223        &mut self,
224        ref_fid: TypstFileId,
225        edits: &mut HashMap<Url, Vec<TextEdit>>,
226    ) -> Option<()> {
227        let ref_src = self.ctx.source_by_id(ref_fid).ok()?;
228
229        let index = get_index_info(&ref_src);
230        if !index.paths.contains(&self.def_path) {
231            return Some(());
232        }
233
234        let uri = self.ctx.uri_for_id(ref_fid).ok()?;
235
236        let link_info = get_link_exprs(&ref_src);
237        let root = LinkedNode::new(ref_src.root());
238        let edits = edits.entry(uri).or_default();
239        for obj in &link_info.objects {
240            if !matches!(&obj.target,
241                LinkTarget::Path(file_id, path) if link_path_matches_def(self.def_fid, *file_id, path.as_ref())
242            ) {
243                continue;
244            }
245            if let Some(edit) = self.rename_resource_path(obj, &root, &ref_src) {
246                edits.push(edit);
247            }
248        }
249
250        Some(())
251    }
252
253    fn rename_resource_path(
254        &mut self,
255        obj: &LinkObject,
256        root: &LinkedNode,
257        src: &Source,
258    ) -> Option<TextEdit> {
259        let r = root.find(obj.span)?;
260        self.rename_path_expr(r.clone(), r.cast()?, src, false)
261    }
262
263    fn rename_module_path(&mut self, span: Span, r: &RefExpr, src: &Source) -> Option<TextEdit> {
264        let importing = r.root.as_ref()?.file_id();
265
266        if importing != Some(self.def_fid) {
267            return None;
268        }
269        crate::log_debug_ct!("import: {span:?} -> {importing:?} v.s. {:?}", self.def_fid);
270        // rename_importer(self.ctx, &ref_src, *span, &self.diff, edits);
271
272        let root = LinkedNode::new(src.root());
273        let import_node = root.find(span).and_then(first_ancestor_expr)?;
274        let (import_path, has_path_var) = node_ancestors(&import_node).find_map(|import_node| {
275            match import_node.cast::<ast::Expr>()? {
276                ast::Expr::ModuleImport(import) => Some((
277                    import.source(),
278                    import.new_name().is_none() && import.imports().is_none(),
279                )),
280                ast::Expr::ModuleInclude(include) => Some((include.source(), false)),
281                _ => None,
282            }
283        })?;
284
285        self.rename_path_expr(import_node.clone(), import_path, src, has_path_var)
286    }
287
288    fn rename_path_expr(
289        &mut self,
290        node: LinkedNode,
291        path: ast::Expr,
292        src: &Source,
293        has_path_var: bool,
294    ) -> Option<TextEdit> {
295        let new_text = match path {
296            ast::Expr::Str(s) => {
297                if !self.inserted.insert(s.span()) {
298                    return None;
299                }
300
301                let old_str = s.get();
302                let old_path = Path::new(old_str.as_str());
303                let new_path = old_path.join(&self.diff).clean();
304                let new_str = unix_slash(&new_path);
305
306                let path_part = Str::from(new_str).repr();
307                let need_alias = new_path.file_name() != old_path.file_name();
308
309                if has_path_var && need_alias {
310                    let alias = old_path.file_stem()?.to_str()?;
311                    format!("{path_part} as {alias}")
312                } else {
313                    path_part.to_string()
314                }
315            }
316            _ => return None,
317        };
318
319        let import_path_range = node.find(path.span())?.range();
320        let range = self.ctx.to_lsp_range(import_path_range, src);
321
322        Some(TextEdit { range, new_text })
323    }
324}
325
326pub(crate) fn edits_to_document_changes(
327    edits: HashMap<Url, Vec<TextEdit>>,
328    change_id: Option<&str>,
329) -> Vec<DocumentChangeOperation> {
330    let mut document_changes = vec![];
331
332    for (uri, edits) in edits {
333        document_changes.push(lsp_types::DocumentChangeOperation::Edit(TextDocumentEdit {
334            text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
335            edits: edits
336                .into_iter()
337                .map(|edit| match change_id {
338                    Some(change_id) => OneOf::Right(AnnotatedTextEdit {
339                        text_edit: edit,
340                        annotation_id: change_id.to_owned(),
341                    }),
342                    None => OneOf::Left(edit),
343                })
344                .collect(),
345        }));
346    }
347
348    document_changes
349}
350
351pub(crate) fn create_change_annotation(
352    label: &str,
353    needs_confirmation: bool,
354    description: Option<String>,
355) -> HashMap<String, ChangeAnnotation> {
356    let mut change_annotations = HashMap::new();
357    change_annotations.insert(
358        label.to_owned(),
359        ChangeAnnotation {
360            label: label.to_owned(),
361            needs_confirmation: Some(needs_confirmation),
362            description,
363        },
364    );
365
366    change_annotations
367}
368
369#[cfg(test)]
370mod tests {
371    use std::{path::Path, str::FromStr};
372
373    use super::*;
374    use crate::tests::*;
375    use tinymist_world::package::PackageSpec;
376    use typst::syntax::VirtualPath;
377
378    #[test]
379    fn test() {
380        snapshot_testing("rename", &|ctx, path| {
381            let source = ctx.source_by_path(&path).unwrap();
382
383            let request = RenameRequest {
384                path: path.clone(),
385                position: find_test_position(&source),
386                new_name: "new_name".to_string(),
387            };
388
389            let mut result = request.request(ctx);
390            // sort the edits to make the snapshot stable
391            if let Some(r) = result.as_mut().and_then(|r| r.changes.as_mut()) {
392                for edits in r.values_mut() {
393                    edits.sort_by(|a, b| {
394                        a.range
395                            .start
396                            .cmp(&b.range.start)
397                            .then(a.range.end.cmp(&b.range.end))
398                    });
399                }
400            };
401
402            assert_snapshot!(JsonRepr::new_redacted(result, &REDACT_LOC));
403        });
404    }
405
406    #[test]
407    fn link_path_match_requires_same_package_spec() {
408        let package_v010 = PackageSpec::from_str("@preview/example:0.1.0").unwrap();
409        let package_v011 = PackageSpec::from_str("@preview/example:0.1.1").unwrap();
410        let def_fid = TypstFileId::new(
411            Some(package_v010.clone()),
412            VirtualPath::new(Path::new("/assets/logo.typ")),
413        );
414        let same_package_ref = TypstFileId::new(
415            Some(package_v010),
416            VirtualPath::new(Path::new("/docs/main.typ")),
417        );
418        let other_package_ref = TypstFileId::new(
419            Some(package_v011),
420            VirtualPath::new(Path::new("/docs/main.typ")),
421        );
422
423        assert!(link_path_matches_def(
424            def_fid,
425            same_package_ref,
426            "../assets/logo.typ"
427        ));
428        assert!(!link_path_matches_def(
429            def_fid,
430            other_package_ref,
431            "../assets/logo.typ"
432        ));
433    }
434}