tinymist-query 0.14.20-rc1

Language queries for tinymist.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use lsp_types::{
    AnnotatedTextEdit, ChangeAnnotation, DocumentChangeOperation, DocumentChanges, OneOf,
    OptionalVersionedTextDocumentIdentifier, RenameFile, TextDocumentEdit,
};
use rustc_hash::FxHashSet;
use tinymist_std::path::{PathClean, unix_slash};
use typst::{
    foundations::{Repr, Str},
    syntax::Span,
};

use crate::adt::interner::Interned;
use crate::{
    analysis::{LinkObject, LinkTarget, get_link_exprs},
    find_references,
    prelude::*,
    prepare_renaming,
    syntax::{Decl, RefExpr, SyntaxClass, first_ancestor_expr, get_index_info, node_ancestors},
};

/// The [`textDocument/rename`] request is sent from the client to the server to
/// ask the server to compute a workspace change so that the client can perform
/// a workspace-wide rename of a symbol.
///
/// [`textDocument/rename`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_rename
#[derive(Debug, Clone)]
pub struct RenameRequest {
    /// The path of the document to request for.
    pub path: PathBuf,
    /// The source code position to request for.
    pub position: LspPosition,
    /// The new name to rename to.
    pub new_name: String,
}

impl SemanticRequest for RenameRequest {
    type Response = WorkspaceEdit;

    fn request(self, ctx: &mut LocalContext) -> Option<Self::Response> {
        let source = ctx.source_by_path(&self.path).ok()?;
        let syntax = ctx.classify_for_decl(&source, self.position)?;

        let def = ctx.def_of_syntax(&source, syntax.clone())?;

        prepare_renaming(&syntax, &def)?;

        match syntax {
            // todo: abs path
            SyntaxClass::ImportPath(path) | SyntaxClass::IncludePath(path) => {
                let ref_path_str = path.cast::<ast::Str>()?.get();
                let new_path_str = if !self.new_name.ends_with(".typ") {
                    self.new_name + ".typ"
                } else {
                    self.new_name
                };

                let def_fid = def.file_id()?;
                // todo: rename in untitled files
                let old_path = ctx.path_for_id(def_fid).ok()?.to_err().ok()?;

                let new_path = Path::new(new_path_str.as_str());
                let rename_loc = Path::new(ref_path_str.as_str());
                let diff = tinymist_std::path::diff(new_path, rename_loc)?;
                if diff.is_absolute() {
                    log::info!(
                        "bad rename: absolute path, base: {rename_loc:?}, new: {new_path:?}, diff: {diff:?}"
                    );
                    return None;
                }

                let new_path = old_path.join(&diff).clean();

                let old_uri = path_to_url(&old_path).ok()?;
                let new_uri = path_to_url(&new_path).ok()?;

                let mut edits: HashMap<Url, Vec<TextEdit>> = HashMap::new();
                do_rename_file(ctx, def_fid, diff, &mut edits);

                let mut document_changes = edits_to_document_changes(edits, None);

                document_changes.push(lsp_types::DocumentChangeOperation::Op(
                    lsp_types::ResourceOp::Rename(RenameFile {
                        old_uri,
                        new_uri,
                        options: None,
                        annotation_id: None,
                    }),
                ));

                // todo: validate: workspace.workspaceEdit.resourceOperations
                Some(WorkspaceEdit {
                    document_changes: Some(DocumentChanges::Operations(document_changes)),
                    ..Default::default()
                })
            }
            _ => {
                let is_label = matches!(def.decl.kind(), DefKind::Reference);
                let references = find_references(ctx, &source, syntax)?;

                let mut edits = HashMap::new();

                for loc in references {
                    let uri = loc.uri;
                    let range = loc.range;
                    let edits = edits.entry(uri).or_insert_with(Vec::new);
                    edits.push(TextEdit {
                        range,
                        new_text: self.new_name.clone(),
                    });
                }

                crate::log_debug_ct!("rename edits: {edits:?}");

                if !is_label {
                    Some(WorkspaceEdit {
                        changes: Some(edits),
                        ..Default::default()
                    })
                } else {
                    let change_id = "Typst Rename Labels";

                    let document_changes = edits_to_document_changes(edits, Some(change_id));

                    let change_annotations = Some(create_change_annotation(
                        change_id,
                        true,
                        Some("The language server fuzzy searched the labels".to_string()),
                    ));

                    Some(WorkspaceEdit {
                        document_changes: Some(DocumentChanges::Operations(document_changes)),
                        change_annotations,
                        ..Default::default()
                    })
                }
            }
        }
    }
}

pub(crate) fn do_rename_file(
    ctx: &mut LocalContext,
    def_fid: TypstFileId,
    diff: PathBuf,
    edits: &mut HashMap<Url, Vec<TextEdit>>,
) -> Option<()> {
    let def_path = def_fid
        .vpath()
        .as_rooted_path()
        .file_name()
        .unwrap_or_default()
        .to_str()
        .unwrap_or_default()
        .into();
    let mut worker = RenameFileWorker {
        ctx,
        def_fid,
        def_path,
        diff,
        inserted: FxHashSet::default(),
    };
    worker.work(edits)
}

fn link_path_matches_def(def_fid: TypstFileId, file_id: TypstFileId, path: &str) -> bool {
    // Compare package and vpath so we avoid allocating a joined file id while
    // still distinguishing package files that share the same internal path.
    file_id.package() == def_fid.package() && file_id.vpath().join(path) == *def_fid.vpath()
}

struct RenameFileWorker<'a> {
    ctx: &'a mut LocalContext,
    def_fid: TypstFileId,
    def_path: Interned<str>,
    diff: PathBuf,
    inserted: FxHashSet<Span>,
}

impl RenameFileWorker<'_> {
    pub(crate) fn work(&mut self, edits: &mut HashMap<Url, Vec<TextEdit>>) -> Option<()> {
        let dep = self.ctx.module_dependencies().get(&self.def_fid).cloned();
        if let Some(dep) = dep {
            for ref_fid in dep.dependents.iter() {
                self.refs_in_file(*ref_fid, edits);
            }
        }

        for ref_fid in self.ctx.source_files().clone() {
            self.links_in_file(ref_fid, edits);
        }

        Some(())
    }

    fn refs_in_file(
        &mut self,
        ref_fid: TypstFileId,
        edits: &mut HashMap<Url, Vec<TextEdit>>,
    ) -> Option<()> {
        let ref_src = self.ctx.source_by_id(ref_fid).ok()?;
        let uri = self.ctx.uri_for_id(ref_fid).ok()?;

        let import_info = self.ctx.expr_stage(&ref_src);

        let edits = edits.entry(uri).or_default();
        for (span, r) in &import_info.resolves {
            if !matches!(
                r.decl.as_ref(),
                Decl::ImportPath(..) | Decl::IncludePath(..) | Decl::PathStem(..)
            ) {
                continue;
            }

            if let Some(edit) = self.rename_module_path(*span, r, &ref_src) {
                edits.push(edit);
            }
        }

        Some(())
    }

    fn links_in_file(
        &mut self,
        ref_fid: TypstFileId,
        edits: &mut HashMap<Url, Vec<TextEdit>>,
    ) -> Option<()> {
        let ref_src = self.ctx.source_by_id(ref_fid).ok()?;

        let index = get_index_info(&ref_src);
        if !index.paths.contains(&self.def_path) {
            return Some(());
        }

        let uri = self.ctx.uri_for_id(ref_fid).ok()?;

        let link_info = get_link_exprs(&ref_src);
        let root = LinkedNode::new(ref_src.root());
        let edits = edits.entry(uri).or_default();
        for obj in &link_info.objects {
            if !matches!(&obj.target,
                LinkTarget::Path(file_id, path) if link_path_matches_def(self.def_fid, *file_id, path.as_ref())
            ) {
                continue;
            }
            if let Some(edit) = self.rename_resource_path(obj, &root, &ref_src) {
                edits.push(edit);
            }
        }

        Some(())
    }

    fn rename_resource_path(
        &mut self,
        obj: &LinkObject,
        root: &LinkedNode,
        src: &Source,
    ) -> Option<TextEdit> {
        let r = root.find(obj.span)?;
        self.rename_path_expr(r.clone(), r.cast()?, src, false)
    }

    fn rename_module_path(&mut self, span: Span, r: &RefExpr, src: &Source) -> Option<TextEdit> {
        let importing = r.root.as_ref()?.file_id();

        if importing != Some(self.def_fid) {
            return None;
        }
        crate::log_debug_ct!("import: {span:?} -> {importing:?} v.s. {:?}", self.def_fid);
        // rename_importer(self.ctx, &ref_src, *span, &self.diff, edits);

        let root = LinkedNode::new(src.root());
        let import_node = root.find(span).and_then(first_ancestor_expr)?;
        let (import_path, has_path_var) = node_ancestors(&import_node).find_map(|import_node| {
            match import_node.cast::<ast::Expr>()? {
                ast::Expr::ModuleImport(import) => Some((
                    import.source(),
                    import.new_name().is_none() && import.imports().is_none(),
                )),
                ast::Expr::ModuleInclude(include) => Some((include.source(), false)),
                _ => None,
            }
        })?;

        self.rename_path_expr(import_node.clone(), import_path, src, has_path_var)
    }

    fn rename_path_expr(
        &mut self,
        node: LinkedNode,
        path: ast::Expr,
        src: &Source,
        has_path_var: bool,
    ) -> Option<TextEdit> {
        let new_text = match path {
            ast::Expr::Str(s) => {
                if !self.inserted.insert(s.span()) {
                    return None;
                }

                let old_str = s.get();
                let old_path = Path::new(old_str.as_str());
                let new_path = old_path.join(&self.diff).clean();
                let new_str = unix_slash(&new_path);

                let path_part = Str::from(new_str).repr();
                let need_alias = new_path.file_name() != old_path.file_name();

                if has_path_var && need_alias {
                    let alias = old_path.file_stem()?.to_str()?;
                    format!("{path_part} as {alias}")
                } else {
                    path_part.to_string()
                }
            }
            _ => return None,
        };

        let import_path_range = node.find(path.span())?.range();
        let range = self.ctx.to_lsp_range(import_path_range, src);

        Some(TextEdit { range, new_text })
    }
}

pub(crate) fn edits_to_document_changes(
    edits: HashMap<Url, Vec<TextEdit>>,
    change_id: Option<&str>,
) -> Vec<DocumentChangeOperation> {
    let mut document_changes = vec![];

    for (uri, edits) in edits {
        document_changes.push(lsp_types::DocumentChangeOperation::Edit(TextDocumentEdit {
            text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
            edits: edits
                .into_iter()
                .map(|edit| match change_id {
                    Some(change_id) => OneOf::Right(AnnotatedTextEdit {
                        text_edit: edit,
                        annotation_id: change_id.to_owned(),
                    }),
                    None => OneOf::Left(edit),
                })
                .collect(),
        }));
    }

    document_changes
}

pub(crate) fn create_change_annotation(
    label: &str,
    needs_confirmation: bool,
    description: Option<String>,
) -> HashMap<String, ChangeAnnotation> {
    let mut change_annotations = HashMap::new();
    change_annotations.insert(
        label.to_owned(),
        ChangeAnnotation {
            label: label.to_owned(),
            needs_confirmation: Some(needs_confirmation),
            description,
        },
    );

    change_annotations
}

#[cfg(test)]
mod tests {
    use std::{path::Path, str::FromStr};

    use super::*;
    use crate::tests::*;
    use tinymist_world::package::PackageSpec;
    use typst::syntax::VirtualPath;

    #[test]
    fn test() {
        snapshot_testing("rename", &|ctx, path| {
            let source = ctx.source_by_path(&path).unwrap();

            let request = RenameRequest {
                path: path.clone(),
                position: find_test_position(&source),
                new_name: "new_name".to_string(),
            };

            let mut result = request.request(ctx);
            // sort the edits to make the snapshot stable
            if let Some(r) = result.as_mut().and_then(|r| r.changes.as_mut()) {
                for edits in r.values_mut() {
                    edits.sort_by(|a, b| {
                        a.range
                            .start
                            .cmp(&b.range.start)
                            .then(a.range.end.cmp(&b.range.end))
                    });
                }
            };

            assert_snapshot!(JsonRepr::new_redacted(result, &REDACT_LOC));
        });
    }

    #[test]
    fn link_path_match_requires_same_package_spec() {
        let package_v010 = PackageSpec::from_str("@preview/example:0.1.0").unwrap();
        let package_v011 = PackageSpec::from_str("@preview/example:0.1.1").unwrap();
        let def_fid = TypstFileId::new(
            Some(package_v010.clone()),
            VirtualPath::new(Path::new("/assets/logo.typ")),
        );
        let same_package_ref = TypstFileId::new(
            Some(package_v010),
            VirtualPath::new(Path::new("/docs/main.typ")),
        );
        let other_package_ref = TypstFileId::new(
            Some(package_v011),
            VirtualPath::new(Path::new("/docs/main.typ")),
        );

        assert!(link_path_matches_def(
            def_fid,
            same_package_ref,
            "../assets/logo.typ"
        ));
        assert!(!link_path_matches_def(
            def_fid,
            other_package_ref,
            "../assets/logo.typ"
        ));
    }
}