editor_lsp_test_context.rs

  1use std::{
  2    borrow::Cow,
  3    ops::{Deref, DerefMut, Range},
  4    sync::Arc,
  5};
  6
  7use anyhow::Result;
  8use serde_json::json;
  9
 10use crate::{Editor, ToPoint};
 11use collections::HashSet;
 12use futures::Future;
 13use gpui::{View, ViewContext, VisualTestContext};
 14use indoc::indoc;
 15use language::{
 16    point_to_lsp, FakeLspAdapter, Language, LanguageConfig, LanguageMatcher, LanguageQueries,
 17};
 18use lsp::{notification, request};
 19use multi_buffer::ToPointUtf16;
 20use project::Project;
 21use smol::stream::StreamExt;
 22use workspace::{AppState, Workspace, WorkspaceHandle};
 23
 24use super::editor_test_context::{AssertionContextManager, EditorTestContext};
 25
 26pub struct EditorLspTestContext {
 27    pub cx: EditorTestContext,
 28    pub lsp: lsp::FakeLanguageServer,
 29    pub workspace: View<Workspace>,
 30    pub buffer_lsp_url: lsp::Url,
 31}
 32
 33impl EditorLspTestContext {
 34    pub async fn new(
 35        language: Language,
 36        capabilities: lsp::ServerCapabilities,
 37        cx: &mut gpui::TestAppContext,
 38    ) -> EditorLspTestContext {
 39        let app_state = cx.update(AppState::test);
 40
 41        cx.update(|cx| {
 42            assets::Assets.load_test_fonts(cx);
 43            language::init(cx);
 44            crate::init(cx);
 45            workspace::init(app_state.clone(), cx);
 46            Project::init_settings(cx);
 47        });
 48
 49        let file_name = format!(
 50            "file.{}",
 51            language
 52                .path_suffixes()
 53                .first()
 54                .expect("language must have a path suffix for EditorLspTestContext")
 55        );
 56
 57        let project = Project::test(app_state.fs.clone(), [], cx).await;
 58
 59        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 60        let mut fake_servers = language_registry.register_fake_lsp(
 61            language.name(),
 62            FakeLspAdapter {
 63                capabilities,
 64                ..Default::default()
 65            },
 66        );
 67        language_registry.add(Arc::new(language));
 68
 69        app_state
 70            .fs
 71            .as_fake()
 72            .insert_tree("/root", json!({ "dir": { file_name.clone(): "" }}))
 73            .await;
 74
 75        let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
 76
 77        let workspace = window.root_view(cx).unwrap();
 78
 79        let mut cx = VisualTestContext::from_window(*window.deref(), cx);
 80        project
 81            .update(&mut cx, |project, cx| {
 82                project.find_or_create_worktree("/root", true, cx)
 83            })
 84            .await
 85            .unwrap();
 86        cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
 87            .await;
 88        let file = cx.read(|cx| workspace.file_project_paths(cx)[0].clone());
 89        let item = workspace
 90            .update(&mut cx, |workspace, cx| {
 91                workspace.open_path(file, None, true, cx)
 92            })
 93            .await
 94            .expect("Could not open test file");
 95        let editor = cx.update(|cx| {
 96            item.act_as::<Editor>(cx)
 97                .expect("Opened test file wasn't an editor")
 98        });
 99        editor.update(&mut cx, |editor, cx| editor.focus(cx));
100
101        let lsp = fake_servers.next().await.unwrap();
102        Self {
103            cx: EditorTestContext {
104                cx,
105                window: window.into(),
106                editor,
107                assertion_cx: AssertionContextManager::new(),
108            },
109            lsp,
110            workspace,
111            buffer_lsp_url: lsp::Url::from_file_path(format!("/root/dir/{file_name}")).unwrap(),
112        }
113    }
114
115    pub async fn new_rust(
116        capabilities: lsp::ServerCapabilities,
117        cx: &mut gpui::TestAppContext,
118    ) -> EditorLspTestContext {
119        let language = Language::new(
120            LanguageConfig {
121                name: "Rust".into(),
122                matcher: LanguageMatcher {
123                    path_suffixes: vec!["rs".to_string()],
124                    ..Default::default()
125                },
126                ..Default::default()
127            },
128            Some(tree_sitter_rust::LANGUAGE.into()),
129        )
130        .with_queries(LanguageQueries {
131            indents: Some(Cow::from(indoc! {r#"
132                [
133                    ((where_clause) _ @end)
134                    (field_expression)
135                    (call_expression)
136                    (assignment_expression)
137                    (let_declaration)
138                    (let_chain)
139                    (await_expression)
140                ] @indent
141
142                (_ "[" "]" @end) @indent
143                (_ "<" ">" @end) @indent
144                (_ "{" "}" @end) @indent
145                (_ "(" ")" @end) @indent"#})),
146            brackets: Some(Cow::from(indoc! {r#"
147                ("(" @open ")" @close)
148                ("[" @open "]" @close)
149                ("{" @open "}" @close)
150                ("<" @open ">" @close)
151                ("\"" @open "\"" @close)
152                (closure_parameters "|" @open "|" @close)"#})),
153            ..Default::default()
154        })
155        .expect("Could not parse queries");
156
157        Self::new(language, capabilities, cx).await
158    }
159
160    pub async fn new_typescript(
161        capabilities: lsp::ServerCapabilities,
162        cx: &mut gpui::TestAppContext,
163    ) -> EditorLspTestContext {
164        let mut word_characters: HashSet<char> = Default::default();
165        word_characters.insert('$');
166        word_characters.insert('#');
167        let language = Language::new(
168            LanguageConfig {
169                name: "Typescript".into(),
170                matcher: LanguageMatcher {
171                    path_suffixes: vec!["ts".to_string()],
172                    ..Default::default()
173                },
174                brackets: language::BracketPairConfig {
175                    pairs: vec![language::BracketPair {
176                        start: "{".to_string(),
177                        end: "}".to_string(),
178                        close: true,
179                        surround: true,
180                        newline: true,
181                    }],
182                    disabled_scopes_by_bracket_ix: Default::default(),
183                },
184                word_characters,
185                ..Default::default()
186            },
187            Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
188        )
189        .with_queries(LanguageQueries {
190            brackets: Some(Cow::from(indoc! {r#"
191                ("(" @open ")" @close)
192                ("[" @open "]" @close)
193                ("{" @open "}" @close)
194                ("<" @open ">" @close)
195                ("\"" @open "\"" @close)"#})),
196            indents: Some(Cow::from(indoc! {r#"
197                [
198                    (call_expression)
199                    (assignment_expression)
200                    (member_expression)
201                    (lexical_declaration)
202                    (variable_declaration)
203                    (assignment_expression)
204                    (if_statement)
205                    (for_statement)
206                ] @indent
207
208                (_ "[" "]" @end) @indent
209                (_ "<" ">" @end) @indent
210                (_ "{" "}" @end) @indent
211                (_ "(" ")" @end) @indent
212                "#})),
213            ..Default::default()
214        })
215        .expect("Could not parse queries");
216
217        Self::new(language, capabilities, cx).await
218    }
219
220    pub async fn new_html(cx: &mut gpui::TestAppContext) -> Self {
221        let language = Language::new(
222            LanguageConfig {
223                name: "HTML".into(),
224                matcher: LanguageMatcher {
225                    path_suffixes: vec!["html".into()],
226                    ..Default::default()
227                },
228                block_comment: Some(("<!-- ".into(), " -->".into())),
229                word_characters: ['-'].into_iter().collect(),
230                ..Default::default()
231            },
232            Some(tree_sitter_html::language()),
233        );
234        Self::new(language, Default::default(), cx).await
235    }
236
237    // Constructs lsp range using a marked string with '[', ']' range delimiters
238    pub fn lsp_range(&mut self, marked_text: &str) -> lsp::Range {
239        let ranges = self.ranges(marked_text);
240        self.to_lsp_range(ranges[0].clone())
241    }
242
243    pub fn to_lsp_range(&mut self, range: Range<usize>) -> lsp::Range {
244        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
245        let start_point = range.start.to_point(&snapshot.buffer_snapshot);
246        let end_point = range.end.to_point(&snapshot.buffer_snapshot);
247
248        self.editor(|editor, cx| {
249            let buffer = editor.buffer().read(cx);
250            let start = point_to_lsp(
251                buffer
252                    .point_to_buffer_offset(start_point, cx)
253                    .unwrap()
254                    .1
255                    .to_point_utf16(&buffer.read(cx)),
256            );
257            let end = point_to_lsp(
258                buffer
259                    .point_to_buffer_offset(end_point, cx)
260                    .unwrap()
261                    .1
262                    .to_point_utf16(&buffer.read(cx)),
263            );
264
265            lsp::Range { start, end }
266        })
267    }
268
269    pub fn to_lsp(&mut self, offset: usize) -> lsp::Position {
270        let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
271        let point = offset.to_point(&snapshot.buffer_snapshot);
272
273        self.editor(|editor, cx| {
274            let buffer = editor.buffer().read(cx);
275            point_to_lsp(
276                buffer
277                    .point_to_buffer_offset(point, cx)
278                    .unwrap()
279                    .1
280                    .to_point_utf16(&buffer.read(cx)),
281            )
282        })
283    }
284
285    pub fn update_workspace<F, T>(&mut self, update: F) -> T
286    where
287        F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
288    {
289        self.workspace.update(&mut self.cx.cx, update)
290    }
291
292    pub fn handle_request<T, F, Fut>(
293        &self,
294        mut handler: F,
295    ) -> futures::channel::mpsc::UnboundedReceiver<()>
296    where
297        T: 'static + request::Request,
298        T::Params: 'static + Send,
299        F: 'static + Send + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut,
300        Fut: 'static + Send + Future<Output = Result<T::Result>>,
301    {
302        let url = self.buffer_lsp_url.clone();
303        self.lsp.handle_request::<T, _, _>(move |params, cx| {
304            let url = url.clone();
305            handler(url, params, cx)
306        })
307    }
308
309    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
310        self.lsp.notify::<T>(params);
311    }
312}
313
314impl Deref for EditorLspTestContext {
315    type Target = EditorTestContext;
316
317    fn deref(&self) -> &Self::Target {
318        &self.cx
319    }
320}
321
322impl DerefMut for EditorLspTestContext {
323    fn deref_mut(&mut self) -> &mut Self::Target {
324        &mut self.cx
325    }
326}